From bda25479aa7e73c90bc77b7c7219eaa411af138e Mon Sep 17 00:00:00 2001 From: Mark Aaron Shirley Date: Wed, 10 Apr 2013 08:44:54 -0700 Subject: Update docs with allow_add_remove --- docs/api-guide/serializers.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 42e81cad..aeb33916 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -244,15 +244,15 @@ This allows you to write views that update or create multiple items when a `PUT` Bulk updates will update any instances that already exist, and create new instances for data items that do not have a corresponding instance. -When performing a bulk update you may want any items that are not present in the incoming data to be deleted. To do so, pass `allow_delete=True` to the serializer. +When performing a bulk update you may want any items that are not present in the incoming data to be deleted. To do so, pass `allow_add_remove=True` to the serializer. - serializer = BookSerializer(queryset, data=data, many=True, allow_delete=True) + serializer = BookSerializer(queryset, data=data, many=True, allow_add_remove=True) serializer.is_valid() # True serializer.save() # `.save()` will be called on each updated or newly created instance. # `.delete()` will be called on any other items in the `queryset`. -Passing `allow_delete=True` ensures that any update operations will completely overwrite the existing queryset, rather than simply updating any objects found in the incoming data. +Passing `allow_add_remove=True` ensures that any update operations will completely overwrite the existing queryset, rather than simply updating any objects found in the incoming data. #### How identity is determined when performing bulk updates -- cgit v1.2.3 From 7815811fe3047b5110e6993ecd72349f6f232232 Mon Sep 17 00:00:00 2001 From: Mark Aaron Shirley Date: Sun, 14 Jul 2013 18:13:37 -0700 Subject: Update nested serialization docs --- docs/api-guide/relations.md | 2 -- docs/api-guide/serializers.md | 17 ++++++++++------- 2 files changed, 10 insertions(+), 9 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 50c9bc54..21942eef 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -213,8 +213,6 @@ Nested relationships can be expressed by using serializers as fields. If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field. -Note that nested relationships are currently read-only. For read-write relationships, you should use a flat relational style. - ## Example For example, the following serializer: diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index d9c23580..23c99942 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -177,7 +177,7 @@ If a nested representation may optionally accept the `None` value you should pas 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. +Similarly if a nested representation should be a list of items, you should pass the `many=True` flag to the nested serialized. class CommentSerializer(serializers.Serializer): user = UserSerializer(required=False) @@ -185,11 +185,13 @@ Similarly if a nested representation should be a list of items, you should the ` content = serializers.CharField(max_length=200) created = serializers.DateTimeField() ---- - -**Note**: Nested serializers are only suitable for read-only representations, as there are cases where they would have ambiguous or non-obvious behavior if used when updating instances. For read-write representations you should always use a flat representation, by using one of the `RelatedField` subclasses. +Validation of nested objects will work the same as before. Errors with nested objects will be nested under the field name of the nested object. ---- + serializer = CommentSerializer(comment, data={'user': {'email': 'foobar', 'user': 'doe'}, 'content': 'baz'}) + serializer.is_valid() + # False + serializer.errors + # {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']} ## Dealing with multiple objects @@ -293,8 +295,7 @@ 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. ---- - +- # ModelSerializer Often you'll want serializer classes that map closely to model definitions. @@ -331,6 +332,8 @@ 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. +If you want to customize the way the serialization is done (e.g. using `allow_add_remove`) you'll need to define the field yourself. + ## 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: -- cgit v1.2.3 From b5dc6b61131cc36b0540133a28613c06e7f4e26a Mon Sep 17 00:00:00 2001 From: Mark Aaron Shirley Date: Sun, 14 Jul 2013 18:18:39 -0700 Subject: Fix docs typo --- docs/api-guide/serializers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 23c99942..022853ca 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -187,7 +187,7 @@ Similarly if a nested representation should be a list of items, you should pass Validation of nested objects will work the same as before. Errors with nested objects will be nested under the field name of the nested object. - serializer = CommentSerializer(comment, data={'user': {'email': 'foobar', 'user': 'doe'}, 'content': 'baz'}) + serializer = CommentSerializer(comment, data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'}) serializer.is_valid() # False serializer.errors -- cgit v1.2.3 From 5b11e23f6fb35834057fba35832a597ce443cc77 Mon Sep 17 00:00:00 2001 From: Alex Burgel Date: Wed, 5 Jun 2013 17:41:29 -0400 Subject: Add docs for collection routes --- docs/api-guide/viewsets.md | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 47e59e2b..9fa6615b 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -92,7 +92,9 @@ The default routers included with REST framework will provide routes for a stand 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` decorator will route `POST` requests. +If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@collection_link`, `@collection_action`, `@link`, or `@action` decorators. The `@collection_link` and `@link` decorator will route `GET` requests, and the `@collection_action` and `@action` decorator will route `POST` requests. + +The `@link` and `@action` decorators contain `pk` in their URL pattern and are intended for methods which require a single instance. The `@collection_link` and `@collection_action` decorators are intended for methods which operate on a collection of objects. For example: @@ -121,13 +123,20 @@ For example: 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... + @collection_link() + def recent_users(self, request): + recent_users = User.objects.all().order('-last_login') + page = self.paginate_queryset(recent_users) + serializer = self.get_pagination_serializer(page) + return Response(serializer.data) + +The 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): ... -The `@action` decorator will route `POST` requests by default, but may also accept other HTTP methods, by using the `method` argument. For example: +The `@collection_action` and `@action` decorators will route `POST` requests by default, but may also accept other HTTP methods, by using the `method` argument. For example: @action(methods=['POST', 'DELETE']) def unset_password(self, request, pk=None): -- cgit v1.2.3 From 57cf8b5fa4f62f9b58912f10536a7ae5076ce54c Mon Sep 17 00:00:00 2001 From: Alex Burgel Date: Thu, 6 Jun 2013 11:51:52 -0400 Subject: Rework extra routes doc for better readability --- docs/api-guide/viewsets.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 9fa6615b..e83487fb 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -92,7 +92,7 @@ The default routers included with REST framework will provide routes for a stand 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 `@collection_link`, `@collection_action`, `@link`, or `@action` decorators. The `@collection_link` and `@link` decorator will route `GET` requests, and the `@collection_action` and `@action` decorator will route `POST` requests. +If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@link`, `@action`, `@collection_link`, or `@collection_action` decorators. The `@link` and `@collection_link` decorators will route `GET` requests, and the `@action` and `@collection_action` decorators will route `POST` requests. The `@link` and `@action` decorators contain `pk` in their URL pattern and are intended for methods which require a single instance. The `@collection_link` and `@collection_action` decorators are intended for methods which operate on a collection of objects. @@ -136,7 +136,7 @@ The decorators can additionally take extra arguments that will be set for the ro def set_password(self, request, pk=None): ... -The `@collection_action` and `@action` decorators will route `POST` requests by default, but may also accept other HTTP methods, by using the `method` argument. For example: +The `@action` and `@collection_action` decorators will route `POST` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example: @action(methods=['POST', 'DELETE']) def unset_password(self, request, pk=None): -- cgit v1.2.3 From e14cbaf6961ad9c94deaf0417d8e8ce5ec96d0ac Mon Sep 17 00:00:00 2001 From: Alex Burgel Date: Sat, 13 Jul 2013 11:11:53 -0400 Subject: Changed collection_* decorators to list_* --- docs/api-guide/viewsets.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index e83487fb..6d6bb133 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -92,15 +92,15 @@ The default routers included with REST framework will provide routes for a stand 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`, `@action`, `@collection_link`, or `@collection_action` decorators. The `@link` and `@collection_link` decorators will route `GET` requests, and the `@action` and `@collection_action` decorators will route `POST` requests. +If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@link`, `@action`, `@list_link`, or `@list_action` decorators. The `@link` and `@list_link` decorators will route `GET` requests, and the `@action` and `@list_action` decorators will route `POST` requests. -The `@link` and `@action` decorators contain `pk` in their URL pattern and are intended for methods which require a single instance. The `@collection_link` and `@collection_action` decorators are intended for methods which operate on a collection of objects. +The `@link` and `@action` decorators contain `pk` in their URL pattern and are intended for methods which require a single instance. The `@list_link` and `@list_action` decorators are intended for methods which operate on a list of objects. For example: from django.contrib.auth.models import User from rest_framework import viewsets - from rest_framework.decorators import action + from rest_framework.decorators import action, list_link from rest_framework.response import Response from myapp.serializers import UserSerializer, PasswordSerializer @@ -123,7 +123,7 @@ For example: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - @collection_link() + @list_link() def recent_users(self, request): recent_users = User.objects.all().order('-last_login') page = self.paginate_queryset(recent_users) @@ -136,7 +136,7 @@ The decorators can additionally take extra arguments that will be set for the ro def set_password(self, request, pk=None): ... -The `@action` and `@collection_action` decorators will route `POST` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example: +The `@action` and `@list_action` decorators will route `POST` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example: @action(methods=['POST', 'DELETE']) def unset_password(self, request, pk=None): -- cgit v1.2.3 From eaae8fb2d973769a827214e0606a7e41028d5d34 Mon Sep 17 00:00:00 2001 From: Alex Burgel Date: Mon, 15 Jul 2013 18:35:13 -0400 Subject: Combined link_* and action_* decorators into detail_route and list_route, marked the originals as deprecated. --- docs/api-guide/routers.md | 16 ++++++++-------- docs/api-guide/viewsets.md | 16 ++++++++-------- 2 files changed, 16 insertions(+), 16 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 86582905..f196dc3c 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -35,12 +35,12 @@ The example above would generate the following URL patterns: * URL pattern: `^accounts/$` Name: `'account-list'` * URL pattern: `^accounts/{pk}/$` Name: `'account-detail'` -### Extra link and actions +### Registering additional routes -Any methods on the viewset decorated with `@link` or `@action` will also be routed. +Any methods on the viewset decorated with `@detail_route` or `@list_route` will also be routed. For example, a given method like this on the `UserViewSet` class: - @action(permission_classes=[IsAdminOrIsSelf]) + @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf]) def set_password(self, request, pk=None): ... @@ -52,7 +52,7 @@ The following URL pattern would additionally be generated: ## 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. +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 `@detail_route` or `@list_route` decorators. @@ -62,8 +62,8 @@ This router includes routes for the standard set of `list`, `create`, `retrieve` - - + +
URL StyleHTTP MethodActionURL Name
PUTupdate
PATCHpartial_update
DELETEdestroy
{prefix}/{lookup}/{methodname}/GET@link decorated method{basename}-{methodname}
POST@action decorated method
{prefix}/{lookup}/{methodname}/GET@detail_route decorated method{basename}-{methodname}
POST@detail_route decorated method
By default the URLs created by `SimpleRouter` are appending with a trailing slash. @@ -86,8 +86,8 @@ This router is similar to `SimpleRouter` as above, but additionally includes a d PUTupdate PATCHpartial_update DELETEdestroy - {prefix}/{lookup}/{methodname}/[.format]GET@link decorated method{basename}-{methodname} - POST@action decorated method + {prefix}/{lookup}/{methodname}/[.format]GET@detail_route decorated method{basename}-{methodname} + POST@detail_route decorated method As with `SimpleRouter` the trailing slashs on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router. diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 6d6bb133..7a8d5979 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -92,15 +92,15 @@ The default routers included with REST framework will provide routes for a stand 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`, `@action`, `@list_link`, or `@list_action` decorators. The `@link` and `@list_link` decorators will route `GET` requests, and the `@action` and `@list_action` decorators will route `POST` requests. +If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@detail_route` or `@list_route` decorators. -The `@link` and `@action` decorators contain `pk` in their URL pattern and are intended for methods which require a single instance. The `@list_link` and `@list_action` decorators are intended for methods which operate on a list of objects. +The `@detail_route` decorator contains `pk` in its URL pattern and is intended for methods which require a single instance. The `@list_route` decorator is intended for methods which operate on a list of objects. For example: from django.contrib.auth.models import User from rest_framework import viewsets - from rest_framework.decorators import action, list_link + from rest_framework.decorators import detail_route, list_route from rest_framework.response import Response from myapp.serializers import UserSerializer, PasswordSerializer @@ -111,7 +111,7 @@ For example: queryset = User.objects.all() serializer_class = UserSerializer - @action() + @detail_route(methods=['post']) def set_password(self, request, pk=None): user = self.get_object() serializer = PasswordSerializer(data=request.DATA) @@ -123,7 +123,7 @@ For example: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - @list_link() + @list_route() def recent_users(self, request): recent_users = User.objects.all().order('-last_login') page = self.paginate_queryset(recent_users) @@ -132,13 +132,13 @@ For example: The decorators can additionally take extra arguments that will be set for the routed view only. For example... - @action(permission_classes=[IsAdminOrIsSelf]) + @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf]) def set_password(self, request, pk=None): ... -The `@action` and `@list_action` decorators will route `POST` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example: +By default, the decorators will route `GET` requests, but may also accept other HTTP methods, by using the `methods` argument. For example: - @action(methods=['POST', 'DELETE']) + @detail_route(methods=['post', 'delete']) def unset_password(self, request, pk=None): ... --- -- cgit v1.2.3 From 1a4ff1567ea4231cde9a2f23725550a754f3f54c Mon Sep 17 00:00:00 2001 From: James Rutherford Date: Mon, 29 Jul 2013 10:16:15 +0100 Subject: Updated authtoken docs to mention south migrations --- docs/api-guide/authentication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index ee1282b5..fd6bfb56 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -121,7 +121,7 @@ To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in y 'rest_framework.authtoken' ) -Make sure to run `manage.py syncdb` after changing your settings. +Make sure to run `manage.py syncdb` after changing your settings. The `authtoken` database tables are managed by south (see [Schema migrations](#schema-migrations) below). You'll also need to create tokens for your users. -- cgit v1.2.3 From 195b1af7ba34b833fc17f5693d7fbd9c8e7cce78 Mon Sep 17 00:00:00 2001 From: James Rutherford Date: Mon, 29 Jul 2013 10:16:51 +0100 Subject: Minor typo fix --- docs/api-guide/authentication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index fd6bfb56..b1ab4622 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -203,7 +203,7 @@ You can do so by inserting a `needed_by` attribute in your user migration: For more details, see the [south documentation on dependencies][south-dependencies]. -Also not that if you're using a `post_save` signal to create tokens, then the first time you create the database tables, you'll need to ensure any migrations are run prior to creating any superusers. For example: +Also note that if you're using a `post_save` signal to create tokens, then the first time you create the database tables, you'll need to ensure any migrations are run prior to creating any superusers. For example: python manage.py syncdb --noinput # Won't create a superuser just yet, due to `--noinput`. python manage.py migrate -- cgit v1.2.3 From 294d957361c78cdafcef60f915738ed0e533327c Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Wed, 31 Jul 2013 20:14:49 +0200 Subject: Add drf-any-permission docs entry --- docs/api-guide/permissions.md | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 2c0a055c..57636bc6 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -188,6 +188,16 @@ Note that the generic views will check the appropriate object level permissions, Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the [filtering documentation][filtering] for more details. +--- + +# Third party packages + +The following third party packages are also available. + +## DRF Any Permissions + +The [DRF Any Permissions][drf-any-permissions] packages provides a different permission behavior in contrast to the REST framework. Only one of the given permissions have to be true in order to get access to the view. + [cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html [authentication]: authentication.md [throttling]: throttling.md @@ -197,3 +207,4 @@ Also note that the generic views will only check the object-level permissions fo [django-oauth2-provider]: https://github.com/caffeinehit/django-oauth2-provider [2.2-announcement]: ../topics/2.2-announcement.md [filtering]: filtering.md +[drf-any-permissions]: https://github.com/kevin-brown/drf-any-permissions -- cgit v1.2.3 From e61210399154723f342ab9295c938bf72c8da7a6 Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Wed, 31 Jul 2013 20:25:28 +0200 Subject: Fix typo --- docs/api-guide/permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 57636bc6..5597886d 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -196,7 +196,7 @@ The following third party packages are also available. ## DRF Any Permissions -The [DRF Any Permissions][drf-any-permissions] packages provides a different permission behavior in contrast to the REST framework. Only one of the given permissions have to be true in order to get access to the view. +The [DRF Any Permissions][drf-any-permissions] packages provides a different permission behavior in contrast to the REST framework. Only one of the given permissions has to be true in order to get access to the view. [cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html [authentication]: authentication.md -- cgit v1.2.3 From 3802442c89a722da7e48210d315856b5993fcdbe Mon Sep 17 00:00:00 2001 From: Ricky Rosario Date: Thu, 1 Aug 2013 17:02:16 -0400 Subject: Add missing comma to generic view example. --- docs/api-guide/generic-views.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 67853ed0..32a4feef 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -40,7 +40,7 @@ For more complex cases you might also want to override various methods on the vi For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something the following entry. - url(r'^/users/', ListCreateAPIView.as_view(model=User) name='user-list') + url(r'^/users/', ListCreateAPIView.as_view(model=User), name='user-list') --- -- cgit v1.2.3 From 4ff1dc6a11ec9e1fd897cf2fdb74d57be7420515 Mon Sep 17 00:00:00 2001 From: James Summerfield Date: Sat, 3 Aug 2013 10:23:39 +0100 Subject: Fixing typos in routers.md --- docs/api-guide/routers.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 86582905..7f53f109 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -38,7 +38,7 @@ The example above would generate the following URL patterns: ### Extra link and actions Any methods on the viewset decorated with `@link` or `@action` will also be routed. -For example, a given method like this on the `UserViewSet` class: +For example, given a method like this on the `UserViewSet` class: @action(permission_classes=[IsAdminOrIsSelf]) def set_password(self, request, pk=None): @@ -66,7 +66,7 @@ This router includes routes for the standard set of `list`, `create`, `retrieve` POST@action decorated method -By default the URLs created by `SimpleRouter` are appending with a trailing slash. +By default the URLs created by `SimpleRouter` are appended with a trailing slash. This behavior can be modified by setting the `trailing_slash` argument to `False` when instantiating the router. For example: router = SimpleRouter(trailing_slash=False) @@ -90,7 +90,7 @@ This router is similar to `SimpleRouter` as above, but additionally includes a d POST@action decorated method -As with `SimpleRouter` the trailing slashs on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router. +As with `SimpleRouter` the trailing slashes on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router. router = DefaultRouter(trailing_slash=False) @@ -139,7 +139,7 @@ The `SimpleRouter` class provides another example of setting the `.routes` attri ## Advanced custom routers -If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should insect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute. +If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute. You may also want to override the `get_default_base_name(self, viewset)` method, or else always explicitly set the `base_name` argument when registering your viewsets with the router. -- cgit v1.2.3 From 4d8d2340be4de905af3488dc721c7b94b1371ef0 Mon Sep 17 00:00:00 2001 From: Veronica Lynn Date: Wed, 7 Aug 2013 14:00:06 -0400 Subject: Fixed typos in a bunch of docs --- docs/api-guide/permissions.md | 2 +- docs/api-guide/relations.md | 8 ++++---- docs/api-guide/renderers.md | 2 +- docs/api-guide/responses.md | 4 ++-- docs/api-guide/reverse.md | 2 +- docs/api-guide/routers.md | 2 +- docs/api-guide/serializers.md | 6 +++--- docs/api-guide/settings.md | 4 ++-- docs/api-guide/testing.md | 2 +- docs/api-guide/views.md | 2 +- 10 files changed, 17 insertions(+), 17 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 5597886d..096ef369 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -147,7 +147,7 @@ If you need to test if a request is a read operation or a write operation, you s **Note**: In versions 2.0 and 2.1, the signature for the permission checks always included an optional `obj` parameter, like so: `.has_permission(self, request, view, obj=None)`. The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required. -As of version 2.2 this signature has now been replaced with two separate method calls, which is more explict and obvious. The old style signature continues to work, but it's use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed. +As of version 2.2 this signature has now been replaced with two separate method calls, which is more explicit and obvious. The old style signature continues to work, but its use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed. For more details see the [2.2 release announcement][2.2-announcement]. diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 50c9bc54..829a3c54 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -39,7 +39,7 @@ In order to explain the various types of relational fields, we'll use a couple o ## RelatedField -`RelatedField` may be used to represent the target of the relationship using it's `__unicode__` method. +`RelatedField` may be used to represent the target of the relationship using its `__unicode__` method. For example, the following serializer. @@ -71,7 +71,7 @@ This field is read only. ## PrimaryKeyRelatedField -`PrimaryKeyRelatedField` may be used to represent the target of the relationship using it's primary key. +`PrimaryKeyRelatedField` may be used to represent the target of the relationship using its primary key. For example, the following serializer: @@ -252,7 +252,7 @@ If you want to implement a read-write relational field, you must also implement ## Example -For, example, we could define a relational field, to serialize a track to a custom string representation, using it's ordering, title, and duration. +For, example, we could define a relational field, to serialize a track to a custom string representation, using its ordering, title, and duration. import time @@ -386,7 +386,7 @@ For more information see [the Django documentation on generic relations][generic By default, relational fields that target a ``ManyToManyField`` with a ``through`` model specified are set to read-only. -If you exlicitly specify a relational field pointing to a +If you explicitly specify a relational field pointing to a ``ManyToManyField`` with a through model, be sure to set ``read_only`` to ``True``. diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index b434efe9..bb3d2015 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -241,7 +241,7 @@ This renderer is used for rendering HTML multipart form data. **It is not suita To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, media_type=None, renderer_context=None)` method. -The method should return a bytestring, which wil be used as the body of the HTTP response. +The method should return a bytestring, which will be used as the body of the HTTP response. The arguments passed to the `.render()` method are: diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md index 399b7c23..5a42aa92 100644 --- a/docs/api-guide/responses.md +++ b/docs/api-guide/responses.md @@ -24,7 +24,7 @@ Unless you want to heavily customize REST framework for some reason, you should Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives. -The renderers used by the `Response` class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primative datatypes before creating the `Response` object. +The renderers used by the `Response` class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the `Response` object. You can use REST framework's `Serializer` classes to perform this data serialization, or use your own custom serialization. @@ -54,7 +54,7 @@ The rendered content of the response. The `.render()` method must have been cal ## .template_name -The `template_name`, if supplied. Only required if `HTMLRenderer` or some other custom template renderer is the accepted renderer for the reponse. +The `template_name`, if supplied. Only required if `HTMLRenderer` or some other custom template renderer is the accepted renderer for the response. ## .accepted_renderer diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md index 19930dc3..94262366 100644 --- a/docs/api-guide/reverse.md +++ b/docs/api-guide/reverse.md @@ -17,7 +17,7 @@ The advantages of doing so are: REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API. -There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink it's output for you, which makes browsing the API much easier. +There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier. ## reverse diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 7f53f109..072a2e79 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -96,7 +96,7 @@ As with `SimpleRouter` the trailing slashes on the URL routes can be removed by # Custom Routers -Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the your URLs for your API are strutured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view. +Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the your URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view. The simplest way to implement a custom router is to subclass one of the existing router classes. The `.routes` attribute is used to template the URL patterns that will be mapped to each viewset. The `.routes` attribute is a list of `Route` named tuples. diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index a1f0853e..bbc8d019 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -403,7 +403,7 @@ You can change the field that is used for object lookups by setting the `lookup_ Not that the `lookup_field` will be used as the default on *all* hyperlinked fields, including both the URL identity, and any hyperlinked relationships. -For more specfic requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example: +For more specific requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example: class AccountSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( @@ -429,7 +429,7 @@ You can create customized subclasses of `ModelSerializer` or `HyperlinkedModelSe Doing so should be considered advanced usage, and will only be needed if you have some particular serializer requirements that you often need to repeat. -## Dynamically modifiying fields +## Dynamically modifying fields Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the `.fields` attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer. @@ -449,7 +449,7 @@ For example, if you wanted to be able to set which fields should be used by a se # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) - # Instatiate the superclass normally + # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields: diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 7b114983..0be0eb24 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -28,7 +28,7 @@ you should use the `api_settings` object. For example. print api_settings.DEFAULT_AUTHENTICATION_CLASSES -The `api_settings` object will check for any user-defined settings, and otherwise fallback to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal. +The `api_settings` object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal. --- @@ -165,7 +165,7 @@ Default: `'multipart'` The renderer classes that are supported when building test requests. -The format of any of these renderer classes may be used when contructing a test request, for example: `client.post('/users', {'username': 'jamie'}, format='json')` +The format of any of these renderer classes may be used when constructing a test request, for example: `client.post('/users', {'username': 'jamie'}, format='json')` Default: diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index 40b07763..92f8d54a 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -34,7 +34,7 @@ To support a wider set of request formats, or change the default format, [see th #### Explicitly encoding the request body -If you need to explictly encode the request body, you can do so by setting the `content_type` flag. For example: +If you need to explicitly encode the request body, you can do so by setting the `content_type` flag. For example: request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json') diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md index 683222d1..15581e09 100644 --- a/docs/api-guide/views.md +++ b/docs/api-guide/views.md @@ -110,7 +110,7 @@ You won't typically need to override this method. ### .finalize_response(self, request, response, \*args, **kwargs) -Ensures that any `Response` object returned from the handler method will be rendered into the correct content type, as determined by the content negotation. +Ensures that any `Response` object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation. You won't typically need to override this method. -- cgit v1.2.3 From 13ca305b06a6d9bf982559640fa488f7ad31e2f8 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 16 Aug 2013 13:27:21 +0100 Subject: Tweak docs. --- docs/api-guide/permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 096ef369..c6372f98 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -196,7 +196,7 @@ The following third party packages are also available. ## DRF Any Permissions -The [DRF Any Permissions][drf-any-permissions] packages provides a different permission behavior in contrast to the REST framework. Only one of the given permissions has to be true in order to get access to the view. +The [DRF Any Permissions][drf-any-permissions] packages provides a different permission behavior in contrast to REST framework. Instead of all specified permissions being required, only one of the given permissions has to be true in order to get access to the view. [cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html [authentication]: authentication.md -- cgit v1.2.3 From 512067062419b736b65ca27bdb5663d863c775dd Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 19 Aug 2013 08:45:53 +0100 Subject: Document customizable view names/descriptions --- docs/api-guide/settings.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 0be0eb24..fe7925a5 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -274,6 +274,40 @@ Default: `['iso-8601']` --- +## View names and descriptions + +**The following settings are used to generate the view names and descriptions, as used in responses to `OPTIONS` requests, and as used in the browsable API.** + +#### VIEW_NAME_FUNCTION + +A string representing the function that should be used when generating view names. + +This should be a function with the following signature: + + view_name(cls, suffix=None) + +* `cls`: The view class. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `cls.__name__`. +* `suffix`: The optional suffix used when differentiating individual views in a viewset. + +Default: `'rest_framework.views.get_view_name'` + +#### VIEW_DESCRIPTION_FUNCTION + +A string representing the function that should be used when generating view descriptions. + +This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support `rst` markup in your view docstrings being output in the browsable API. + +This should be a function with the following signature: + + view_description(cls, html=False) + +* `cls`: The view class. Typically the description function would inspect the docstring of the class when generating a description, by accessing `cls.__doc__` +* `html`: A boolean indicating if HTML output is required. `True` when used in the browsable API, and `False` when used in generating `OPTIONS` responses. + +Default: `'rest_framework.views.get_view_description'` + +--- + ## Miscellaneous settings #### FORMAT_SUFFIX_KWARG -- cgit v1.2.3 From 4292cc18fa3e4b3f5e67c02c3780cdcbf901a0a1 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 19 Aug 2013 20:53:30 +0100 Subject: Docs tweaking --- docs/api-guide/routers.md | 11 +++++++---- docs/api-guide/viewsets.md | 2 +- 2 files changed, 8 insertions(+), 5 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 7884c2e9..c8465418 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -48,6 +48,8 @@ The following URL pattern would additionally be generated: * URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'` +For more information see the viewset documentation on [marking extra actions for routing][route-decorators]. + # API Guide ## SimpleRouter @@ -58,12 +60,12 @@ This router includes routes for the standard set of `list`, `create`, `retrieve` URL StyleHTTP MethodActionURL Name {prefix}/GETlist{basename}-list POSTcreate + {prefix}/{methodname}/GET, or as specified by `methods` argument`@list_route` decorated method{basename}-{methodname} {prefix}/{lookup}/GETretrieve{basename}-detail PUTupdate PATCHpartial_update DELETEdestroy - {prefix}/{lookup}/{methodname}/GET@detail_route decorated method{basename}-{methodname} - POST@detail_route decorated method + {prefix}/{lookup}/{methodname}/GET, or as specified by `methods` argument`@detail_route` decorated method{basename}-{methodname} By default the URLs created by `SimpleRouter` are appended with a trailing slash. @@ -82,12 +84,12 @@ This router is similar to `SimpleRouter` as above, but additionally includes a d [.format]GETautomatically generated root viewapi-root {prefix}/[.format]GETlist{basename}-list POSTcreate + {prefix}/{methodname}/[.format]GET, or as specified by `methods` argument`@list_route` decorated method{basename}-{methodname} {prefix}/{lookup}/[.format]GETretrieve{basename}-detail PUTupdate PATCHpartial_update DELETEdestroy - {prefix}/{lookup}/{methodname}/[.format]GET@detail_route decorated method{basename}-{methodname} - POST@detail_route decorated method + {prefix}/{lookup}/{methodname}/[.format]GET, or as specified by `methods` argument`@detail_route` decorated method{basename}-{methodname} As with `SimpleRouter` the trailing slashes on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router. @@ -144,3 +146,4 @@ If you want to provide totally custom behavior, you can override `BaseRouter` an 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 +[route-decorators]: viewsets.html#marking-extra-actions-for-routing \ No newline at end of file diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 95efc229..9005e7cb 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -61,7 +61,7 @@ There are two main advantages of using a `ViewSet` class over using a `View` cla 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 +## Marking extra actions 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: -- cgit v1.2.3 From 1bf712341508b5d9aa07fb62f55b7e495278fabf Mon Sep 17 00:00:00 2001 From: Filipe Ximenes Date: Tue, 20 Aug 2013 16:24:13 -0300 Subject: improving documentation about object level permissions #1049 --- docs/api-guide/generic-views.md | 5 ++++- docs/api-guide/permissions.md | 7 +++++++ 2 files changed, 11 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 32a4feef..2a585f9c 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -108,7 +108,10 @@ For example: filter = {} for field in self.multiple_lookup_fields: filter[field] = self.kwargs[field] - return get_object_or_404(queryset, **filter) + + obj = get_object_or_404(queryset, **filter) + self.check_object_permissions(self.request, obj) + return obj #### `get_serializer_class(self)` diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index c6372f98..bb7343af 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -28,6 +28,13 @@ 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. +For example: + + def get_object(self): + obj = get_object_or_404(self.get_queryset()) + self.check_object_permissions(self.request, obj) + return obj + ## Setting the permission policy The default permission policy may be set globally, using the `DEFAULT_PERMISSION_CLASSES` setting. For example. -- cgit v1.2.3 From 5e40e50f2b187fe2ff2e8ee63b4e39ece42f1521 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 21 Aug 2013 19:46:09 +0100 Subject: Include import paths throughout docs. Closes #1051. Thanks to @pydanny for the report. --- docs/api-guide/authentication.md | 14 ++++++++++++++ docs/api-guide/content-negotiation.md | 6 ++++++ docs/api-guide/fields.md | 13 ++++++++----- docs/api-guide/filtering.md | 14 ++++++++++++++ docs/api-guide/generic-views.md | 5 +++++ docs/api-guide/pagination.md | 7 ++++++- docs/api-guide/parsers.md | 4 ++++ docs/api-guide/permissions.md | 6 ++++++ docs/api-guide/relations.md | 11 ++++++----- docs/api-guide/renderers.md | 9 +++++++-- docs/api-guide/reverse.md | 4 ++-- docs/api-guide/routers.md | 7 +++++++ docs/api-guide/serializers.md | 7 +++++++ docs/api-guide/status-codes.md | 1 + docs/api-guide/testing.md | 21 ++++++++++++++++++--- docs/api-guide/throttling.md | 4 ++++ docs/api-guide/viewsets.md | 9 +++++++++ 17 files changed, 124 insertions(+), 18 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index b1ab4622..f30b16ed 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -46,6 +46,11 @@ The default authentication schemes may be set globally, using the `DEFAULT_AUTHE You can also set the authentication scheme on a per-view or per-viewset basis, using the `APIView` class based views. + from rest_framework.authentication import SessionAuthentication, BasicAuthentication + from rest_framework.permissions import IsAuthenticated + from rest_framework.response import Response + from rest_framework.views import APIView + class ExampleView(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) @@ -157,11 +162,16 @@ The `curl` command line tool may be useful for testing token authenticated APIs. If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal. + from django.dispatch import receiver + from rest_framework.authtoken.models import Token + @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) +Note that you'll want to ensure you place this code snippet in an installed `models.py` module, or some other location that will be imported by Django on startup. + If you've already created some users, you can generate tokens for all existing users like this: from django.contrib.auth.models import User @@ -336,6 +346,10 @@ If the `.authenticate_header()` method is not overridden, the authentication sch The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'. + from django.contrib.auth.models import User + from rest_framework import authentication + from rest_framework import exceptions + class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('X_USERNAME') diff --git a/docs/api-guide/content-negotiation.md b/docs/api-guide/content-negotiation.md index 2a774278..94dd59ca 100644 --- a/docs/api-guide/content-negotiation.md +++ b/docs/api-guide/content-negotiation.md @@ -54,6 +54,8 @@ The `select_renderer()` method should return a two-tuple of (renderer instance, The following is a custom content negotiation class which ignores the client request when selecting the appropriate parser or renderer. + from rest_framework.negotiation import BaseContentNegotiation + class IgnoreClientContentNegotiation(BaseContentNegotiation): def select_parser(self, request, parsers): """ @@ -77,6 +79,10 @@ The default content negotiation class may be set globally, using the `DEFAULT_CO You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class based views. + from myapp.negotiation import IgnoreClientContentNegotiation + from rest_framework.response import Response + from rest_framework.views import APIView + class NoNegotiationView(APIView): """ An example view that does not perform content negotiation. diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index d69730c9..962c49e2 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -78,6 +78,9 @@ A generic, **read-only** field. You can use this field for any attribute that d For example, using the following model. + from django.db import models + from django.utils.timezone import now + class Account(models.Model): owner = models.ForeignKey('auth.user') name = models.CharField(max_length=100) @@ -85,13 +88,14 @@ For example, using the following model. payment_expiry = models.DateTimeField() def has_expired(self): - now = datetime.datetime.now() - return now > self.payment_expiry + return now() > self.payment_expiry A serializer definition that looked like this: + from rest_framework import serializers + class AccountSerializer(serializers.HyperlinkedModelSerializer): - expired = Field(source='has_expired') + expired = serializers.Field(source='has_expired') class Meta: fields = ('url', 'owner', 'name', 'expired') @@ -125,12 +129,11 @@ The `ModelField` class is generally intended for internal use, but can be used b 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 + from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): - days_since_joined = serializers.SerializerMethodField('get_days_since_joined') class Meta: diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 05c997a3..649462da 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -20,6 +20,10 @@ You can do so by filtering based on the value of `request.user`. For example: + from myapp.models import Purchase + from myapp.serializers import PurchaseSerializer + from rest_framework import generics + class PurchaseList(generics.ListAPIView) serializer_class = PurchaseSerializer @@ -90,6 +94,11 @@ The default filter backends may be set globally, using the `DEFAULT_FILTER_BACKE You can also set the filter backends on a per-view, or per-viewset basis, using the `GenericAPIView` class based views. + from django.contrib.auth.models import User + from myapp.serializers import UserSerializer + from rest_framework import filters + from rest_framework import generics + class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer = UserSerializer @@ -150,6 +159,11 @@ This will automatically create a `FilterSet` class for the given fields, and wil For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view. For example: + import django_filters + from myapp.models import Product + from myapp.serializers import ProductSerializer + from rest_framework import generics + class ProductFilter(django_filters.FilterSet): min_price = django_filters.NumberFilter(lookup_type='gte') max_price = django_filters.NumberFilter(lookup_type='lte') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 32a4feef..7f754df8 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -17,6 +17,11 @@ 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. + from django.contrib.auth.models import User + from myapp.serializers import UserSerializer + from rest_framework import generics + from rest_framework.permissions import IsAdminUser + class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 912ce41b..ca0174b7 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -13,6 +13,7 @@ REST framework includes a `PaginationSerializer` class that makes it easy to ret Let's start by taking a look at an example from the Django documentation. from django.core.paginator import Paginator + objects = ['john', 'paul', 'george', 'ringo'] paginator = Paginator(objects, 2) page = paginator.page(1) @@ -22,6 +23,7 @@ Let's start by taking a look at an example from the Django documentation. At this point we've got a page object. If we wanted to return this page object as a JSON response, we'd need to provide the client with context such as next and previous links, so that it would be able to page through the remaining results. from rest_framework.pagination import PaginationSerializer + serializer = PaginationSerializer(instance=page) serializer.data # {'count': 4, 'next': '?page=2', 'previous': None, 'results': [u'john', u'paul']} @@ -114,6 +116,9 @@ You can also override the name used for the object list field, by setting the `r For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this. + from rest_framework import pagination + from rest_framework import serializers + class LinksSerializer(serializers.Serializer): next = pagination.NextPageField(source='*') prev = pagination.PreviousPageField(source='*') @@ -135,7 +140,7 @@ To have your custom pagination serializer be used by default, use the `DEFAULT_P 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): + class PaginatedListView(generics.ListAPIView): model = ExampleModel pagination_serializer_class = CustomPaginationSerializer paginate_by = 10 diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 5bd79a31..d3c42b1c 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -37,6 +37,10 @@ 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, or viewset, using the `APIView` class based views. + from rest_framework.parsers import YAMLParser + from rest_framework.response import Response + from rest_framework.views import APIView + class ExampleView(APIView): """ A view that can accept POST requests with YAML content. diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index c6372f98..a3d86ed4 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -47,6 +47,10 @@ If not specified, this setting defaults to allowing unrestricted access: You can also set the authentication policy on a per-view, or per-viewset basis, using the `APIView` class based views. + from rest_framework.permissions import IsAuthenticated + from rest_framework.responses import Response + from rest_framework.views import APIView + class ExampleView(APIView): permission_classes = (IsAuthenticated,) @@ -157,6 +161,8 @@ For more details see the [2.2 release announcement][2.2-announcement]. The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted. + from rest_framework import permissions + class BlacklistPermission(permissions.BasePermission): """ Global permission check for blacklisted IPs. diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 829a3c54..aa14bc72 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -76,7 +76,7 @@ This field is read only. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): - tracks = PrimaryKeyRelatedField(many=True, read_only=True) + tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Album @@ -110,8 +110,8 @@ By default this field is read-write, although you can change this behavior using For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): - tracks = HyperlinkedRelatedField(many=True, read_only=True, - view_name='track-detail') + tracks = serializers.HyperlinkedRelatedField(many=True, read_only=True, + view_name='track-detail') class Meta: model = Album @@ -148,7 +148,8 @@ By default this field is read-write, although you can change this behavior using For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): - tracks = SlugRelatedField(many=True, read_only=True, slug_field='title') + tracks = serializers.SlugRelatedField(many=True, read_only=True, + slug_field='title') class Meta: model = Album @@ -183,7 +184,7 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer: class AlbumSerializer(serializers.HyperlinkedModelSerializer): - track_listing = HyperlinkedIdentityField(view_name='track-list') + track_listing = serializers.HyperlinkedIdentityField(view_name='track-list') class Meta: model = Album diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index bb3d2015..7fc1fc1f 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -30,11 +30,16 @@ 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, or viewset, using the `APIView` class based views. + from django.contrib.auth.models import User + from rest_framework.renderers import JSONRenderer, YAMLRenderer + from rest_framework.response import Response + from rest_framework.views import APIView + class UserCountView(APIView): """ - A view that returns the count of active users, in JSON or JSONp. + A view that returns the count of active users, in JSON or YAML. """ - renderer_classes = (JSONRenderer, JSONPRenderer) + renderer_classes = (JSONRenderer, YAMLRenderer) def get(self, request, format=None): user_count = User.objects.filter(active=True).count() diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md index 94262366..383eca4c 100644 --- a/docs/api-guide/reverse.md +++ b/docs/api-guide/reverse.md @@ -27,13 +27,13 @@ Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except t You should **include the request as a keyword argument** to the function, for example: - import datetime from rest_framework.reverse import reverse from rest_framework.views import APIView + from django.utils.timezone import now class APIRootView(APIView): def get(self, request): - year = datetime.datetime.now().year + year = now().year data = { ... 'year-summary-url': reverse('year-summary', args=[year], request=request) diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 072a2e79..fb48197e 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -14,6 +14,8 @@ REST framework adds support for automatic URL routing to Django, and provides yo Here's an example of a simple URL conf, that uses `DefaultRouter`. + from rest_framework import routers + router = routers.SimpleRouter() router.register(r'users', UserViewSet) router.register(r'accounts', AccountViewSet) @@ -40,6 +42,9 @@ The example above would generate the following URL patterns: Any methods on the viewset decorated with `@link` or `@action` will also be routed. For example, given a method like this on the `UserViewSet` class: + from myapp.permissions import IsAdminOrIsSelf + from rest_framework.decorators import action + @action(permission_classes=[IsAdminOrIsSelf]) def set_password(self, request, pk=None): ... @@ -120,6 +125,8 @@ The arguments to the `Route` named tuple are: The following example will only route to the `list` and `retrieve` actions, and does not use the trailing slash convention. + from rest_framework.routers import Route, SimpleRouter + class ReadOnlyRouter(SimpleRouter): """ A router for read-only APIs, which doesn't use trailing slashes. diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index bbc8d019..d9fd4643 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -28,6 +28,8 @@ We'll declare a serializer that we can use to serialize and deserialize `Comment Declaring a serializer looks very similar to declaring a form: + from rest_framework import serializers + class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) @@ -59,6 +61,8 @@ 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`. + from rest_framework.renderers import JSONRenderer + json = JSONRenderer().render(serializer.data) json # '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}' @@ -67,6 +71,9 @@ At this point we've translated the model instance into Python native datatypes. Deserialization is similar. First we parse a stream into Python native datatypes... + from StringIO import StringIO + from rest_framework.parsers import JSONParser + stream = StringIO(json) data = JSONParser().parse(stream) diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md index db2e059c..409f659b 100644 --- a/docs/api-guide/status-codes.md +++ b/docs/api-guide/status-codes.md @@ -9,6 +9,7 @@ Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make more code more obvious and readable. from rest_framework import status + from rest_framework.response import Response def empty_view(self): content = {'please move along': 'nothing to see here'} diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index 92f8d54a..b3880f8f 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -16,6 +16,8 @@ Extends [Django's existing `RequestFactory` class][requestfactory]. The `APIRequestFactory` class supports an almost identical API to Django's standard `RequestFactory` class. This means the that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. + from rest_framework.test import APIRequestFactory + # Using the standard RequestFactory API to create a form POST request factory = APIRequestFactory() request = factory.post('/notes/', {'title': 'new idea'}) @@ -49,6 +51,8 @@ For example, using `APIRequestFactory`, you can make a form PUT request like so: Using Django's `RequestFactory`, you'd need to explicitly encode the data yourself: + from django.test.client import encode_multipart, RequestFactory + factory = RequestFactory() data = {'title': 'remember to email dave'} content = encode_multipart('BoUnDaRyStRiNg', data) @@ -72,6 +76,12 @@ To forcibly authenticate a request, use the `force_authenticate()` method. The signature for the method is `force_authenticate(request, user=None, token=None)`. When making the call, either or both of the user and token may be set. +For example, when forcibly authenticating using a token, you might do something like the following: + + user = User.objects.get(username='olivia') + request = factory.get('/accounts/django-superstars/') + force_authenticate(request, user=user, token=user.token) + --- **Note**: When using `APIRequestFactory`, the object that is returned is Django's standard `HttpRequest`, and not REST framework's `Request` object, which is only generated once the view is called. @@ -105,6 +115,8 @@ Extends [Django's existing `Client` class][client]. The `APIClient` class supports the same request interface as `APIRequestFactory`. This means the that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. For example: + from rest_framework.test import APIClient + client = APIClient() client.post('/notes/', {'title': 'new idea'}, format='json') @@ -131,8 +143,11 @@ The `login` method is appropriate for testing APIs that use session authenticati The `credentials` method can be used to set headers that will then be included on all subsequent requests by the test client. + from rest_framework.authtoken.models import Token + from rest_framework.test import APIClient + # Include an appropriate `Authorization:` header on all requests. - token = Token.objects.get(username='lauren') + token = Token.objects.get(user__username='lauren') client = APIClient() client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) @@ -190,10 +205,10 @@ You can use any of REST framework's test case classes as you would for the regul Ensure we can create a new account object. """ url = reverse('account-list') - data = {'name': 'DabApps'} + expected = {'name': 'DabApps'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) - self.assertEqual(response.data, data) + self.assertEqual(response.data, expected) --- diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index 56f32f58..42f9c228 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -43,6 +43,10 @@ The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `mi You can also set the throttling policy on a per-view or per-viewset basis, using the `APIView` class based views. + from rest_framework.response import Response + from rest_framework.throttling import UserRateThrottle + from rest_framework.views import APIView + class ExampleView(APIView): throttle_classes = (UserRateThrottle,) diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 0c68afb0..61f9d2f8 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -19,6 +19,12 @@ Typically, rather than explicitly registering the views in a viewset in the urlc Let's define a simple viewset that can be used to list or retrieve all the users in the system. + from django.contrib.auth.models import User + from django.shortcuts import get_object_or_404 + from myapps.serializers import UserSerializer + from rest_framework import viewsets + from rest_framewor.responses import Response + class UserViewSet(viewsets.ViewSet): """ A simple ViewSet that for listing or retrieving users. @@ -41,6 +47,9 @@ If we need to, we can bind this viewset into two separate views, like so: Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. + from myapp.views import UserViewSet + from rest_framework.routers import DefaultRouter + router = DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = router.urls -- cgit v1.2.3 From cf6ae397db1353370fef05df99a8d321806a6f58 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 21 Aug 2013 19:57:30 +0100 Subject: Docs tweaking around `check_object_permissions` --- docs/api-guide/generic-views.md | 2 ++ docs/api-guide/permissions.md | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 281a0481..931cae54 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -118,6 +118,8 @@ For example: self.check_object_permissions(self.request, obj) return obj +Note that if your API doesn't include any object level permissions, you may optionally exclude the ``self.check_object_permissions, and simply return the object from the `get_object_or_404` lookup. + #### `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. diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 6b80a98c..12aa4c18 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -25,7 +25,8 @@ Object level permissions are run by REST framework's generic views when `.get_ob 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. +or if you override the `get_object` method on a generic view, then 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. For example: -- cgit v1.2.3 From ec5955101b4b15b828ac5b6fc54e8d10f2a7c64a Mon Sep 17 00:00:00 2001 From: Ramiro Morales Date: Thu, 22 Aug 2013 12:40:12 -0300 Subject: Update parsers.md s/renderers/parsers/--- docs/api-guide/parsers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index d3c42b1c..1030fcb6 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -34,7 +34,7 @@ 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, or viewset, +You can also set the parsers used for an individual view, or viewset, using the `APIView` class based views. from rest_framework.parsers import YAMLParser -- cgit v1.2.3 From dba602781355f6ee0cbc34775209cd37a52ca4d4 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 23 Aug 2013 11:27:12 +0100 Subject: Add missing period. --- docs/api-guide/testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index b3880f8f..35c1f766 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -2,7 +2,7 @@ # Testing -> Code without tests is broken as designed +> Code without tests is broken as designed. > > — [Jacob Kaplan-Moss][cite] -- cgit v1.2.3 From 436e66a42db21b52fd5e1582011d2f0f7f81f9c7 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 23 Aug 2013 16:45:55 +0100 Subject: JSON responses should not include a charset --- docs/api-guide/renderers.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 7fc1fc1f..d46d0568 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -88,7 +88,7 @@ The client may additionally include an `'indent'` media type parameter, in which **.format**: `'.json'` -**.charset**: `utf-8` +**.charset**: `None` ## UnicodeJSONRenderer @@ -110,7 +110,7 @@ Both the `JSONRenderer` and `UnicodeJSONRenderer` styles conform to [RFC 4627][r **.format**: `'.json'` -**.charset**: `utf-8` +**.charset**: `None` ## JSONPRenderer @@ -295,12 +295,15 @@ By default renderer classes are assumed to be using the `UTF-8` encoding. To us Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the `Response` class, with the `charset` attribute set on the renderer used to determine the encoding. -If the renderer returns a bytestring representing raw binary content, you should set a charset value of `None`, which will ensure the `Content-Type` header of the response will not have a `charset` value set. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string. +If the renderer returns a bytestring representing raw binary content, you should set a charset value of `None`, which will ensure the `Content-Type` header of the response will not have a `charset` value set. + +In some cases you may also want to set the `render_style` attribute to `'binary'`. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string. class JPEGRenderer(renderers.BaseRenderer): media_type = 'image/jpeg' format = 'jpg' charset = None + render_style = 'binary' def render(self, data, media_type=None, renderer_context=None): return data -- cgit v1.2.3 From c7847ebc45f38e4d735b77c54ad1a55c87242fac Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 23 Aug 2013 17:10:50 +0100 Subject: Docs for HTMLFormRenderer --- docs/api-guide/renderers.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index d46d0568..c116ceda 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -212,6 +212,18 @@ You can use `TemplateHTMLRenderer` either to return regular HTML pages using RES See also: `TemplateHTMLRenderer` +## HTMLFormRenderer + +Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing `
` tags or an submit actions, as you'll probably need those to include the desired method and URL. Also note that the `HTMLFormRenderer` does not yet support including field error messages. + +**.media_type**: `text/html` + +**.format**: `'.form'` + +**.charset**: `utf-8` + +**.template**: `'rest_framework/form.html'` + ## BrowsableAPIRenderer 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. @@ -222,6 +234,8 @@ Renders data into HTML for the Browsable API. This renderer will determine whic **.charset**: `utf-8` +**.template**: `'rest_framework/api.html'` + #### Customizing BrowsableAPIRenderer By default the response content will be rendered with the highest priority renderer apart from `BrowseableAPIRenderer`. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the `get_default_renderer()` method. For example: -- cgit v1.2.3 From 53d60543c3a5c637491aaeb887269627ce9179ab Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 25 Aug 2013 20:31:04 +0100 Subject: Add warning against HTMLFormRenderer --- docs/api-guide/renderers.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index c116ceda..657377d9 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -216,6 +216,8 @@ See also: `TemplateHTMLRenderer` Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing `` tags or an submit actions, as you'll probably need those to include the desired method and URL. Also note that the `HTMLFormRenderer` does not yet support including field error messages. +Note that the template used by the `HTMLFormRenderer` class, and the context submitted to it **may be subject to change**. If you need to use this renderer class it is advised that you either make a local copy of the class and templates, or follow the release note on REST framework upgrades closely. + **.media_type**: `text/html` **.format**: `'.form'` -- cgit v1.2.3 From afee470aca28c73fb0f107e99fdb98e5a2d5a135 Mon Sep 17 00:00:00 2001 From: Kristian Øllegaard Date: Mon, 26 Aug 2013 11:02:01 +0200 Subject: More information on how actions are mapped to URLs in viewsets --- docs/api-guide/viewsets.md | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 61f9d2f8..2e65b7a4 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -142,6 +142,10 @@ The `@action` decorator will route `POST` requests by default, but may also acce @action(methods=['POST', 'DELETE']) def unset_password(self, request, pk=None): ... + +The two new actions will then be available at the urls `^users/{pk}/set_password/$` and `^users/{pk}/unset_password/$` + + --- # API Reference -- cgit v1.2.3 From ea6eee304c230a9277fdc76f4ac91654e0019b7a Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 27 Aug 2013 12:37:55 +0100 Subject: Note 'request.session' as available on requests. --- docs/api-guide/requests.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md index 39a34fcf..0696fedf 100644 --- a/docs/api-guide/requests.md +++ b/docs/api-guide/requests.md @@ -117,7 +117,7 @@ For more information see the [browser enhancements documentation]. # Standard HttpRequest attributes -As REST framework's `Request` extends Django's `HttpRequest`, all the other standard attributes and methods are also available. For example the `request.META` dictionary is available as normal. +As REST framework's `Request` extends Django's `HttpRequest`, all the other standard attributes and methods are also available. For example the `request.META` and `request.session` dictionaries are available as normal. Note that due to implementation reasons the `Request` class does not inherit from `HttpRequest` class, but instead extends the class using composition. -- cgit v1.2.3 From 848567a0cd4f244bfe9fd68e97ae672bd259fd92 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 28 Aug 2013 12:55:49 +0100 Subject: Docs for `MAX_PAGINATE_BY` setting & view attribute. --- docs/api-guide/pagination.md | 8 +++++--- docs/api-guide/settings.md | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index ca0174b7..0829589f 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -85,11 +85,12 @@ We could now use our pagination serializer in a view like this. 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 `DEFAULT_PAGINATION_SERIALIZER_CLASS`, `PAGINATE_BY` and `PAGINATE_BY_PARAM` settings. For example. +The default pagination style may be set globally, using the `DEFAULT_PAGINATION_SERIALIZER_CLASS`, `PAGINATE_BY`, `PAGINATE_BY_PARAM`, and `MAX_PAGINATE_BY` settings. For example. REST_FRAMEWORK = { - 'PAGINATE_BY': 10, - 'PAGINATE_BY_PARAM': 'page_size' + 'PAGINATE_BY': 10, # Default to 10 + 'PAGINATE_BY_PARAM': 'page_size', # Allow client to override, using `?page_size=xxx`. + 'MAX_PAGINATE_BY': 100 # Maximum limit allowed when using `?page_size=xxx`. } You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view. @@ -99,6 +100,7 @@ You can also set the pagination style on a per-view basis, using the `ListAPIVie serializer_class = ExampleModelSerializer paginate_by = 10 paginate_by_param = 'page_size' + max_paginate_by = 100 Note that using a `paginate_by` value of `None` will turn off pagination for the view. diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index fe7925a5..542e8c5f 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -127,6 +127,35 @@ Default: `None` The name of a query parameter, which can be used by the client to override the default page size to use for pagination. If set to `None`, clients may not override the default page size. +For example, given the following settings: + + REST_FRAMEWORK = { + 'PAGINATE_BY': 10, + 'PAGINATE_BY_PARAM': 'page_size', + } + +A client would be able to modify the pagination size by using the `page_size` query parameter. For example: + + GET http://example.com/api/accounts?page_size=25 + +Default: `None` + +#### MAX_PAGINATE_BY + +The maximum page size to allow when the page size is specified by the client. If set to `None`, then no maximum limit is applied. + +For example, given the following settings: + + REST_FRAMEWORK = { + 'PAGINATE_BY': 10, + 'PAGINATE_BY_PARAM': 'page_size', + 'MAX_PAGINATE_BY': 100 + } + +A client request like the following would return a paginated list of up to 100 items. + + GET http://example.com/api/accounts?page_size=999 + Default: `None` --- -- cgit v1.2.3 From 97b52156cc0e96c2edb7e1b176838bfd9c22321a Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 28 Aug 2013 13:34:14 +0100 Subject: Added `.cache` attribute on throttles. Closes #1066. More localised than a new settings key, and more flexible in that different throttles can use different behavior. Thanks to @chicheng for the report! :) --- docs/api-guide/throttling.md | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index 42f9c228..cc469217 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -70,6 +70,13 @@ Or, if you're using the `@api_view` decorator with function based views. The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate [cache settings][cache-setting]. The default value of `LocMemCache` backend should be okay for simple setups. See Django's [cache documentation][cache-docs] for more details. +If you need to use a cache other than `'default'`, you can do so by creating a custom throttle class and setting the `cache` attribute. For example: + + class CustomAnonRateThrottle(AnonRateThrottle): + cache = get_cache('alternate') + +You'll need to rememeber to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute. + --- # API Reference -- cgit v1.2.3 From 2d37952e7872f7f69f588b02941ba6f5d739cdb6 Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Thu, 29 Aug 2013 00:50:54 +0200 Subject: Add composed-permissions entry to the api-guide. --- docs/api-guide/permissions.md | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 12aa4c18..a7bf1555 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -212,6 +212,10 @@ The following third party packages are also available. The [DRF Any Permissions][drf-any-permissions] packages provides a different permission behavior in contrast to REST framework. Instead of all specified permissions being required, only one of the given permissions has to be true in order to get access to the view. +## Composed Permissions + +The [Composed Permissions][composed-permissions] package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components. + [cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html [authentication]: authentication.md [throttling]: throttling.md @@ -222,3 +226,4 @@ The [DRF Any Permissions][drf-any-permissions] packages provides a different per [2.2-announcement]: ../topics/2.2-announcement.md [filtering]: filtering.md [drf-any-permissions]: https://github.com/kevin-brown/drf-any-permissions +[composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions -- cgit v1.2.3 From bf07b8e616bd92e4ae3c2c09b198181d7075e6bd Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 29 Aug 2013 08:53:19 +0100 Subject: Better docs for customizing dynamic routes. Refs #908 --- docs/api-guide/routers.md | 81 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 70 insertions(+), 11 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index f083b3d4..730fa876 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -123,28 +123,87 @@ The arguments to the `Route` named tuple are: **initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the `suffix` argument is reserved for identifying the viewset type, used when generating the view name and breadcrumb links. +## Customizing dynamic routes + +You can also customize how the `@list_route` and `@detail_route` decorators are routed. +To route either or both of these decorators, include a `DynamicListRoute` and/or `DynamicDetailRoute` named tuple in the `.routes` list. + +The arguments to `DynamicListRoute` and `DynamicDetailRoute` are: + +**url**: A string representing the URL to be routed. May include the same format strings as `Route`, and additionally accepts the `{methodname}` and `{methodnamehyphen}` format strings. + +**name**: The name of the URL as used in `reverse` calls. May include the following format strings: `{basename}`, `{methodname}` and `{methodnamehyphen}`. + +**initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view. + ## Example The following example will only route to the `list` and `retrieve` actions, and does not use the trailing slash convention. - from rest_framework.routers import Route, SimpleRouter + from rest_framework.routers import Route, DynamicDetailRoute, SimpleRouter - class ReadOnlyRouter(SimpleRouter): + class CustomReadOnlyRouter(SimpleRouter): """ A router for read-only APIs, which doesn't use trailing slashes. """ routes = [ - Route(url=r'^{prefix}$', - mapping={'get': 'list'}, - name='{basename}-list', - initkwargs={'suffix': 'List'}), - Route(url=r'^{prefix}/{lookup}$', - mapping={'get': 'retrieve'}, - name='{basename}-detail', - initkwargs={'suffix': 'Detail'}) + Route( + url=r'^{prefix}$', + mapping={'get': 'list'}, + name='{basename}-list', + initkwargs={'suffix': 'List'} + ), + Route( + url=r'^{prefix}/{lookup}$', + mapping={'get': 'retrieve'}, + name='{basename}-detail', + initkwargs={'suffix': 'Detail'} + ), + DynamicDetailRoute( + url=r'^{prefix}/{lookup}/{methodnamehyphen}$', + name='{basename}-{methodnamehyphen}', + initkwargs={} + ) ] -The `SimpleRouter` class provides another example of setting the `.routes` attribute. +Let's take a look at the routes our `CustomReadOnlyRouter` would generate for a simple viewset. + +`views.py`: + + class UserViewSet(viewsets.ReadOnlyModelViewSet): + """ + A viewset that provides the standard actions + """ + queryset = User.objects.all() + serializer_class = UserSerializer + lookup_field = 'username' + + @detail_route() + def group_names(self, request): + """ + Returns a list of all the group names that the given + user belongs to. + """ + user = self.get_object() + groups = user.groups.all() + return Response([group.name for group in groups]) + +`urls.py`: + + router = CustomReadOnlyRouter() + router.register('users', UserViewSet) + urlpatterns = router.urls + +The following mappings would be generated... + + + + + + +
URLHTTP MethodActionURL Name
/usersGETlistuser-list
/users/{username}GETretrieveuser-detail
/users/{username}/group-namesGETgroup_namesuser-group-names
+ +For another example of setting the `.routes` attribute, see the source code for the `SimpleRouter` class. ## Advanced custom routers -- cgit v1.2.3 From da9c17067c3150897da4cab149f12dee08768346 Mon Sep 17 00:00:00 2001 From: Brett Koonce Date: Thu, 29 Aug 2013 09:23:34 -0500 Subject: minor sp --- docs/api-guide/generic-views.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 931cae54..7185b6b6 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -73,7 +73,7 @@ The following attributes control the basic view behavior. **Pagination**: -The following attibutes are used to control pagination when used with list views. +The following attributes 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 override 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`. @@ -135,7 +135,7 @@ For example: #### `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. +Returns the page size to use with pagination. By default this uses the `paginate_by` attribute, and may be overridden by the client 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. -- cgit v1.2.3 From d0123a1385b18f25da766c177056c308fbb74b67 Mon Sep 17 00:00:00 2001 From: Kevin Brown Date: Mon, 2 Sep 2013 10:23:54 -0400 Subject: Changed DOAC documentation link --- docs/api-guide/authentication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index f30b16ed..7caeac1e 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -404,4 +404,4 @@ The [Django OAuth2 Consumer][doac] library from [Rediker Software][rediker] is a [oauthlib]: https://github.com/idan/oauthlib [doac]: https://github.com/Rediker-Software/doac [rediker]: https://github.com/Rediker-Software -[doac-rest-framework]: https://github.com/Rediker-Software/doac/blob/master/docs/markdown/integrations.md# +[doac-rest-framework]: https://github.com/Rediker-Software/doac/blob/master/docs/integrations.md# -- cgit v1.2.3 From c4cb26f73bee65b068f140f1f931ede43e41f58a Mon Sep 17 00:00:00 2001 From: Tyler Hayes Date: Wed, 4 Sep 2013 03:38:34 -0700 Subject: Tiny typo fix --- docs/api-guide/serializers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 5d7e2ac8..a3cd1d6a 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -250,7 +250,7 @@ This allows you to write views that update or create multiple items when a `PUT` serializer = BookSerializer(queryset, data=data, many=True) serializer.is_valid() # True - serialize.save() # `.save()` will be called on each updated or newly created instance. + serializer.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. -- cgit v1.2.3 From 916d8ab37da2f0c4412507710649ba0f352f29bb Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 6 Sep 2013 12:19:51 +0100 Subject: Fix typo --- docs/api-guide/relations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 15ba9a3a..5ec4b22f 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -421,7 +421,7 @@ For example, if all your object URLs used both a account and a slug in the the U 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) + return queryset.get(account=account, slug=slug) --- -- cgit v1.2.3 From b5523bcc7ddab97620fd7b49e385b44c664ca899 Mon Sep 17 00:00:00 2001 From: Andy Freeland Date: Fri, 6 Sep 2013 11:40:34 -0500 Subject: Support customizable view EXCEPTION_HANDLER Add `api_settings.EXCEPTION_HANDLER` to support custom error responses. Fixes #907. --- docs/api-guide/settings.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 542e8c5f..13f96f9a 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -25,7 +25,7 @@ If you need to access the values of REST framework's API settings in your projec you should use the `api_settings` object. For example. from rest_framework.settings import api_settings - + print api_settings.DEFAULT_AUTHENTICATION_CLASSES The `api_settings` object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal. @@ -339,6 +339,20 @@ Default: `'rest_framework.views.get_view_description'` ## Miscellaneous settings +#### EXCEPTION_HANDLER + +A string representing the function that should be used when returning a response for any given exception. If the function returns `None`, a 500 error will be raised. + +This setting can be changed to support error responses other than the default `{"detail": "Failure..."}` responses. For example, you can use it to provide API responses like `{"errors": [{"message": "Failure...", "code": ""} ...]}`. + +This should be a function with the following signature: + + exception_handler(exc) + +* `exc`: The exception. + +Default: `'rest_framework.views.exception_handler'` + #### FORMAT_SUFFIX_KWARG The name of a parameter in the URL conf that may be used to provide a format suffix. -- cgit v1.2.3 From bae0ef6b5dcb0abf2be865340e5476aeab5ce137 Mon Sep 17 00:00:00 2001 From: Andy Freeland Date: Fri, 6 Sep 2013 13:57:32 -0500 Subject: Add EXCEPTION_HANDLER docs to exception docs --- docs/api-guide/exceptions.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 8b3e50f1..fa5053df 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -30,9 +30,27 @@ Might receive an error response indicating that the `DELETE` method is not allow HTTP/1.1 405 Method Not Allowed Content-Type: application/json; charset=utf-8 Content-Length: 42 - + {"detail": "Method 'DELETE' not allowed."} +## Custom exception handling + +To implement custom exception handling (e.g. to handle additional exception classes or to override the error response format), create an exception handler function with the following signature: + + exception_handler(exc) + +* `exc`: The exception. + +If the function returns `None`, a 500 error will be raised. + +The exception handler is set globally, using the `EXCEPTION_HANDLER` setting. For example: + + 'EXCEPTION_HANDLER': 'project.app.module.function' + +If not specified, this setting defaults to the exception handler described above: + + 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' + --- # API Reference -- cgit v1.2.3 From b6c0c815aa75b3f2fe0fae3a2221e7d0e976418b Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 7 Sep 2013 20:45:43 +0100 Subject: Extra docs on custom exception handling. --- docs/api-guide/exceptions.md | 43 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 9 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index fa5053df..0c48783a 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -28,28 +28,53 @@ For example, the following request: Might receive an error response indicating that the `DELETE` method is not allowed on that resource: HTTP/1.1 405 Method Not Allowed - Content-Type: application/json; charset=utf-8 + Content-Type: application/json Content-Length: 42 {"detail": "Method 'DELETE' not allowed."} ## Custom exception handling -To implement custom exception handling (e.g. to handle additional exception classes or to override the error response format), create an exception handler function with the following signature: +You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API. - exception_handler(exc) +The function must take a single argument, which is the exception to be handled, and should either return a `Response` object, or return `None` if the exception cannot be handled. If the handler returns `None` then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response. -* `exc`: The exception. +For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so: -If the function returns `None`, a 500 error will be raised. + HTTP/1.1 405 Method Not Allowed + Content-Type: application/json + Content-Length: 62 + + {"status_code": 405, "detail": "Method 'DELETE' not allowed."} + +In order to alter the style of the response, you could write the following custom exception handler: + + from rest_framework.views import exception_handler + + def custom_exception_handler(exc): + # Call REST framework's default exception handler first, + # to get the standard error response. + response = exception_handler(exc) + + # Now add the HTTP status code to the response. + if response is not None: + response.data['status_code'] = response.status_code + + return response + +The exception handler must also be configured in your settings, using the `EXCEPTION_HANDLER` setting key. For example: -The exception handler is set globally, using the `EXCEPTION_HANDLER` setting. For example: + REST_FRAMEWORK = { + 'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler' + } - 'EXCEPTION_HANDLER': 'project.app.module.function' +If not specified, the `'EXCEPTION_HANDLER'` setting defaults to the standard exception handler provided by REST framework: -If not specified, this setting defaults to the exception handler described above: + REST_FRAMEWORK = { + 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' + } - 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' +Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the `HTTP_400_BAD_REQUEST` responses that are returned by the generic views when serializer validation fails. --- -- cgit v1.2.3 From 5970baa20112921217ae4f2c2a9f175df25922db Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 10 Sep 2013 21:00:13 +0100 Subject: Tweaks and docs to object-level model permissions. --- docs/api-guide/filtering.md | 46 +++++++++++++++++++++++++++++++++++++++++++ docs/api-guide/permissions.md | 18 ++++++++++++++++- 2 files changed, 63 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 649462da..859e8d52 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -257,6 +257,49 @@ The `ordering` attribute may be either a string or a list/tuple of strings. --- +## DjangoObjectPermissionsFilter + +The `DjangoObjectPermissionsFilter` is intended to be used together with the [`django-guardian`][guardian] package, with custom `'view'` permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission. + +This filter class must be used with views that provide either a `queryset` or a `model` attribute. + +If you're using `DjangoObjectPermissionsFilter`, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass `DjangoObjectPermissions` and add `'view'` permissions to the `perms_map` attribute. + +A complete example using both `DjangoObjectPermissionsFilter` and `DjangoObjectPermissions` might look something like this. + +**permissions.py**: + + class CustomObjectPermissions(permissions.DjangoObjectPermissions): + """ + Similar to `DjangoObjectPermissions`, but adding 'view' permissions. + """ + perms_map = { + 'GET': ['%(app_label)s.view_%(model_name)s'], + 'OPTIONS': ['%(app_label)s.view_%(model_name)s'], + 'HEAD': ['%(app_label)s.view_%(model_name)s'], + 'POST': ['%(app_label)s.add_%(model_name)s'], + 'PUT': ['%(app_label)s.change_%(model_name)s'], + 'PATCH': ['%(app_label)s.change_%(model_name)s'], + 'DELETE': ['%(app_label)s.delete_%(model_name)s'], + } + +**views.py**: + + class EventViewSet(viewsets.ModelViewSet): + """ + Viewset that only lists events if user has 'view' permissions, and only + allows operations on individual events if user has appropriate 'view', 'add', + 'change' or 'delete' permissions. + """ + queryset = Event.objects.all() + serializer = EventSerializer + filter_backends = (filters.DjangoObjectPermissionsFilter,) + permission_classes = (myapp.permissions.CustomObjectPermissions,) + +For more information on adding `'view'` permissions for models, see the [relevant section][view-permissions] of the `django-guardian` documentation, and [this blogpost][view-permissions-blogpost]. + +--- + # Custom generic filtering You can also provide your own generic filtering backend, or write an installable app for other developers to use. @@ -281,5 +324,8 @@ We could achieve the same behavior by overriding `get_queryset()` on the views, [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 +[guardian]: http://pythonhosted.org/django-guardian/ +[view-permissions]: http://pythonhosted.org/django-guardian/userguide/assign.html +[view-permissions-blogpost]: http://blog.nyaruka.com/adding-a-view-permission-to-django-models [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/permissions.md b/docs/api-guide/permissions.md index a7bf1555..871de84e 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -120,7 +120,21 @@ To use custom model permissions, override `DjangoModelPermissions` and set the ` ## DjangoModelPermissionsOrAnonReadOnly -Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API. +Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API. + +## DjangoObjectPermissions + +This permission class ties into Django's standard [object permissions framework][objectpermissions] that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as [django-guardian][guardian]. + +When applied to a view that has a `.model` property, authorization will only be granted if the user *is authenticated* and has the *relevant per-object permissions* and *relevant model permissions* assigned. + +* `POST` requests require the user to have the `add` permission on the model instance. +* `PUT` and `PATCH` requests require the user to have the `change` permission on the model instance. +* `DELETE` requests require the user to have the `delete` permission on the model instance. + +Note that `DjangoObjectPermissions` **does not** require the `django-guardian` package, and should support other object-level backends equally well. + +As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoModelPermissions` and setting the `.perms_map` property. Refer to the source code for details. Note that if you add a custom `view` permission for `GET`, `HEAD` and `OPTIONS` requests, you'll probably also want to consider adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions. ## TokenHasReadWriteScope @@ -220,7 +234,9 @@ The [Composed Permissions][composed-permissions] package provides a simple way t [authentication]: authentication.md [throttling]: throttling.md [contribauth]: https://docs.djangoproject.com/en/1.0/topics/auth/#permissions +[objectpermissions]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#handling-object-permissions [guardian]: https://github.com/lukaszb/django-guardian +[get_objects_for_user]: http://pythonhosted.org/django-guardian/api/guardian.shortcuts.html#get-objects-for-user [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 -- cgit v1.2.3 From 2a6a2013df4fcb8e09425e9fa758b91b3a23b751 Mon Sep 17 00:00:00 2001 From: Diego Ponciano Date: Wed, 11 Sep 2013 17:25:57 -0300 Subject: small typo correction on ViewSet example code --- docs/api-guide/viewsets.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 2e65b7a4..1062cb32 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -23,7 +23,7 @@ Let's define a simple viewset that can be used to list or retrieve all the users from django.shortcuts import get_object_or_404 from myapps.serializers import UserSerializer from rest_framework import viewsets - from rest_framewor.responses import Response + from rest_framework.response import Response class UserViewSet(viewsets.ViewSet): """ -- cgit v1.2.3 From 895beb89c60cea534f85b8a7749615755c4d43b5 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 12 Sep 2013 21:41:21 +0100 Subject: Note on '.model' as default only, with 'serializer_class', and 'queryset' attributes prefered. Closes #1100 --- docs/api-guide/generic-views.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 7185b6b6..dc0076df 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -69,7 +69,7 @@ The following attributes control the basic view behavior. **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. +* `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. Note that `model` is only ever used for generating a default queryset or serializer class - the `queryset` and `serializer_class` attributes are always preferred if provided. **Pagination**: -- cgit v1.2.3 From fda0c520bd3fb81c7eec06da70bb7abfed519d93 Mon Sep 17 00:00:00 2001 From: Grzegorz Kapkowski Date: Mon, 23 Sep 2013 16:10:46 +0200 Subject: Match docs to current code. --- docs/api-guide/filtering.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 859e8d52..784aa585 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -195,9 +195,9 @@ For more details on using filter sets see the [django-filter documentation][djan ## 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 `SearchFilter` 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`. +The `SearchFilter` 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() -- cgit v1.2.3 From 8a1d3275795a6eea931cb0b67465c88d745bd2b6 Mon Sep 17 00:00:00 2001 From: Doron Pearl Date: Mon, 30 Sep 2013 14:08:46 -0400 Subject: corrected doc for throttle_classes decorator the decorator actually expects an array and otherwise raise an exception.--- docs/api-guide/throttling.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index cc469217..fc1525df 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -59,7 +59,7 @@ using the `APIView` class based views. Or, if you're using the `@api_view` decorator with function based views. @api_view('GET') - @throttle_classes(UserRateThrottle) + @throttle_classes([UserRateThrottle]) def example_view(request, format=None): content = { 'status': 'request was permitted' -- cgit v1.2.3 From 42bbf6907e041d6abe773854b9aaa53eded82f4e Mon Sep 17 00:00:00 2001 From: Craig de Stigter Date: Thu, 3 Oct 2013 12:38:42 +1300 Subject: docs: add paragraph on transform_fieldname methods --- docs/api-guide/serializers.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index bbc8d019..2d3e999f 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -63,6 +63,21 @@ At this point we've translated the model instance into Python native datatypes. json # '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}' +### Customizing field representation + +Sometimes when serializing objects, you may not want to represent everything exactly the way it is in your model. + +If you need to customize the serialized value of a particular field, you can do this by creating a `transform_` method. For example if you needed to render some markdown from a text field: + + description = serializers.TextField() + description_html = serializers.TextField(source='description', read_only=True) + + def transform_description_html(self, obj, value): + from django.contrib.markup.templatetags.markup import markdown + return markdown(value) + +These methods are essentially the reverse of `validate_` (see *Validation* below.) + ## Deserializing objects Deserialization is similar. First we parse a stream into Python native datatypes... -- cgit v1.2.3 From f6301636fb52dc6e02fd55e1c07c0be0a3b4ebfd Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 3 Oct 2013 15:18:38 +0100 Subject: Drop erronous left-over bit of docs. Closes #1147 --- docs/api-guide/serializers.md | 1 - 1 file changed, 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index a3cd1d6a..6b91aa76 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -84,7 +84,6 @@ Deserialization is similar. First we parse a stream into Python native datatype # True serializer.object # - >>> serializer.deserialize('json', stream) When deserializing data, we can either create a new instance, or update an existing instance. -- cgit v1.2.3 From ab4be47379ba49092063f843fd446919534db776 Mon Sep 17 00:00:00 2001 From: Omer Katz Date: Thu, 3 Oct 2013 17:34:34 +0200 Subject: Fixed code example. --- docs/api-guide/routers.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 730fa876..f20a695b 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -42,12 +42,15 @@ The example above would generate the following URL patterns: Any methods on the viewset decorated with `@detail_route` or `@list_route` will also be routed. For example, given a method like this on the `UserViewSet` class: - from myapp.permissions import IsAdminOrIsSelf + from myapp.permissions import IsAdminOrIsSelf from rest_framework.decorators import detail_route - - @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf]) - def set_password(self, request, pk=None): + + class UserViewSet(ModelViewSet): ... + + @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf]) + def set_password(self, request, pk=None): + ... The following URL pattern would additionally be generated: -- cgit v1.2.3 From 89ac03af26a63a2126165e8995f7936798ce0450 Mon Sep 17 00:00:00 2001 From: Álvaro Lázaro Date: Sat, 12 Oct 2013 20:31:33 +0200 Subject: Add missing commas in relations.md --- docs/api-guide/relations.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 5ec4b22f..b9d96b5e 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -54,7 +54,7 @@ Would serialize to the following representation. { 'album_name': 'Things We Lost In The Fire', - 'artist': 'Low' + 'artist': 'Low', 'tracks': [ '1: Sunflower', '2: Whitetail', @@ -86,7 +86,7 @@ Would serialize to a representation like this: { 'album_name': 'The Roots', - 'artist': 'Undun' + 'artist': 'Undun', 'tracks': [ 89, 90, @@ -121,7 +121,7 @@ Would serialize to a representation like this: { 'album_name': 'Graceland', - 'artist': 'Paul Simon' + 'artist': 'Paul Simon', 'tracks': [ 'http://www.example.com/api/tracks/45/', 'http://www.example.com/api/tracks/46/', @@ -159,7 +159,7 @@ Would serialize to a representation like this: { 'album_name': 'Dear John', - 'artist': 'Loney Dear' + 'artist': 'Loney Dear', 'tracks': [ 'Airport Surroundings', 'Everything Turns to You', @@ -194,7 +194,7 @@ Would serialize to a representation like this: { 'album_name': 'The Eraser', - 'artist': 'Thom Yorke' + 'artist': 'Thom Yorke', 'track_listing': 'http://www.example.com/api/track_list/12/', } @@ -234,7 +234,7 @@ Would serialize to a nested representation like this: { 'album_name': 'The Grey Album', - 'artist': 'Danger Mouse' + 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement'}, {'order': 2, 'title': 'What More Can I Say'}, @@ -271,7 +271,7 @@ This custom field would then serialize to the following representation. { 'album_name': 'Sometimes I Wish We Were an Eagle', - 'artist': 'Bill Callahan' + 'artist': 'Bill Callahan', 'tracks': [ 'Track 1: Jim Cain (04:39)', 'Track 2: Eid Ma Clack Shaw (04:19)', -- cgit v1.2.3 From ed9c3258a6f9df6fabb569a65f3eb3363affa523 Mon Sep 17 00:00:00 2001 From: Jesús Espino Date: Mon, 21 Oct 2013 10:24:06 +0200 Subject: Remove the detail=None from APIException signature The documentation not match with the implementation. The APIException doesn't have detail parameter in the constructor class, actually doesn't have constructor method at all.--- docs/api-guide/exceptions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 0c48783a..c46d415e 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -82,7 +82,7 @@ Note that the exception handler will only be called for responses generated by r ## APIException -**Signature:** `APIException(detail=None)` +**Signature:** `APIException()` The **base class** for all exceptions raised inside REST framework. -- cgit v1.2.3 From 76672787cdba6a4ab8173b51fa099c910556889b Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 21 Oct 2013 09:47:07 +0100 Subject: Added . Closes #1188. --- docs/api-guide/generic-views.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index dc0076df..24fc0bc7 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -65,7 +65,8 @@ 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. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes use lookup fields that correctly correspond with the URL conf. +* `lookup_field` - The model field that should be used to for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value. +* `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`. **Shortcuts**: -- cgit v1.2.3 From 25c9d552c05527f4b8b257d59cd7be39005f3668 Mon Sep 17 00:00:00 2001 From: Jacek Bzdak Date: Tue, 22 Oct 2013 13:11:14 +0200 Subject: Explained a bit more about django-filter implementation. Well, I spent some time trying to gues how djang-filter works, and if this changes would be introduced, I would have saved this time. --- docs/api-guide/filtering.md | 43 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 784aa585..bcb0bb41 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -165,8 +165,8 @@ For more advanced filtering requirements you can specify a `FilterSet` class tha from rest_framework import generics class ProductFilter(django_filters.FilterSet): - min_price = django_filters.NumberFilter(lookup_type='gte') - max_price = django_filters.NumberFilter(lookup_type='lte') + min_price = django_filters.NumberFilter(name="price", lookup_type='gte') + max_price = django_filters.NumberFilter(name="price", lookup_type='lte') class Meta: model = Product fields = ['category', 'in_stock', 'min_price', 'max_price'] @@ -176,12 +176,51 @@ For more advanced filtering requirements you can specify a `FilterSet` class tha 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]. +You can also span relationships using `django-filter`, let's assume that each +product has foreign key to `Manufacturer` model, so we create filter that +filters using `Manufacturer` name. For example: + + import django_filters + from myapp.models import Product + from myapp.serializers import ProductSerializer + from rest_framework import generics + + class ProductFilter(django_filters.FilterSet): + class Meta: + model = Product + fields = ['category', 'in_stock', 'manufacturer__name`] + +This enables us to make queries like: + + http://example.com/api/products?manufacturer__name=foo + +This is nice, but it shows underlying model structure in REST API, which may +be undesired, but you can use: + + import django_filters + from myapp.models import Product + from myapp.serializers import ProductSerializer + from rest_framework import generics + + class ProductFilter(django_filters.FilterSet): + + manufacturer = django_filters.CharFilter(name="manufacturer__name") + + class Meta: + model = Product + fields = ['category', 'in_stock', 'manufacturer`] + +And now you can execute: + + http://example.com/api/products?manufacturer=foo + --- **Hints & Tips** -- cgit v1.2.3 From cc9c7cd8a479b7fa76a66b8669e4a62fd78be867 Mon Sep 17 00:00:00 2001 From: Jacek Bzdak Date: Tue, 22 Oct 2013 13:15:48 +0200 Subject: Small documentation fix --- docs/api-guide/filtering.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index bcb0bb41..a0132ffc 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -181,8 +181,6 @@ 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]. - You can also span relationships using `django-filter`, let's assume that each product has foreign key to `Manufacturer` model, so we create filter that filters using `Manufacturer` name. For example: @@ -220,6 +218,8 @@ be undesired, but you can use: And now you can execute: http://example.com/api/products?manufacturer=foo + +For more details on using filter sets see the [django-filter documentation][django-filter-docs]. --- -- cgit v1.2.3 From c92af2b1dd25acebe440f667ede3bad4906b9b28 Mon Sep 17 00:00:00 2001 From: Yamila Date: Thu, 24 Oct 2013 15:56:53 +0200 Subject: Typo on generic-views.md --- docs/api-guide/generic-views.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 24fc0bc7..9681c8c7 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -125,7 +125,7 @@ Note that if your API doesn't include any object level permissions, you may opti 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. +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 users. For example: -- cgit v1.2.3 From 82e9ddcf7a5cb5fda81e84326bb6f8181ccdffab Mon Sep 17 00:00:00 2001 From: Yamila Moreno Date: Thu, 24 Oct 2013 15:39:02 +0200 Subject: Added get_filter_backends method --- docs/api-guide/generic-views.md | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 24fc0bc7..8fedcdaa 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -121,6 +121,22 @@ For example: Note that if your API doesn't include any object level permissions, you may optionally exclude the ``self.check_object_permissions, and simply return the object from the `get_object_or_404` lookup. +#### `get_filter_backends(self)` + +Returns the classes that should be used to filter the queryset. Defaults to returning the `filter_backends` attribute. + +May be override to provide more complex behavior with filters, as using different (or even exlusive) lists of filter_backends depending on different criteria. + +For example: + + def get_filter_backends(self): + if "geo_route" in self.request.QUERY_PARAMS: + return (GeoRouteFilter, CategoryFilter) + elif "geo_point" in self.request.QUERY_PARAMS: + return (GeoPointFilter, CategoryFilter) + + return (CategoryFilter,) + #### `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. @@ -328,7 +344,7 @@ You can then simply apply this mixin to a view or viewset anytime you need to ap serializer_class = UserSerializer lookup_fields = ('account', 'username') -Using custom mixins is a good option if you have custom behavior that needs to be used +Using custom mixins is a good option if you have custom behavior that needs to be used ## Creating custom base classes @@ -337,7 +353,7 @@ If you are using a mixin across multiple views, you can take this a step further class BaseRetrieveView(MultipleFieldLookupMixin, generics.RetrieveAPIView): pass - + class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin, generics.RetrieveUpdateDestroyAPIView): pass -- cgit v1.2.3 From 7d5499bcac379a506f78fc0065ebe31c8d01240f Mon Sep 17 00:00:00 2001 From: Kit Randel Date: Fri, 25 Oct 2013 11:45:33 +1300 Subject: In the API test client example 'data' was not defined. There's also no need to define 'expected' as we can just test against the dict. --- docs/api-guide/testing.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index 35c1f766..4a8a9168 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -205,10 +205,10 @@ You can use any of REST framework's test case classes as you would for the regul Ensure we can create a new account object. """ url = reverse('account-list') - expected = {'name': 'DabApps'} + data = {'name': 'DabApps'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) - self.assertEqual(response.data, expected) + self.assertEqual(response.data, data) --- -- cgit v1.2.3 From f72488d60915f2f77234bc75ccfd604cc6a4143f Mon Sep 17 00:00:00 2001 From: erkarl Date: Thu, 31 Oct 2013 03:47:23 +0200 Subject: Updated OAuth2 authentication docs. --- docs/api-guide/authentication.md | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 7caeac1e..1a1c68b8 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -265,6 +265,12 @@ This authentication class depends on the optional [django-oauth2-provider][djang 'provider.oauth2', ) +Then add `OAuth2Authentication` to your global `DEFAULT_AUTHENTICATION` setting: + + 'DEFAULT_AUTHENTICATION_CLASSES': ( + 'rest_framework.authentication.OAuth2Authentication', + ), + You must also include the following in your root `urls.py` module: url(r'^oauth2/', include('provider.oauth2.urls', namespace='oauth2')), -- cgit v1.2.3 From fd2c291c4d9243937a31e0e6f523016067824b83 Mon Sep 17 00:00:00 2001 From: Doğan Çeçen Date: Mon, 11 Nov 2013 11:54:30 +0200 Subject: Typo on api-guide/fields.md and serializers.py --- docs/api-guide/fields.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 962c49e2..4272c9a7 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -299,9 +299,9 @@ 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 initial 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. +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 initial datatype, and a primitive, serializable datatype. Primitive 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 primitive 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. +The `.to_native()` method is called to convert the initial datatype into a primitive, serializable datatype. The `from_native()` method is called to restore a primitive datatype into it's initial representation. ## Examples -- cgit v1.2.3 From 52ac2199a8b332f7a485d5c22b1a53633b4be9dd Mon Sep 17 00:00:00 2001 From: Jacob Haslehurst Date: Mon, 11 Nov 2013 22:24:37 +1100 Subject: Added drf-ujson-renderer to renderers docs drf-ujson-renderer is a third party renderer that implements JSON renderering using UltraJSON--- docs/api-guide/renderers.md | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 657377d9..1f286ef1 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -409,6 +409,10 @@ The following third party packages are also available. Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework. +## UltraJSON + +[UltraJSON][ultrajson] is a blazing-fast C JSON encoder which can give 2-10x performance increases on typical workloads. [Jacob Haslehurst][hzy] maintains the [drf-ujson-renderer][drf-ujson-renderer] package which implements JSON rendering using the UJSON package. + [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process [conneg]: content-negotiation.md [browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers @@ -426,3 +430,6 @@ Comma-separated values are a plain-text tabular data format, that can be easily [mjumbewu]: https://github.com/mjumbewu [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack [djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv +[ultrajson]: https://github.com/esnme/ultrajson +[hzy]: https://github.com/hzy +[drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer -- cgit v1.2.3 From 128bda5712ef041514c5e2feadef0ad248f33f54 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 15 Nov 2013 15:24:32 +0000 Subject: Use less specfic language in UltaJSON notes --- docs/api-guide/renderers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 1f286ef1..858e2f07 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -411,7 +411,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily ## UltraJSON -[UltraJSON][ultrajson] is a blazing-fast C JSON encoder which can give 2-10x performance increases on typical workloads. [Jacob Haslehurst][hzy] maintains the [drf-ujson-renderer][drf-ujson-renderer] package which implements JSON rendering using the UJSON package. +[UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Jacob Haslehurst][hzy] maintains the [drf-ujson-renderer][drf-ujson-renderer] package which implements JSON rendering using the UJSON package. [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process [conneg]: content-negotiation.md -- cgit v1.2.3 From 3765865b4bf69d76d5bcb8e9c8071f4380b54177 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 20 Nov 2013 17:40:56 +0000 Subject: Update 'default' explanation. Closes #1239 --- docs/api-guide/fields.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 4272c9a7..03c5af32 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -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 behavior is to not populate the attribute at all. +If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all. May be set to a function or other callable, in which case the value will be evaluated each time it is used. -- cgit v1.2.3 From 2dce8d7a8a0e64f84994b6ac437e2d96920f094e Mon Sep 17 00:00:00 2001 From: Omer Katz Date: Wed, 27 Nov 2013 13:23:49 +0200 Subject: Recommend using Pillow instead of PIL. --- docs/api-guide/fields.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 03c5af32..b0dedd39 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -286,7 +286,7 @@ An image representation. Corresponds to `django.forms.fields.ImageField`. -Requires the `PIL` package. +Requires either the `Pillow` package or `PIL` package. It is strongly recommends to use `Pillow` where possible. `PIL` is practically unmaintained and introduces [many problems][pilproblems]. Signature and validation is the same as with `FileField`. @@ -345,3 +345,4 @@ As an example, let's create a field that can be used represent the class name of [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 +[pilproblems]: http://pillow.readthedocs.org/en/latest/about.html -- cgit v1.2.3 From c46106c96158a99eb2ff29c464a2fa60aff23122 Mon Sep 17 00:00:00 2001 From: Omer Katz Date: Wed, 27 Nov 2013 14:47:37 +0200 Subject: Rephrased documentation changes according to feedback on IRC. --- docs/api-guide/fields.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index b0dedd39..e05c0306 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -286,7 +286,7 @@ An image representation. Corresponds to `django.forms.fields.ImageField`. -Requires either the `Pillow` package or `PIL` package. It is strongly recommends to use `Pillow` where possible. `PIL` is practically unmaintained and introduces [many problems][pilproblems]. +Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained. Signature and validation is the same as with `FileField`. @@ -345,4 +345,3 @@ As an example, let's create a field that can be used represent the class name of [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 -[pilproblems]: http://pillow.readthedocs.org/en/latest/about.html -- cgit v1.2.3 From 850cd83ba709e863598f8eec3d6551ef3bc3801c Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Mon, 2 Dec 2013 11:44:04 +0100 Subject: Fix TemplateHTMLRenderer example --- docs/api-guide/renderers.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 858e2f07..f30fa26a 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -167,14 +167,14 @@ The template name is determined by (in order of preference): An example of a view that uses `TemplateHTMLRenderer`: - class UserDetail(generics.RetrieveUserAPIView): + class UserDetail(generics.RetrieveAPIView): """ A view that returns a templated HTML representations of a given user. """ queryset = User.objects.all() renderer_classes = (TemplateHTMLRenderer,) - def get(self, request, *args, **kwargs) + def get(self, request, *args, **kwargs): self.object = self.get_object() return Response({'user': self.object}, template_name='user_detail.html') -- cgit v1.2.3 From 699ec7236b326c97a98c6058280b822c701393fe Mon Sep 17 00:00:00 2001 From: Pablo Recio Date: Tue, 3 Dec 2013 00:07:41 +0000 Subject: Adds pre_delete and post_delete hooks on --- docs/api-guide/generic-views.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index b9242724..83c3e45f 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -163,12 +163,14 @@ For example: return 20 return 100 -**Save hooks**: +**Save / deletion 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. * `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. +* `pre_delete(self, obj)` - A hook that is called before deleting an object. +* `post_delete(self, obj)` - A hook that is called after deleting 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. -- cgit v1.2.3 From 3c3906e278d5e707ab1fd72bdbcb79649777df33 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 4 Dec 2013 08:51:34 +0000 Subject: Clarify wording, fixes #1133. --- docs/api-guide/viewsets.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 1062cb32..4fdd9364 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -170,7 +170,7 @@ The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, #### Example -Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: +Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes, or the `model` attribute shortcut. For example: class AccountViewSet(viewsets.ModelViewSet): """ -- cgit v1.2.3 From f2682537e0fa91bb415be1a64e6bc85275129141 Mon Sep 17 00:00:00 2001 From: Drew Kowalik Date: Wed, 4 Dec 2013 16:10:05 -0800 Subject: fix broken documentation links --- docs/api-guide/views.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md index 15581e09..194a7a6b 100644 --- a/docs/api-guide/views.md +++ b/docs/api-guide/views.md @@ -168,5 +168,5 @@ Each of these decorators takes a single argument which must be a list or tuple o [cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html [cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html -[settings]: api-guide/settings.md -[throttling]: api-guide/throttling.md +[settings]: settings.md +[throttling]: throttling.md -- cgit v1.2.3 From f8088bedef04c5bc487bdc764ac54d1f18f42c26 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 5 Dec 2013 09:01:00 +0000 Subject: Upgrade JSONP security warning. --- docs/api-guide/renderers.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index f30fa26a..cf200569 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -118,7 +118,13 @@ Renders the request data into `JSONP`. The `JSONP` media type provides a mechan The javascript callback function must be set by the client including a `callback` URL query parameter. For example `http://example.com/api/users?callback=jsonpCallback`. If the callback function is not explicitly set by the client it will default to `'callback'`. -**Note**: If you require cross-domain AJAX requests, you may want to consider using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details. +--- + +**Warning**: If you require cross-domain AJAX requests, you should almost certainly be using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details. + +The `jsonp` approach is essentially a browser hack, and is [only appropriate for globally readable API endpoints][jsonp-security], where `GET` requests are unauthenticated and do not require any user permissions. + +--- **.media_type**: `application/javascript` @@ -419,6 +425,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily [rfc4627]: http://www.ietf.org/rfc/rfc4627.txt [cors]: http://www.w3.org/TR/cors/ [cors-docs]: ../topics/ajax-csrf-cors.md +[jsonp-security]: http://stackoverflow.com/questions/613962/is-jsonp-safe-to-use [testing]: testing.md [HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas [quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven -- cgit v1.2.3 From 910de38a9c8cd03243e738c8f4adcbade8a4d7d6 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 6 Dec 2013 22:13:50 +0000 Subject: Version 2.3.10 --- docs/api-guide/status-codes.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md index 409f659b..64c46434 100644 --- a/docs/api-guide/status-codes.md +++ b/docs/api-guide/status-codes.md @@ -17,6 +17,18 @@ Using bare status codes in your responses isn't recommended. REST framework inc The full set of HTTP status codes included in the `status` module is listed below. +The module also includes a set of helper functions for testing if a status code is in a given range. + + from rest_framework import status + from rest_framework.test import APITestCase + + class ExampleTestCase(APITestCase): + def test_url_root(self): + url = reverse('index') + response = self.client.get(url) + self.assertTrue(status.is_success(response.status_code)) + + For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616] and [RFC 6585][rfc6585]. @@ -90,6 +102,15 @@ Response status codes beginning with the digit "5" indicate cases in which the s HTTP_505_HTTP_VERSION_NOT_SUPPORTED HTTP_511_NETWORK_AUTHENTICATION_REQUIRED +## Helper functions + +The following helper functions are available for identifying the category of the response code. + + is_informational() # 1xx + is_success() # 2xx + is_redirect() # 3xx + is_client_error() # 4xx + is_server_error() # 5xx [rfc2324]: http://www.ietf.org/rfc/rfc2324.txt [rfc2616]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html -- cgit v1.2.3 From 100a933279e3119e2627d744cd7eb472b542f6fe Mon Sep 17 00:00:00 2001 From: kahnjw Date: Fri, 6 Dec 2013 14:22:08 -0800 Subject: Add documentation to explain what effect these changes have. --- docs/api-guide/throttling.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index cc469217..ee57383c 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -35,11 +35,16 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/day' - } + }, + 'NUM_PROXIES': 2, } The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period. +By default Django REST Framework will try to use the `HTTP_X_FORWARDED_FOR` header to uniquely identify client machines for throttling. If HTTP_X_FORWARDED_FOR is not present `REMOTE_ADDR` header value will be used. + +To help Django REST Framework identify unique clients the number of application proxies can be set using `NUM_PROXIES`. This setting will allow the throttle to correctly identify unique requests whenthere are multiple application side proxies in front of the server. `NUM_PROXIES` should be set to an integer. It is important to understand that if you configure `NUM_PROXIES > 0` all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client. + You can also set the throttling policy on a per-view or per-viewset basis, using the `APIView` class based views. -- cgit v1.2.3 From 196c5952e4f610054e832aef36cb2383b8c129c0 Mon Sep 17 00:00:00 2001 From: kahnjw Date: Fri, 6 Dec 2013 14:24:16 -0800 Subject: Fix typo --- docs/api-guide/throttling.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index ee57383c..69b15a82 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -43,7 +43,7 @@ The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `mi By default Django REST Framework will try to use the `HTTP_X_FORWARDED_FOR` header to uniquely identify client machines for throttling. If HTTP_X_FORWARDED_FOR is not present `REMOTE_ADDR` header value will be used. -To help Django REST Framework identify unique clients the number of application proxies can be set using `NUM_PROXIES`. This setting will allow the throttle to correctly identify unique requests whenthere are multiple application side proxies in front of the server. `NUM_PROXIES` should be set to an integer. It is important to understand that if you configure `NUM_PROXIES > 0` all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client. +To help Django REST Framework identify unique clients the number of application proxies can be set using `NUM_PROXIES`. This setting will allow the throttle to correctly identify unique requests when there are multiple application side proxies in front of the server. `NUM_PROXIES` should be set to an integer. It is important to understand that if you configure `NUM_PROXIES > 0` all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client. You can also set the throttling policy on a per-view or per-viewset basis, using the `APIView` class based views. -- cgit v1.2.3 From 887da7f6c5a9e7b5007f5e4af32a6b93b18c70ea Mon Sep 17 00:00:00 2001 From: kahnjw Date: Fri, 6 Dec 2013 14:30:33 -0800 Subject: Add missing tick marks --- docs/api-guide/throttling.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index 69b15a82..34418e84 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -41,7 +41,7 @@ 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. -By default Django REST Framework will try to use the `HTTP_X_FORWARDED_FOR` header to uniquely identify client machines for throttling. If HTTP_X_FORWARDED_FOR is not present `REMOTE_ADDR` header value will be used. +By default Django REST Framework will try to use the `HTTP_X_FORWARDED_FOR` header to uniquely identify client machines for throttling. If `HTTP_X_FORWARDED_FOR` is not present `REMOTE_ADDR` header value will be used. To help Django REST Framework identify unique clients the number of application proxies can be set using `NUM_PROXIES`. This setting will allow the throttle to correctly identify unique requests when there are multiple application side proxies in front of the server. `NUM_PROXIES` should be set to an integer. It is important to understand that if you configure `NUM_PROXIES > 0` all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client. -- cgit v1.2.3 From 3399158d62416af56201eac63cc20d8934f08de2 Mon Sep 17 00:00:00 2001 From: taras Date: Sun, 8 Dec 2013 11:40:40 -0500 Subject: RelatedField is function of serializer class --- docs/api-guide/relations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index b9d96b5e..556429bb 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -44,7 +44,7 @@ In order to explain the various types of relational fields, we'll use a couple o For example, the following serializer. class AlbumSerializer(serializers.ModelSerializer): - tracks = RelatedField(many=True) + tracks = serializers.RelatedField(many=True) class Meta: model = Album -- cgit v1.2.3 From de319f3e28d27d71fffce7c8f12c23363d5c25eb Mon Sep 17 00:00:00 2001 From: Ian Date: Mon, 9 Dec 2013 09:53:16 +0000 Subject: Fix typo "Not" -> "Note" --- docs/api-guide/serializers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 4c3fb9d3..6fc25f57 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -425,7 +425,7 @@ You can change the field that is used for object lookups by setting the `lookup_ fields = ('url', 'account_name', 'users', 'created') lookup_field = 'slug' -Not that the `lookup_field` will be used as the default on *all* hyperlinked fields, including both the URL identity, and any hyperlinked relationships. +Note that the `lookup_field` will be used as the default on *all* hyperlinked fields, including both the URL identity, and any hyperlinked relationships. For more specific requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example: -- cgit v1.2.3 From 9ba7be959c2a2fea989527c590ce833df5925e63 Mon Sep 17 00:00:00 2001 From: Maxim Kamenkov Date: Mon, 9 Dec 2013 20:33:06 +0200 Subject: Added REST Condition to 3rd party permissions packages list. --- docs/api-guide/permissions.md | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 871de84e..60624b63 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -230,6 +230,10 @@ The [DRF Any Permissions][drf-any-permissions] packages provides a different per The [Composed Permissions][composed-permissions] package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components. +## REST Condition + +The [REST Condition][rest-condition] yet another but simple and convenient extension for complex permissions tree. The extension allows to combine permissions with logical operators rules. Logical expressions can be used along with the usual permissions classes in api views. + [cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html [authentication]: authentication.md [throttling]: throttling.md @@ -243,3 +247,4 @@ The [Composed Permissions][composed-permissions] package provides a simple way t [filtering]: filtering.md [drf-any-permissions]: https://github.com/kevin-brown/drf-any-permissions [composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions +[rest-condition]: https://github.com/caxap/rest_condition -- cgit v1.2.3 From 785a42cd5aee9e96f9b780ff144fa13c16189748 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 10 Dec 2013 08:38:43 +0000 Subject: Tweak REST condition text. --- docs/api-guide/permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 60624b63..6a0f48f4 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -232,7 +232,7 @@ The [Composed Permissions][composed-permissions] package provides a simple way t ## REST Condition -The [REST Condition][rest-condition] yet another but simple and convenient extension for complex permissions tree. The extension allows to combine permissions with logical operators rules. Logical expressions can be used along with the usual permissions classes in api views. +The [REST Condition][rest-condition] package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators. [cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html [authentication]: authentication.md -- cgit v1.2.3 From 7382f8c6adc17c9feb02d028f7791af632d6dd3b Mon Sep 17 00:00:00 2001 From: David Ray Date: Tue, 10 Dec 2013 14:56:07 -0500 Subject: Update routers.md Reference to ```DefaultRouter``` should be ```SimpleRouter```--- docs/api-guide/routers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index fb48197e..8151e60f 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -12,7 +12,7 @@ REST framework adds support for automatic URL routing to Django, and provides yo ## Usage -Here's an example of a simple URL conf, that uses `DefaultRouter`. +Here's an example of a simple URL conf, that uses `SimpleRouter`. from rest_framework import routers -- cgit v1.2.3 From 5acefd3b17e498af756fa48e27d7f8ce19322c7a Mon Sep 17 00:00:00 2001 From: OddBloke Date: Wed, 11 Dec 2013 13:55:54 +0000 Subject: Add full required imports to Generating Tokens example Previously we were missing User and post_save.--- docs/api-guide/authentication.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 1a1c68b8..ef77e02c 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -162,6 +162,8 @@ The `curl` command line tool may be useful for testing token authenticated APIs. If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal. + from django.contrib.auth.models import User + from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token -- cgit v1.2.3 From 4f473f0b9e918f2e071da0c84bd9b584c00ac919 Mon Sep 17 00:00:00 2001 From: OddBloke Date: Wed, 11 Dec 2013 13:56:56 +0000 Subject: Use get_user_model instead of User in Generating Tokens example Because that's a better way of doing it.--- docs/api-guide/authentication.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index ef77e02c..53efc49a 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -162,12 +162,12 @@ The `curl` command line tool may be useful for testing token authenticated APIs. If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal. - from django.contrib.auth.models import User + from django.contrib.auth import get_user_model from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token - @receiver(post_save, sender=User) + @receiver(post_save, sender=get_user_model()) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) -- cgit v1.2.3 From df2d9034c2a5a07dc3aa5455db892ee94cbed467 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 12 Dec 2013 23:10:31 +0000 Subject: Add third party packages --- docs/api-guide/filtering.md | 9 +++++++++ docs/api-guide/routers.md | 9 +++++++++ 2 files changed, 18 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index a0132ffc..0e02a2a7 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -360,6 +360,14 @@ For example, you might need to restrict users to only being able to see objects 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. +# Third party packages + +The following third party packages provide additional filter implementations. + +## Django REST framework chain + +The [django-rest-framework-chain package][django-rest-framework-chain] works together with the `DjangoFilterBackend` class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field. + [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 @@ -368,3 +376,4 @@ We could achieve the same behavior by overriding `get_queryset()` on the views, [view-permissions-blogpost]: http://blog.nyaruka.com/adding-a-view-permission-to-django-models [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 +[django-rest-framework-chain]: https://github.com/philipn/django-rest-framework-chain diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 8151e60f..9001b859 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -150,4 +150,13 @@ If you want to provide totally custom behavior, you can override `BaseRouter` an 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. +# Third Party Packages + +The following third party packages provide router implementations that extend the default functionality provided by REST framework. + +## DRF Nested Routers + +The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources. + [cite]: http://guides.rubyonrails.org/routing.html +[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers -- cgit v1.2.3 From 83da4949c099fcf7e7636c98b9052b502e1bf74b Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 13 Dec 2013 00:02:18 +0000 Subject: Allow NUM_PROXIES=0 and include more docs --- docs/api-guide/settings.md | 6 ++++++ docs/api-guide/throttling.md | 18 ++++++++++++------ 2 files changed, 18 insertions(+), 6 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 13f96f9a..d8c878ff 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -359,5 +359,11 @@ The name of a parameter in the URL conf that may be used to provide a format suf Default: `'format'` +#### NUM_PROXIES + +An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to `None` then less strict IP matching will be used by the throttle classes. + +Default: `None` + [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 34418e84..b2a5bb19 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -35,16 +35,11 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/day' - }, - 'NUM_PROXIES': 2, + } } The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period. -By default Django REST Framework will try to use the `HTTP_X_FORWARDED_FOR` header to uniquely identify client machines for throttling. If `HTTP_X_FORWARDED_FOR` is not present `REMOTE_ADDR` header value will be used. - -To help Django REST Framework identify unique clients the number of application proxies can be set using `NUM_PROXIES`. This setting will allow the throttle to correctly identify unique requests when there are multiple application side proxies in front of the server. `NUM_PROXIES` should be set to an integer. It is important to understand that if you configure `NUM_PROXIES > 0` all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client. - You can also set the throttling policy on a per-view or per-viewset basis, using the `APIView` class based views. @@ -71,6 +66,16 @@ Or, if you're using the `@api_view` decorator with function based views. } return Response(content) +## How clients are identified + +By default the `X-Forwarded-For` HTTP header is used to uniquely identify client machines for throttling. If the `X-Forwarded-For` header is not present, then the value of the `Remote-Addr` header will be used. + +If you need to more strictly identify unique clients, you'll need to configure the number of application proxies that the API runs behind by setting the `NUM_PROXIES` setting. This setting should be an integer of 0 or more, and will allow the throttle to identify the client IP as being the last IP address in the `X-Forwarded-For` header, once any application proxy IP addresses have first been excluded. + +It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client. + +Further context on how the `X-Forwarded-For` header works, and identifier a remote client IP can be [found here][identifing-clients]. + ## Setting up the cache The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate [cache settings][cache-setting]. The default value of `LocMemCache` backend should be okay for simple setups. See Django's [cache documentation][cache-docs] for more details. @@ -183,5 +188,6 @@ 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 +[identifing-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster [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 -- cgit v1.2.3 From ed931b90ae9e72f963673e6e188b1802a5a65360 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 13 Dec 2013 00:11:59 +0000 Subject: Further docs tweaks --- docs/api-guide/throttling.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index b2a5bb19..536f0ab7 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -68,13 +68,13 @@ Or, if you're using the `@api_view` decorator with function based views. ## How clients are identified -By default the `X-Forwarded-For` HTTP header is used to uniquely identify client machines for throttling. If the `X-Forwarded-For` header is not present, then the value of the `Remote-Addr` header will be used. +The `X-Forwarded-For` and `Remote-Addr` HTTP headers are used to uniquely identify client IP addresses for throttling. If the `X-Forwarded-For` header is present then it will be used, otherwise the value of the `Remote-Addr` header will be used. -If you need to more strictly identify unique clients, you'll need to configure the number of application proxies that the API runs behind by setting the `NUM_PROXIES` setting. This setting should be an integer of 0 or more, and will allow the throttle to identify the client IP as being the last IP address in the `X-Forwarded-For` header, once any application proxy IP addresses have first been excluded. +If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the `NUM_PROXIES` setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the `X-Forwarded-For` header, once any application proxy IP addresses have first been excluded. If set to zero, then the `Remote-Addr` header will always be used as the identifying IP address. It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client. -Further context on how the `X-Forwarded-For` header works, and identifier a remote client IP can be [found here][identifing-clients]. +Further context on how the `X-Forwarded-For` header works, and identifing a remote client IP can be [found here][identifing-clients]. ## Setting up the cache -- cgit v1.2.3 From 73e8536e0d38f6677ac30aa2b3ba80563961191f Mon Sep 17 00:00:00 2001 From: S. Andrew Sheppard Date: Thu, 12 Dec 2013 21:45:44 -0600 Subject: third-party package: wq.db --- docs/api-guide/routers.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 8151e60f..ed903114 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -150,4 +150,18 @@ If you want to provide totally custom behavior, you can override `BaseRouter` an 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. +# Third party packages + +The following third party packages are also available. + +## wq.db + +[wq.db] provides an advanced [Router][wq.db-router] class (and singleton instance) that extends `DefaultRouter` with a `register_model()` API. Much like Django's `admin.site.register`, the only required argument to `app.router.register_model` is a model class. Reasonable defaults for a url prefix and viewset will be inferred from the model and global configuration. + + from wq.db.rest import app + from .models import MyModel + app.router.register_model(MyModel) + [cite]: http://guides.rubyonrails.org/routing.html +[wq.db]: http://wq.io/wq.db +[wq.db-router]: http://wq.io/docs/app.py -- cgit v1.2.3 From 39dbea4da43f829863d395d5f2ee158837f2afe2 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 13 Dec 2013 20:27:17 +0000 Subject: Links to drf-nested-routers --- docs/api-guide/relations.md | 11 +++++++++++ docs/api-guide/routers.md | 4 +--- 2 files changed, 12 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 556429bb..1b089c54 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -442,7 +442,18 @@ In the 2.4 release, these parts of the API will be removed entirely. For more details see the [2.2 release announcement][2.2-announcement]. +--- + +# Third Party Packages + +The following third party packages are also available. + +## DRF Nested Routers + +The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources. + [cite]: http://lwn.net/Articles/193245/ [reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward [generic-relations]: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1 [2.2-announcement]: ../topics/2.2-announcement.md +[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 54fae65f..895589db 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -158,9 +158,6 @@ The following third party packages are also available. The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources. -[cite]: http://guides.rubyonrails.org/routing.html -[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers - ## wq.db The [wq.db package][wq.db] provides an advanced [Router][wq.db-router] class (and singleton instance) that extends `DefaultRouter` with a `register_model()` API. Much like Django's `admin.site.register`, the only required argument to `app.router.register_model` is a model class. Reasonable defaults for a url prefix and viewset will be inferred from the model and global configuration. @@ -171,5 +168,6 @@ The [wq.db package][wq.db] provides an advanced [Router][wq.db-router] class (an app.router.register_model(MyModel) [cite]: http://guides.rubyonrails.org/routing.html +[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers [wq.db]: http://wq.io/wq.db [wq.db-router]: http://wq.io/docs/app.py -- cgit v1.2.3 From 22343ee11764aac3686ad500da5c9aae30540e8e Mon Sep 17 00:00:00 2001 From: Vitaly Babiy Date: Sat, 21 Dec 2013 07:05:21 -0500 Subject: Added links to djangorestframework-camel-case in the third party sections of the docs for both parsers and renderers. --- docs/api-guide/parsers.md | 6 ++++++ docs/api-guide/renderers.md | 7 +++++++ 2 files changed, 13 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 1030fcb6..db0b666f 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -186,9 +186,15 @@ The following third party packages are also available. [MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework. +## CamelCase JSON + +[djangorestframework-camel-case] provides a camelCase JSON parser for django REST framework, its maintained by [vbabiy] + [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 +[vbabiy]: https://github.com/vbabiy [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack +[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case \ No newline at end of file diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index cf200569..673b5902 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -419,6 +419,11 @@ Comma-separated values are a plain-text tabular data format, that can be easily [UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Jacob Haslehurst][hzy] maintains the [drf-ujson-renderer][drf-ujson-renderer] package which implements JSON rendering using the UJSON package. +## CamelCase JSON + +[djangorestframework-camel-case] provides a camelCase JSON render for django REST framework, its maintained by [vbabiy] + + [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process [conneg]: content-negotiation.md [browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers @@ -435,8 +440,10 @@ Comma-separated values are a plain-text tabular data format, that can be easily [messagepack]: http://msgpack.org/ [juanriaza]: https://github.com/juanriaza [mjumbewu]: https://github.com/mjumbewu +[vbabiy]: https://github.com/vbabiy [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack [djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv [ultrajson]: https://github.com/esnme/ultrajson [hzy]: https://github.com/hzy [drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer +[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case \ No newline at end of file -- cgit v1.2.3 From 1f3ded4559ad18d03ee49b3befd19ddaea7e70b2 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 21 Dec 2013 17:18:25 +0000 Subject: Docs tweaks --- docs/api-guide/parsers.md | 2 +- docs/api-guide/renderers.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index db0b666f..72a4af64 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -188,7 +188,7 @@ The following third party packages are also available. ## CamelCase JSON -[djangorestframework-camel-case] provides a camelCase JSON parser for django REST framework, its maintained by [vbabiy] +[djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy]. [jquery-ajax]: http://api.jquery.com/jQuery.ajax/ [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 673b5902..7798827b 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -421,7 +421,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily ## CamelCase JSON -[djangorestframework-camel-case] provides a camelCase JSON render for django REST framework, its maintained by [vbabiy] +[djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy]. [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process -- cgit v1.2.3 From bc0e994784f46330b4e849c3326fbd5c500298b3 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 21 Dec 2013 21:10:05 +0000 Subject: Added example of using APIException class. Closes #1300 --- docs/api-guide/exceptions.md | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index c46d415e..221df679 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -88,6 +88,14 @@ The **base class** for all exceptions raised inside REST framework. To provide a custom exception, subclass `APIException` and set the `.status_code` and `.detail` properties on the class. +For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so: + + from rest_framework.exceptions import APIException + + class ServiceUnavailable(APIException): + status_code = 503 + detail = 'Service temporarily unavailable, try again later.' + ## ParseError **Signature:** `ParseError(detail=None)` -- cgit v1.2.3 From d24ea39a4e4131486d45492339dcbbfefb6a933b Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 23 Dec 2013 14:29:22 +0000 Subject: Added note on view_name in hyperlinked relationships. Closes #1221 --- docs/api-guide/relations.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 1b089c54..4bee75af 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -134,7 +134,7 @@ By default this field is read-write, although you can change this behavior using **Arguments**: -* `view_name` - The view name that should be used as the target of the relationship. **required**. +* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this wil be a string with the format `-detail`. **required**. * `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`. @@ -202,7 +202,7 @@ This field is always read-only. **Arguments**: -* `view_name` - The view name that should be used as the target of the relationship. **required**. +* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this wil be a string with the format `-detail`. **required**. * `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. @@ -454,6 +454,7 @@ The [drf-nested-routers package][drf-nested-routers] provides routers and relati [cite]: http://lwn.net/Articles/193245/ [reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward +[routers]: http://django-rest-framework.org/api-guide/routers#defaultrouter [generic-relations]: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1 [2.2-announcement]: ../topics/2.2-announcement.md [drf-nested-routers]: https://github.com/alanjds/drf-nested-routers -- cgit v1.2.3 From 75e872473197f9b810c9daf348cb452faadac476 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 23 Dec 2013 14:38:51 +0000 Subject: Fuller notes on the 'base_name' argument. Closes #1160. --- docs/api-guide/routers.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 895589db..7efc140a 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -37,6 +37,18 @@ The example above would generate the following URL patterns: * URL pattern: `^accounts/$` Name: `'account-list'` * URL pattern: `^accounts/{pk}/$` Name: `'account-detail'` +--- + +**Note**: The `base_name` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part. + +Typically you won't *need* to specify the `base-name` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have any `.model` or `.queryset` attribute set. If you try to register that viewset you'll see an error like this: + + 'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.model' or '.queryset' attribute. + +This means you'll need to explicitly set the `base_name` argument when registering the viewset, as it could not be automatically determined from the model name. + +--- + ### Extra link and actions Any methods on the viewset decorated with `@link` or `@action` will also be routed. -- cgit v1.2.3 From a1d7aa8f712b659f9d8302a2d2a098d2538e6c89 Mon Sep 17 00:00:00 2001 From: Paul Melnikow Date: Thu, 2 Jan 2014 17:44:47 -0500 Subject: Allow viewset to specify lookup value regex for routing This patch allows a viewset to define a pattern for its lookup field, which the router will honor. Without this patch, any characters are allowed in the lookup field, and overriding this behavior requires subclassing router and copying and pasting the implementation of get_lookup_regex. It's possible it would be better to remove this functionality from the routers and simply expose a parameter to get_lookup_regex which allows overriding the lookup_regex. That way the viewset config logic could be in the a subclass, which could invoke the super method directly. I'm using this now for PostgreSQL UUID fields using https://github.com/dcramer/django-uuidfield . Without this patch, that field passes the lookup string to the database driver, which raises a DataError to complain about the invalid UUID. It's possible the field ought to signal this error in a different way, which could obviate the need to specify a pattern. --- docs/api-guide/routers.md | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 846ac9f9..f3beabdd 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -83,6 +83,12 @@ This behavior can be modified by setting the `trailing_slash` argument to `False Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style. +With `trailing_slash` set to True, the router will match lookup values containing any characters except slashes and dots. When set to False, dots are allowed. To restrict the lookup pattern, set the `lookup_field_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs: + + class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): + lookup_field = 'my_model_id' + lookup_value_regex = '[0-9a-f]{32}' + ## 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. -- cgit v1.2.3 From 3cd15fb1713dfc49e1bf1fd48045ca3ae5654e18 Mon Sep 17 00:00:00 2001 From: Paul Melnikow Date: Sat, 4 Jan 2014 16:57:50 -0500 Subject: Router: Do not automatically adjust lookup_regex when trailing_slash is True BREAKING CHANGE When trailing_slash is set to True, the router no longer will adjust the lookup regex to allow it to include periods. To simulate the old behavior, the programmer should specify `lookup_regex = '[^/]+'` on the viewset. https://github.com/tomchristie/django-rest-framework/pull/1328#issuecomment-31517099 --- docs/api-guide/routers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index f3beabdd..6b4ae6db 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -83,7 +83,7 @@ This behavior can be modified by setting the `trailing_slash` argument to `False Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style. -With `trailing_slash` set to True, the router will match lookup values containing any characters except slashes and dots. When set to False, dots are allowed. To restrict the lookup pattern, set the `lookup_field_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs: +The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_field_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs: class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): lookup_field = 'my_model_id' -- cgit v1.2.3 From 899381575a6038f550a064261ed5c6ba0655211b Mon Sep 17 00:00:00 2001 From: Paul Melnikow Date: Sat, 4 Jan 2014 17:03:01 -0500 Subject: Fix a typo --- docs/api-guide/routers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 6b4ae6db..249e99a4 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -83,7 +83,7 @@ This behavior can be modified by setting the `trailing_slash` argument to `False Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style. -The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_field_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs: +The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs: class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): lookup_field = 'my_model_id' -- cgit v1.2.3 From 78494401c5c45d16d632bb2fa9629678e47a98bc Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 8 Jan 2014 15:22:41 +0000 Subject: Use www.django-rest-framework.org for docs instead of django-rest-framework.org due to issues with naked domains --- docs/api-guide/relations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 4bee75af..cc4f5585 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -454,7 +454,7 @@ The [drf-nested-routers package][drf-nested-routers] provides routers and relati [cite]: http://lwn.net/Articles/193245/ [reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward -[routers]: http://django-rest-framework.org/api-guide/routers#defaultrouter +[routers]: http://www.django-rest-framework.org/api-guide/routers#defaultrouter [generic-relations]: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1 [2.2-announcement]: ../topics/2.2-announcement.md [drf-nested-routers]: https://github.com/alanjds/drf-nested-routers -- cgit v1.2.3 From 052e236fde3453b33a4e651293da84e7d302cefb Mon Sep 17 00:00:00 2001 From: Yuri Prezument Date: Thu, 9 Jan 2014 18:12:30 +0200 Subject: Fix URL/Slug Field signatures in docs --- docs/api-guide/fields.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index e05c0306..91866664 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -167,13 +167,13 @@ or `django.db.models.fields.TextField`. Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation. -**Signature:** `CharField(max_length=200, min_length=None)` +**Signature:** `URLField(max_length=200, min_length=None)` ## SlugField Corresponds to `django.db.models.fields.SlugField`. -**Signature:** `CharField(max_length=50, min_length=None)` +**Signature:** `SlugField(max_length=50, min_length=None)` ## ChoiceField -- cgit v1.2.3 From 4b8d1b66ab2184166192e0c1ffea9b5f11fff8d3 Mon Sep 17 00:00:00 2001 From: Paul Melnikow Date: Fri, 10 Jan 2014 08:22:47 -0500 Subject: serializers.md: Fix typos --- docs/api-guide/serializers.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 6fc25f57..04439092 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -103,11 +103,11 @@ Deserialization is similar. First we parse a stream into Python native datatype When deserializing data, we can either create a new instance, or update an existing instance. serializer = CommentSerializer(data=data) # Create new instance - serializer = CommentSerializer(comment, data=data) # Update `instance` + serializer = CommentSerializer(comment, data=data) # Update `comment` 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 + serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `comment` with partial data ## Validation @@ -208,7 +208,7 @@ Similarly if a nested representation should be a list of items, you should pass Validation of nested objects will work the same as before. Errors with nested objects will be nested under the field name of the nested object. - serializer = CommentSerializer(comment, data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'}) + serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'}) serializer.is_valid() # False serializer.errors -- cgit v1.2.3 From 6e622d644c9b55b905e24497f0fb818d557fd970 Mon Sep 17 00:00:00 2001 From: Yuri Prezument Date: Sun, 5 Jan 2014 15:58:46 +0200 Subject: CharField - add allow_null argument --- docs/api-guide/fields.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index e05c0306..83825350 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -157,23 +157,24 @@ Corresponds to `django.db.models.fields.BooleanField`. ## CharField A text representation, optionally validates the text to be shorter than `max_length` and longer than `min_length`. +If `allow_none` is `False` (default), `None` values will be converted to an empty string. Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.TextField`. -**Signature:** `CharField(max_length=None, min_length=None)` +**Signature:** `CharField(max_length=None, min_length=None, allow_none=False)` ## 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)` +**Signature:** `CharField(max_length=200, min_length=None, allow_none=False)` ## SlugField Corresponds to `django.db.models.fields.SlugField`. -**Signature:** `CharField(max_length=50, min_length=None)` +**Signature:** `CharField(max_length=50, min_length=None, allow_none=False)` ## ChoiceField -- cgit v1.2.3 From 85d74fc86a934309359a437dd487193013055977 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 14 Jan 2014 11:25:44 +0000 Subject: Added write_only and write_only_fields. Refs #1306 --- docs/api-guide/fields.md | 8 +++++++- docs/api-guide/serializers.md | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 91866664..c136509b 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -28,7 +28,13 @@ 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 during deserialization. +Set this to `True` to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization. + +Defaults to `False` + +### `write_only` + +Set this to `True` to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation. Defaults to `False` diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 04439092..b05acfd5 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -373,6 +373,25 @@ You may wish to specify multiple fields as read-only. Instead of adding each fi 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 which fields should be write-only + +You may wish to specify multiple fields as write-only. Instead of adding each field explicitly with the `write_only=True` attribute, you may use the `write_only_fields` Meta option, like so: + + class CreateUserSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ('email', 'username', 'password') + write_only_fields = ('password',) # Note: Password field is write-only + + def restore_object(self, attrs, instance=None): + """ + Instantiate a new User instance. + """ + assert instance is None, 'Cannot update users with CreateUserSerializer' + user = User(email=attrs['email'], username=attrs['username']) + user.set_password(attrs['password']) + return user + ## Specifying fields explicitly You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class. -- cgit v1.2.3 From d20c49da4ae6f569d3acc243169e3c13c89a95fe Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 14 Jan 2014 20:34:33 +0000 Subject: More HyperlinkedModelSerializer docs --- docs/api-guide/serializers.md | 23 +++++++++++++++++++++++ docs/api-guide/settings.md | 6 ++++++ 2 files changed, 29 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index b05acfd5..e8369c20 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -464,6 +464,29 @@ For more specific requirements such as specifying a different lookup for each fi model = Account fields = ('url', 'account_name', 'users', 'created') +## Overiding the URL field behavior + +The name of the URL field defaults to 'url'. You can override this globally, by using the `URL_FIELD_NAME` setting. + +You can also override this on a per-serializer basis by using the `url_field_name` option on the serializer, like so: + + class AccountSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = Account + fields = ('account_url', 'account_name', 'users', 'created') + url_field_name = 'account_url' + +**Note**: The generic view implementations normally generate a `Location` header in response to successful `POST` requests. Serializers using `url_field_name` option will not have this header automatically included by the view. If you need to do so you will ned to also override the view's `get_success_headers()` method. + +You can also overide the URL field's view name and lookup field without overriding the field explicitly, by using the `view_name` and `lookup_field` options, like so: + + class AccountSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = Account + fields = ('account_url', 'account_name', 'users', 'created') + view_name = 'account_detail' + lookup_field='account_name' + --- # Advanced serializer usage diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 13f96f9a..5aee52aa 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -353,6 +353,12 @@ This should be a function with the following signature: Default: `'rest_framework.views.exception_handler'` +#### URL_FIELD_NAME + +A string representing the key that should be used for the URL fields generated by `HyperlinkedModelSerializer`. + +Default: `'url'` + #### FORMAT_SUFFIX_KWARG The name of a parameter in the URL conf that may be used to provide a format suffix. -- cgit v1.2.3 From 71c03b9db97edbde228777981de0ac7b664302de Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 15 Jan 2014 14:27:41 +0000 Subject: Security update to OrderingFilter --- docs/api-guide/filtering.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 0e02a2a7..07420d84 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -282,13 +282,37 @@ Multiple orderings may also be specified: http://example.com/api/users?ordering=account,username +### Specifying which fields may be ordered against + +It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an `ordering_fields` attribute on the view, like so: + + class UserListView(generics.ListAPIView): + queryset = User.objects.all() + serializer_class = UserSerializer + filter_backends = (filters.OrderingFilter,) + ordering_fields = ('username', 'email') + +This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data. + +If you *don't* specify an `ordering_fields` attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the `serializer_class` attribute. + +If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on *any* model field or queryset aggregate, by using the special value `'__all__'`. + + class BookingsListView(generics.ListAPIView): + queryset = Booking.objects.all() + serializer_class = BookingSerializer + filter_backends = (filters.OrderingFilter,) + ordering_fields = '__all__' + +### Specifying a default ordering + If an `ordering` attribute is set on the view, this will be used as the default ordering. Typically 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 + serializer_class = UserSerializer filter_backends = (filters.OrderingFilter,) ordering = ('username',) -- cgit v1.2.3 From 37cd49cac98dfb5b79c4e4df0f42e782280172ce Mon Sep 17 00:00:00 2001 From: Miroslav Shubernetskiy Date: Sat, 18 Jan 2014 22:31:36 -0500 Subject: Added docs for bulk views from django-rest-framework-bulk. --- docs/api-guide/generic-views.md | 49 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 83c3e45f..11b55063 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -362,6 +362,54 @@ If you are using a mixin across multiple views, you can take this a step further 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. +# Third party packages + +The following third party packages provide additional generic view implementations. + +## Django REST Framework bulk + +The [django-rest-framework-bulk package][django-rest-framework-bulk] implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests. + +### Mixins + +As with Django Rest Framework standard mixins, each mixin defines a specific behavior which allows to composite multiple mixins (either with other bulk mixins or standard mixins) for more functionality. + +#### BulkCreateModelMixin + +Provides a `.create(request, *args, **kwargs)` method, that implements creating either a single or multiple objects depending on the `request.DATA` data-type (list or object). + +If any object(s) is/are created, as with the standard `CreateModelMixin`, `201 Created` response is returned with the serialization of created object(s). If any errors occur while validating the provided data, `400 Bad Request` is returned with error details for each attempted creation object. + +#### BulkUpdateModelMixin + +Provides a `.bulk_update(request, *args, **kwargs)` method, that implements updating multiple objects at the same time. Since each object needs to be identified, each object within `request.DATA` must provide its identity as per serializer's `.get_identity()`. + +Also provides a `.partial_bulk_update(request, *args, **kwargs)` method, which is similar to the `bulk_update`, except that all fields for all resources will be optional. + +If all objects are updated, `200 OK` response is returned with the serialized representation of all updated objects. If any validation errors occur, `400 Bad Request` is returned. + +#### BulkDestroyModelMixin + +Provides a `.bulk_destroy(request, *args, **kwargs)` method, that implements deletion of all objects within a queryset. Since that can potentially be very dangerous, this mixin also provides an `.allow_bulk_destroy(queryset, filtered)` hook to determine if the bulk delete should be allowed. By default it allows the request if the queryset was filtered. + +If the objects are deleted this returns `204 No Content` response or `400 Bad Request` if the request is not allowed as per `allow_bulk_destroy`. + +### Concrete View Classes + +In addition to the bulk mixins, this package also implements some of the most common bulk concrete view classes. Those include: + +* `BulkCreateAPIView` +* `BulkUpdateAPIView` +* `BulkDestroyAPIView` +* `ListBulkCreateAPIView` +* `ListCreateBulkUpdateAPIView` +* `ListCreateBulkUpdateDestroyAPIView` +* `ListBulkCreateUpdateAPIView` +* `ListBulkCreateUpdateDestroyAPIView` + +To create custom concrete view classes, you can also composite the mixins manually as explained in **Creating custom base classes** of Django Rest Framework documentation. + + [cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views [GenericAPIView]: #genericapiview @@ -370,3 +418,4 @@ Using custom base classes is a good option if you have custom behavior that cons [RetrieveModelMixin]: #retrievemodelmixin [UpdateModelMixin]: #updatemodelmixin [DestroyModelMixin]: #destroymodelmixin +[django-rest-framework-bulk]: https://github.com/miki725/django-rest-framework-bulk -- cgit v1.2.3 From 1c34051f5edcb7cddae63fc02b0a21d6e5fc1143 Mon Sep 17 00:00:00 2001 From: José Padilla Date: Sat, 18 Jan 2014 23:51:18 -0500 Subject: Include the djangorestframework-jwt package --- docs/api-guide/authentication.md | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 53efc49a..dc8e2099 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -389,6 +389,10 @@ The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 supp The [Django OAuth2 Consumer][doac] library from [Rediker Software][rediker] is another package that provides [OAuth 2.0 support for REST framework][doac-rest-framework]. The package includes token scoping permissions on tokens, which allows finer-grained access to your API. +## JSON Web Token Authentication + +JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. [Blimp][blimp] maintains the [djangorestframework-jwt][djangorestframework-jwt] package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password. + [cite]: http://jacobian.org/writing/rest-worst-practices/ [http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2 [http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4 @@ -413,3 +417,5 @@ The [Django OAuth2 Consumer][doac] library from [Rediker Software][rediker] is a [doac]: https://github.com/Rediker-Software/doac [rediker]: https://github.com/Rediker-Software [doac-rest-framework]: https://github.com/Rediker-Software/doac/blob/master/docs/integrations.md# +[blimp]: https://github.com/GetBlimp +[djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt -- cgit v1.2.3 From e3c5a134510c8e364bd278dc5033ccb5515927d7 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 19 Jan 2014 21:09:49 +0000 Subject: Drop django-rest-framework-bulk API descriptions --- docs/api-guide/generic-views.md | 40 ---------------------------------------- 1 file changed, 40 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 11b55063..e23b2c74 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -370,48 +370,8 @@ The following third party packages provide additional generic view implementatio The [django-rest-framework-bulk package][django-rest-framework-bulk] implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests. -### Mixins - -As with Django Rest Framework standard mixins, each mixin defines a specific behavior which allows to composite multiple mixins (either with other bulk mixins or standard mixins) for more functionality. - -#### BulkCreateModelMixin - -Provides a `.create(request, *args, **kwargs)` method, that implements creating either a single or multiple objects depending on the `request.DATA` data-type (list or object). - -If any object(s) is/are created, as with the standard `CreateModelMixin`, `201 Created` response is returned with the serialization of created object(s). If any errors occur while validating the provided data, `400 Bad Request` is returned with error details for each attempted creation object. - -#### BulkUpdateModelMixin - -Provides a `.bulk_update(request, *args, **kwargs)` method, that implements updating multiple objects at the same time. Since each object needs to be identified, each object within `request.DATA` must provide its identity as per serializer's `.get_identity()`. - -Also provides a `.partial_bulk_update(request, *args, **kwargs)` method, which is similar to the `bulk_update`, except that all fields for all resources will be optional. - -If all objects are updated, `200 OK` response is returned with the serialized representation of all updated objects. If any validation errors occur, `400 Bad Request` is returned. - -#### BulkDestroyModelMixin - -Provides a `.bulk_destroy(request, *args, **kwargs)` method, that implements deletion of all objects within a queryset. Since that can potentially be very dangerous, this mixin also provides an `.allow_bulk_destroy(queryset, filtered)` hook to determine if the bulk delete should be allowed. By default it allows the request if the queryset was filtered. - -If the objects are deleted this returns `204 No Content` response or `400 Bad Request` if the request is not allowed as per `allow_bulk_destroy`. - -### Concrete View Classes - -In addition to the bulk mixins, this package also implements some of the most common bulk concrete view classes. Those include: - -* `BulkCreateAPIView` -* `BulkUpdateAPIView` -* `BulkDestroyAPIView` -* `ListBulkCreateAPIView` -* `ListCreateBulkUpdateAPIView` -* `ListCreateBulkUpdateDestroyAPIView` -* `ListBulkCreateUpdateAPIView` -* `ListBulkCreateUpdateDestroyAPIView` - -To create custom concrete view classes, you can also composite the mixins manually as explained in **Creating custom base classes** of Django Rest Framework documentation. - [cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views - [GenericAPIView]: #genericapiview [ListModelMixin]: #listmodelmixin [CreateModelMixin]: #createmodelmixin -- cgit v1.2.3 From 77ced39e6c02cd375ac6df0c00f78846ac5cbec5 Mon Sep 17 00:00:00 2001 From: Paul Melnikow Date: Fri, 31 Jan 2014 12:26:45 -0500 Subject: Fix doc for custom exception sample The way to provide a default detail for APIException is to define a `default_detail` attribute on the subclass. Defining a `detail` attribute without `default_detail` will not work, and will result in empty detail instead. --- docs/api-guide/exceptions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 221df679..4e8b823c 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -94,7 +94,7 @@ For example, if your API relies on a third party service that may sometimes be u class ServiceUnavailable(APIException): status_code = 503 - detail = 'Service temporarily unavailable, try again later.' + default_detail = 'Service temporarily unavailable, try again later.' ## ParseError -- cgit v1.2.3 From e437854a44249806478c40f1e36244863e5ded3d Mon Sep 17 00:00:00 2001 From: meoooh Date: Sat, 1 Feb 2014 15:02:11 +0900 Subject: Update fields.md --- docs/api-guide/fields.md | 1 + 1 file changed, 1 insertion(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index c136509b..0b50aa95 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -104,6 +104,7 @@ A serializer definition that looked like this: expired = serializers.Field(source='has_expired') class Meta: + model = Account fields = ('url', 'owner', 'name', 'expired') Would produce output similar to: -- cgit v1.2.3 From a33eb4177e78a65d9e07cec18198b48fa11acca1 Mon Sep 17 00:00:00 2001 From: Jeff Fein-Worton Date: Sun, 2 Feb 2014 21:21:08 -0800 Subject: fixed typo (wrong "its") --- docs/api-guide/fields.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 0b50aa95..93f992e6 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -126,7 +126,7 @@ A field that supports both read and write operations. By itself `WritableField` ## ModelField -A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to it's associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. +A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. The `ModelField` class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model. For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))` @@ -308,7 +308,7 @@ Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files. 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 initial datatype, and a primitive, serializable datatype. Primitive 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 primitive objects. -The `.to_native()` method is called to convert the initial datatype into a primitive, serializable datatype. The `from_native()` method is called to restore a primitive datatype into it's initial representation. +The `.to_native()` method is called to convert the initial datatype into a primitive, serializable datatype. The `from_native()` method is called to restore a primitive datatype into its initial representation. ## Examples -- cgit v1.2.3 From 40b148a2e427ffbedbc04c47235f07bf98d7e520 Mon Sep 17 00:00:00 2001 From: Charlie Denton Date: Mon, 3 Feb 2014 14:54:44 +0000 Subject: Viewsets docs typo The docstring in the example said "update" instead of "create".--- docs/api-guide/viewsets.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 4fdd9364..23b16575 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -225,7 +225,7 @@ To create a base viewset class that provides `create`, `list` and `retrieve` ope mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ - A viewset that provides `retrieve`, `update`, and `list` actions. + A viewset that provides `retrieve`, `create`, and `list` actions. To use it, override the class and set the `.queryset` and `.serializer_class` attributes. -- cgit v1.2.3 From ba8a0bac538adc8d6897ece14648e03ce7441b24 Mon Sep 17 00:00:00 2001 From: RicterZ Date: Tue, 4 Feb 2014 23:41:13 +0800 Subject: Fixed a bug backticks fix you may optionally exclude the ``self.check_object_permissions, and simply return the object from the `get_object_or_404` lookup. to you may optionally exclude the `self.check_object_permissions`, and simply return the object from the `get_object_or_404` lookup.--- docs/api-guide/generic-views.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index e23b2c74..fb927ea8 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -119,7 +119,7 @@ For example: self.check_object_permissions(self.request, obj) return obj -Note that if your API doesn't include any object level permissions, you may optionally exclude the ``self.check_object_permissions, and simply return the object from the `get_object_or_404` lookup. +Note that if your API doesn't include any object level permissions, you may optionally exclude the `self.check_object_permissions`, and simply return the object from the `get_object_or_404` lookup. #### `get_filter_backends(self)` -- cgit v1.2.3 From d48ba1cff76ffceb1d700e9e0c6ccf518a6382da Mon Sep 17 00:00:00 2001 From: Andrey Kaygorodov Date: Wed, 5 Feb 2014 05:47:27 +0800 Subject: turn of pagination --- docs/api-guide/pagination.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 0829589f..f86e6ce1 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -102,7 +102,7 @@ You can also set the pagination style on a per-view basis, using the `ListAPIVie paginate_by_param = 'page_size' max_paginate_by = 100 -Note that using a `paginate_by` value of `None` will turn off pagination for the view. +Note that using a `paginate_by` value of `None` will turn off pagination for the view. But if you specified `PAGINATE_BY` and `PAGINATE_BY_PARAM` in your settings file then you have to set both `paginate_by` and `paginate_by_param` to a `None` value in order to turn off pagination for the view. 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. -- cgit v1.2.3 From 2d20512d259f51a5a5c2b71b20f98d24e0176f16 Mon Sep 17 00:00:00 2001 From: Andrey Kaygorodov Date: Wed, 5 Feb 2014 21:10:51 +0800 Subject: #1390, docs, turning of pagination --- docs/api-guide/pagination.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index f86e6ce1..047a0988 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -102,7 +102,8 @@ You can also set the pagination style on a per-view basis, using the `ListAPIVie paginate_by_param = 'page_size' max_paginate_by = 100 -Note that using a `paginate_by` value of `None` will turn off pagination for the view. But if you specified `PAGINATE_BY` and `PAGINATE_BY_PARAM` in your settings file then you have to set both `paginate_by` and `paginate_by_param` to a `None` value in order to turn off pagination for the view. +Note that using a `paginate_by` value of `None` will turn off pagination for the view. +Note if you use the `PAGINATE_BY_PARAM` settings, you also have to set the `paginate_by_param` attribute in your view to `None` in order to turn off pagination for those requests that contain the `paginate_by_param` parameter. 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. -- cgit v1.2.3 From 97b7c25987c3bfa096a084dc671fc24816b08f87 Mon Sep 17 00:00:00 2001 From: Hassan Shamim Date: Mon, 10 Feb 2014 12:54:56 -0600 Subject: Replace 'detail' with 'default_detail' in Exceptions guide and APIException class docstring. --- docs/api-guide/exceptions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 4e8b823c..66e18173 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -18,7 +18,7 @@ The handled exceptions are: In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error. -By default all error responses will include a key `details` in the body of the response, but other keys may also be included. +By default all error responses will include a key `detail` in the body of the response, but other keys may also be included. For example, the following request: @@ -86,7 +86,7 @@ Note that the exception handler will only be called for responses generated by r The **base class** for all exceptions raised inside REST framework. -To provide a custom exception, subclass `APIException` and set the `.status_code` and `.detail` properties on the class. +To provide a custom exception, subclass `APIException` and set the `.status_code` and `.default_detail` properties on the class. For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so: -- cgit v1.2.3 From 821f8488023cb5161eb0f69b9121f6d956c39baf Mon Sep 17 00:00:00 2001 From: Vita Smid Date: Fri, 14 Feb 2014 10:44:02 +0100 Subject: Minor typos fixed in api-guide/testing.md (request -> response). --- docs/api-guide/testing.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index 4a8a9168..72c33961 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -218,12 +218,12 @@ You can use any of REST framework's test case classes as you would for the regul When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response. -For example, it's easier to inspect `request.data`: +For example, it's easier to inspect `response.data`: response = self.client.get('/users/4/') self.assertEqual(response.data, {'id': 4, 'username': 'lauren'}) -Instead of inspecting the result of parsing `request.content`: +Instead of inspecting the result of parsing `response.content`: response = self.client.get('/users/4/') self.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'}) -- cgit v1.2.3 From 6f4c2c6f0536bdf596534c295e411e17be14aab7 Mon Sep 17 00:00:00 2001 From: Bo Peng Date: Fri, 14 Feb 2014 13:47:06 -0600 Subject: Update throttling.md Added comma to make DEFAULT_THROTTLE_CLASSES a tuple in example, for copy&paste to work nicely.--- docs/api-guide/throttling.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index fc1525df..b7c320f0 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -150,7 +150,7 @@ For example, given the following views... REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( - 'rest_framework.throttling.ScopedRateThrottle' + 'rest_framework.throttling.ScopedRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'contacts': '1000/day', -- cgit v1.2.3 From b3aa512d35b7f3e432bb41bf9de9ac7db7a1ed4c Mon Sep 17 00:00:00 2001 From: Saurabh Kumar Date: Tue, 18 Feb 2014 20:39:39 +0530 Subject: fix(docs): fix code indentation in serializers.md It fixes the indentation of `restore_object()` in the section "Specifying which fields should be write-only" serializers documentation.--- docs/api-guide/serializers.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index e8369c20..39fe61eb 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -383,14 +383,14 @@ You may wish to specify multiple fields as write-only. Instead of adding each f fields = ('email', 'username', 'password') write_only_fields = ('password',) # Note: Password field is write-only - def restore_object(self, attrs, instance=None): - """ - Instantiate a new User instance. - """ - assert instance is None, 'Cannot update users with CreateUserSerializer' - user = User(email=attrs['email'], username=attrs['username']) - user.set_password(attrs['password']) - return user + def restore_object(self, attrs, instance=None): + """ + Instantiate a new User instance. + """ + assert instance is None, 'Cannot update users with CreateUserSerializer' + user = User(email=attrs['email'], username=attrs['username']) + user.set_password(attrs['password']) + return user ## Specifying fields explicitly -- cgit v1.2.3 From 1a4c6f075b33661e9b919c95575a5439aa924dcd Mon Sep 17 00:00:00 2001 From: Elvio Toccalino Date: Thu, 20 Feb 2014 01:07:39 -0300 Subject: include djangorestframework-httpsignature in the docs --- docs/api-guide/authentication.md | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index dc8e2099..f992b0ce 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -393,6 +393,10 @@ The [Django OAuth2 Consumer][doac] library from [Rediker Software][rediker] is a JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. [Blimp][blimp] maintains the [djangorestframework-jwt][djangorestframework-jwt] package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password. +## HTTP Signature Authentication + +HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] package which provides an easy to use HTTP Signature Authentication mechanism. + [cite]: http://jacobian.org/writing/rest-worst-practices/ [http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2 [http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4 @@ -419,3 +423,7 @@ JSON Web Token is a fairly new standard which can be used for token-based authen [doac-rest-framework]: https://github.com/Rediker-Software/doac/blob/master/docs/integrations.md# [blimp]: https://github.com/GetBlimp [djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt +[etoccalino]: https://github.com/etoccalino/ +[djangorestframework-httpsignature]: https://github.com/etoccalino/django-rest-framework-httpsignature +[amazon-http-signature]: http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html +[http-signature-ietf-draft]: https://datatracker.ietf.org/doc/draft-cavage-http-signatures/ -- cgit v1.2.3 From 98410693738aa81528bef2016a69e87560ae4ae3 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 20 Feb 2014 14:54:17 +0000 Subject: Link to DRF-extensions. Refs #1430 --- docs/api-guide/pagination.md | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 0829589f..efc4ae7f 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -147,4 +147,14 @@ Alternatively, to set your custom pagination serializer on a per-view basis, use pagination_serializer_class = CustomPaginationSerializer paginate_by = 10 +# Third party packages + +The following third party packages are also available. + +## DRF-extensions + +The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` mixin class][paginate-by-max-mixin] that allows your API clients to specify `?page_size=max` to obtain the maximum allowed page size. + [cite]: https://docs.djangoproject.com/en/dev/topics/pagination/ +[drf-extensions]: http://chibisov.github.io/drf-extensions/docs/ +[paginate-by-max-mixin]: http://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin \ No newline at end of file -- cgit v1.2.3 From c3967c08ab48a8129b7d7fdc00175fd203aea6c8 Mon Sep 17 00:00:00 2001 From: Charlie Denton Date: Fri, 21 Feb 2014 14:23:33 +0000 Subject: Minor docs example fix Dates are smaller when they happen before.--- docs/api-guide/serializers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 39fe61eb..7ee060af 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -161,7 +161,7 @@ To do any other validation that requires access to multiple fields, add a method """ Check that the start is before the stop. """ - if attrs['start'] < attrs['finish']: + if attrs['start'] > attrs['finish']: raise serializers.ValidationError("finish must occur after start") return attrs -- cgit v1.2.3 From a4470c42765004825ed6c09ae434dfd7dd969d1e Mon Sep 17 00:00:00 2001 From: Kumar McMillan Date: Fri, 28 Feb 2014 16:51:32 -0600 Subject: Fix trailing whitespace Sorry, my editor does this automatically --- docs/api-guide/authentication.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index f992b0ce..59bea733 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -93,7 +93,7 @@ Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the author If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the `WSGIPassAuthorization` directive in the appropriate context and setting it to `'On'`. - # this can go in either server config, virtual host, directory or .htaccess + # this can go in either server config, virtual host, directory or .htaccess WSGIPassAuthorization On --- @@ -117,7 +117,7 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401 ## 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: @@ -125,7 +125,7 @@ To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in y ... 'rest_framework.authtoken' ) - + Make sure to run `manage.py syncdb` after changing your settings. The `authtoken` database tables are managed by south (see [Schema migrations](#schema-migrations) below). You'll also need to create tokens for your users. @@ -209,7 +209,7 @@ You can do so by inserting a `needed_by` attribute in your user migration: needed_by = ( ('authtoken', '0001_initial'), ) - + def forwards(self): ... @@ -282,7 +282,7 @@ Note that the `namespace='oauth2'` argument is required. Finally, sync your database. python manage.py syncdb - python manage.py migrate + python manage.py migrate --- @@ -368,7 +368,7 @@ The following example will authenticate any incoming request as the user given b user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') - + return (user, None) --- -- cgit v1.2.3 From c2cd610b15e97979be23e4c7e713028ef7f2e23a Mon Sep 17 00:00:00 2001 From: Kumar McMillan Date: Fri, 28 Feb 2014 16:51:58 -0600 Subject: Adds HawkREST to 3rd party auth docs --- docs/api-guide/authentication.md | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 59bea733..88a7a011 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -393,6 +393,10 @@ The [Django OAuth2 Consumer][doac] library from [Rediker Software][rediker] is a JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. [Blimp][blimp] maintains the [djangorestframework-jwt][djangorestframework-jwt] package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password. +## Hawk HTTP Authentication + +The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let you work with [Hawk][hawk] signed requests and responses in your API. [Hawk][hawk] lets two parties securely communicate with each other using messages signed by a shared key. It is based on [HTTP MAC access authentication][mac] (which was based on parts of [OAuth 1.0][oauth-1.0a]). + ## HTTP Signature Authentication HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] package which provides an easy to use HTTP Signature Authentication mechanism. @@ -427,3 +431,7 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a [djangorestframework-httpsignature]: https://github.com/etoccalino/django-rest-framework-httpsignature [amazon-http-signature]: http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html [http-signature-ietf-draft]: https://datatracker.ietf.org/doc/draft-cavage-http-signatures/ +[hawkrest]: http://hawkrest.readthedocs.org/en/latest/ +[hawk]: https://github.com/hueniverse/hawk +[mohawk]: http://mohawk.readthedocs.org/en/latest/ +[mac]: http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05 -- cgit v1.2.3 From 2353878951b0607a95d539c27c362d0353c53119 Mon Sep 17 00:00:00 2001 From: Peter Inglesby Date: Thu, 6 Mar 2014 21:39:44 +0000 Subject: Add SEARCH_PARAM and ORDERING_PARAM to settings Fixes #1434--- docs/api-guide/filtering.md | 6 +++++- docs/api-guide/settings.md | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 07420d84..d6c4b1c1 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -264,13 +264,17 @@ For example: search_fields = ('=username', '=email') +By default, the search parameter is named `'search`', but this may be overridden with the `SEARCH_PARAM` setting. + 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 `'ordering'` to the required field name. For example: +The `OrderingFilter` class supports simple query parameter controlled ordering of results. By default, the query parameter is named `'ordering'`, but this may by overridden with the `ORDERING_PARAM` setting. + +For example, to order users by username: http://example.com/api/users?ordering=username diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 5aee52aa..c979019f 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -158,6 +158,18 @@ A client request like the following would return a paginated list of up to 100 i Default: `None` +### SEARCH_PARAM + +The name of a query paramater, which can be used to specify the search term used by `SearchFilter`. + +Default: `search` + +#### ORDERING_PARAM + +The name of a query paramater, which can be used to specify the ordering of results returned by `OrderingFilter`. + +Default: `ordering` + --- ## Authentication settings -- cgit v1.2.3 From c779dce3e4bba8fc453e0abe51f6fb5b2f005721 Mon Sep 17 00:00:00 2001 From: Steven Cummings Date: Sun, 16 Mar 2014 18:55:21 -0500 Subject: Serializer fields section for 3rd-party packages * Add new section to serializer fields page where we can list and link 3rd-party packages that provide more field types * Add an entry for drf-compound-fields --- docs/api-guide/fields.md | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 93f992e6..89606798 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] @@ -47,7 +47,7 @@ Defaults to `True`. ### `default` -If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all. +If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all. May be set to a function or other callable, in which case the value will be evaluated each time it is used. @@ -92,7 +92,7 @@ For example, using the following model. name = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) payment_expiry = models.DateTimeField() - + def has_expired(self): return now() > self.payment_expiry @@ -102,7 +102,7 @@ A serializer definition that looked like this: class AccountSerializer(serializers.HyperlinkedModelSerializer): expired = serializers.Field(source='has_expired') - + class Meta: model = Account fields = ('url', 'owner', 'name', 'expired') @@ -112,7 +112,7 @@ Would produce output similar to: { 'url': 'http://example.com/api/accounts/3/', 'owner': 'http://example.com/api/users/12/', - 'name': 'FooCorp business account', + 'name': 'FooCorp business account', 'expired': True } @@ -224,7 +224,7 @@ In the case of JSON this means the default datetime representation uses the [ECM **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. +* `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 specify 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'`) @@ -284,7 +284,7 @@ Corresponds to `django.forms.fields.FileField`. **Signature:** `FileField(max_length=None, allow_empty_file=False)` - `max_length` designates the maximum length for the file name. - + - `allow_empty_file` designates if empty files are allowed. ## ImageField @@ -329,12 +329,12 @@ Let's look at an example of serializing a class that represents an RGB color val """ 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()`. @@ -347,6 +347,14 @@ As an example, let's create a field that can be used represent the class name of """ return obj.__class__ +# More fields from 3rd-party packages + +## [drf-compound-fields](http://drf-compound-fields.readthedocs.org) + +Provides "compound" serializer fields, such as lists of simple values, which can be described by +other fields rather than serializers with the `many=True` option. Also provided are fields for +typed dictionaries and values that can be either a specific type or a list of items of that type. + [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 -- cgit v1.2.3 From dddbff59319bdefbf235f8a37af5b6ac20c4fec1 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 17 Mar 2014 08:33:18 +0000 Subject: Tweak DRF compound fields docs --- docs/api-guide/fields.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 89606798..b3d5b55a 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -347,16 +347,15 @@ As an example, let's create a field that can be used represent the class name of """ return obj.__class__ -# More fields from 3rd-party packages +# Third party packages -## [drf-compound-fields](http://drf-compound-fields.readthedocs.org) +## DRF Compound Fields -Provides "compound" serializer fields, such as lists of simple values, which can be described by -other fields rather than serializers with the `many=True` option. Also provided are fields for -typed dictionaries and values that can be either a specific type or a list of items of that type. +The [drf-compound-fields][drf-compound-fields] package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the `many=True` option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type. [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 +[drf-compound-fields]: http://drf-compound-fields.readthedocs.org -- cgit v1.2.3 From abe14c06f78de3b1ab20ed73f0ee5691f5224f94 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 17 Mar 2014 08:36:13 +0000 Subject: Minor docs tweak --- docs/api-guide/fields.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index b3d5b55a..67fa65d2 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -349,6 +349,8 @@ As an example, let's create a field that can be used represent the class name of # Third party packages +The following third party packages are also available. + ## DRF Compound Fields The [drf-compound-fields][drf-compound-fields] package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the `many=True` option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type. -- cgit v1.2.3 From 3234a5dd6b0c090dd25a716e7b1c2567d8fee89b Mon Sep 17 00:00:00 2001 From: Craig Date: Tue, 8 Apr 2014 22:56:07 -0400 Subject: Fix python syntax in filtering docs --- docs/api-guide/filtering.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index d6c4b1c1..6a8a267b 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -24,7 +24,7 @@ For example: from myapp.serializers import PurchaseSerializer from rest_framework import generics - class PurchaseList(generics.ListAPIView) + class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): @@ -46,7 +46,7 @@ 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) + class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): @@ -63,7 +63,7 @@ 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) + class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): -- cgit v1.2.3 From f68596a7326777f971d9551ff1bfc7176389ea22 Mon Sep 17 00:00:00 2001 From: Miro Hrončok Date: Thu, 10 Apr 2014 01:58:06 +0200 Subject: Document new UnicodeYAMLRenderer --- docs/api-guide/renderers.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 7798827b..7a3429bf 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -138,6 +138,26 @@ Renders the request data into `YAML`. Requires the `pyyaml` package to be installed. +Note that non-ascii characters will be rendered using `\uXXXX` character escape. For example: + + unicode black star: "\u2605" + +**.media_type**: `application/yaml` + +**.format**: `'.yaml'` + +**.charset**: `utf-8` + +## UnicodeYAMLRenderer + +Renders the request data into `YAML`. + +Requires the `pyyaml` package to be installed. + +Note that non-ascii characters will not be character escaped. For example: + + unicode black star: ★ + **.media_type**: `application/yaml` **.format**: `'.yaml'` -- cgit v1.2.3 From 5e8f05a8de410125d6df7a8e27f61e94176a8897 Mon Sep 17 00:00:00 2001 From: dpetzel Date: Mon, 28 Apr 2014 13:51:50 -0400 Subject: very minor typo in code example --- docs/api-guide/permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 6a0f48f4..50f669a2 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -56,7 +56,7 @@ You can also set the authentication policy on a per-view, or per-viewset basis, using the `APIView` class based views. from rest_framework.permissions import IsAuthenticated - from rest_framework.responses import Response + from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): -- cgit v1.2.3 From d8cb85ef8fb0a0804d9b2c09d909ad99f69301c8 Mon Sep 17 00:00:00 2001 From: Laurent Bristiel Date: Mon, 28 Apr 2014 22:00:36 +0200 Subject: typo --- docs/api-guide/generic-views.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index fb927ea8..7d06f246 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -70,7 +70,7 @@ The following attributes control the basic view behavior. **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. Note that `model` is only ever used for generating a default queryset or serializer class - the `queryset` and `serializer_class` attributes are always preferred if provided. +* `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 `DEFAULT_MODEL_SERIALIZER_CLASS` setting will determine the base serializer class. Note that `model` is only ever used for generating a default queryset or serializer class - the `queryset` and `serializer_class` attributes are always preferred if provided. **Pagination**: -- cgit v1.2.3 From 768f537dcbb5d4f7429a74556559047bfd6f3078 Mon Sep 17 00:00:00 2001 From: Giorgos Logiotatidis Date: Thu, 15 May 2014 15:34:31 +0300 Subject: Typo fix. --- docs/api-guide/serializers.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 7ee060af..0044f070 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -464,7 +464,7 @@ For more specific requirements such as specifying a different lookup for each fi model = Account fields = ('url', 'account_name', 'users', 'created') -## Overiding the URL field behavior +## Overriding the URL field behavior The name of the URL field defaults to 'url'. You can override this globally, by using the `URL_FIELD_NAME` setting. @@ -478,7 +478,7 @@ You can also override this on a per-serializer basis by using the `url_field_nam **Note**: The generic view implementations normally generate a `Location` header in response to successful `POST` requests. Serializers using `url_field_name` option will not have this header automatically included by the view. If you need to do so you will ned to also override the view's `get_success_headers()` method. -You can also overide the URL field's view name and lookup field without overriding the field explicitly, by using the `view_name` and `lookup_field` options, like so: +You can also override the URL field's view name and lookup field without overriding the field explicitly, by using the `view_name` and `lookup_field` options, like so: class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: -- cgit v1.2.3 From 1e7b5fd2c04e587e30cf29e15ca3074b8d33b92e Mon Sep 17 00:00:00 2001 From: Ian Foote Date: Tue, 20 May 2014 14:55:00 +0100 Subject: Document ChoiceField blank_display_value parameter --- docs/api-guide/fields.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 67fa65d2..58dbf977 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -184,7 +184,9 @@ Corresponds to `django.db.models.fields.SlugField`. ## ChoiceField -A field that can accept a value out of a limited set of choices. +A field that can accept a value out of a limited set of choices. Optionally takes a `blank_display_value` parameter that customizes the display value of an empty choice. + +**Signature:** `ChoiceField(choices=(), blank_display_value=None)` ## EmailField -- cgit v1.2.3 From eab5933070d5df9078a6b88e85ee933cbfa28955 Mon Sep 17 00:00:00 2001 From: khamaileon Date: Mon, 26 May 2014 18:43:50 +0200 Subject: Add the allow_add_remove parameter to the get_serializer method --- docs/api-guide/generic-views.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 7d06f246..bb748981 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -187,7 +187,7 @@ Remember that the `pre_save()` method is not called by `GenericAPIView` itself, 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`. * `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_serializer(self, instance=None, data=None, files=None, many=False, partial=False, allow_add_remove=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. -- cgit v1.2.3 From a7ff51118f8c8d696219ea7723b283a0ee680457 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 29 May 2014 14:33:16 +0100 Subject: Note on configuring TokenAuthentication --- docs/api-guide/authentication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 88a7a011..1cb37d67 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -119,7 +119,7 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401 This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. -To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting: +To use the `TokenAuthentication` scheme you'll need to [configure the authentication classes](#setting-the-authentication-scheme) to include `TokenAuthentication`, and additionally include `rest_framework.authtoken` in your `INSTALLED_APPS` setting: INSTALLED_APPS = ( ... -- cgit v1.2.3 From 31f63e1e5502d45f414df400679c238346137b10 Mon Sep 17 00:00:00 2001 From: Rodolfo Carvalho Date: Mon, 2 Jun 2014 11:06:03 +0200 Subject: Fix typo in docs --- docs/api-guide/viewsets.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 23b16575..b3085f75 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -137,7 +137,7 @@ The `@action` and `@link` decorators can additionally take extra arguments that def set_password(self, request, pk=None): ... -The `@action` decorator will route `POST` requests by default, but may also accept other HTTP methods, by using the `method` argument. For example: +The `@action` decorator will route `POST` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example: @action(methods=['POST', 'DELETE']) def unset_password(self, request, pk=None): -- cgit v1.2.3 From be84f71bc906c926c9955a4cf47630b24461067d Mon Sep 17 00:00:00 2001 From: Greg Barker Date: Tue, 10 Jun 2014 15:20:45 -0700 Subject: Fix #1614 - Corrected reference to serializers.CharField --- docs/api-guide/serializers.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 0044f070..cedf1ff7 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -73,8 +73,8 @@ Sometimes when serializing objects, you may not want to represent everything exa If you need to customize the serialized value of a particular field, you can do this by creating a `transform_` method. For example if you needed to render some markdown from a text field: - description = serializers.TextField() - description_html = serializers.TextField(source='description', read_only=True) + description = serializers.CharField() + description_html = serializers.CharField(source='description', read_only=True) def transform_description_html(self, obj, value): from django.contrib.markup.templatetags.markup import markdown -- cgit v1.2.3 From 3f727ce738776838d8420450ce28485954fbb097 Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Tue, 24 Jun 2014 09:02:44 +0200 Subject: Added (first pass) notes to docs & release notes. Backed out `SOUTH_MIGRATION_MODULES` setting from `rest_framework.settings` --- docs/api-guide/authentication.md | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 88a7a011..0bddd0d0 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -126,7 +126,13 @@ To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in y 'rest_framework.authtoken' ) -Make sure to run `manage.py syncdb` after changing your settings. The `authtoken` database tables are managed by south (see [Schema migrations](#schema-migrations) below). + +--- + +**Note:** Make sure to run `manage.py syncdb` after changing your settings. Both Django native (from v1.7) and South migrations for the `authtoken` database tables are provided. See [Schema migrations](#schema-migrations) below. + +--- + You'll also need to create tokens for your users. @@ -198,7 +204,21 @@ Note that the default `obtain_auth_token` view explicitly uses JSON requests and #### Schema migrations -The `rest_framework.authtoken` app includes a south migration that will create the authtoken table. +The `rest_framework.authtoken` app includes both a Django native migration (for Django versions >1.7) and a south migration that will create the authtoken table. + +---- + +**Note** By default both Django (>1.7) and South will look for a module named `migrations`. To avoid a collision here, in order to use South you **must** provide the `SOUTH_MIGRATION_MODULES` option in your `settings.py`: + + + SOUTH_MIGRATION_MODULES = { + 'authtoken': 'rest_framework.authtoken.south_migrations', + } + +This tells South to look in the `south_migrations` module for the `authtoken` app. + +---- + 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. -- cgit v1.2.3 From c1426d1078a40de521aeec6c4099538efa6b24c7 Mon Sep 17 00:00:00 2001 From: Chibisov Gennady Date: Thu, 26 Jun 2014 23:29:00 +0400 Subject: Fixes #1651. Add link to drf-extensions nested routers to docs --- docs/api-guide/routers.md | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 7efc140a..64f05af3 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -179,7 +179,16 @@ The [wq.db package][wq.db] provides an advanced [Router][wq.db-router] class (an app.router.register_model(MyModel) +## DRF-extensions + +The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions-routers] for creating [nested viewsets][drf-extensions-nested-viewsets], [collection level controllers][drf-extensions-collection-level-controllers] with [customizable endpoint names][drf-extensions-customizable-endpoint-names]. + [cite]: http://guides.rubyonrails.org/routing.html [drf-nested-routers]: https://github.com/alanjds/drf-nested-routers [wq.db]: http://wq.io/wq.db [wq.db-router]: http://wq.io/docs/app.py +[drf-extensions]: http://chibisov.github.io/drf-extensions/docs/ +[drf-extensions-routers]: http://chibisov.github.io/drf-extensions/docs/#routers +[drf-extensions-nested-viewsets]: http://chibisov.github.io/drf-extensions/docs/#nested-routes +[drf-extensions-collection-level-controllers]: http://chibisov.github.io/drf-extensions/docs/#collection-level-controllers +[drf-extensions-customizable-endpoint-names]: http://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name \ No newline at end of file -- cgit v1.2.3 From 91eabd54bbc42e8a2540db2ff070097db7a0f4a0 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 1 Jul 2014 14:34:23 +0100 Subject: Docs tweak --- docs/api-guide/filtering.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 6a8a267b..ec5ab61f 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -199,8 +199,7 @@ This enables us to make queries like: http://example.com/api/products?manufacturer__name=foo -This is nice, but it shows underlying model structure in REST API, which may -be undesired, but you can use: +This is nice, but it exposes the Django's double underscore convention as part of the API. If you instead want to explicitly name the filter argument you can instead explicitly include it on the `FilterSet` class: import django_filters from myapp.models import Product @@ -208,7 +207,6 @@ be undesired, but you can use: from rest_framework import generics class ProductFilter(django_filters.FilterSet): - manufacturer = django_filters.CharFilter(name="manufacturer__name") class Meta: -- cgit v1.2.3 From b51901812596aa478cc8cb1046e42049214bc9ff Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 7 Jul 2014 09:51:23 +0100 Subject: Docs on object level permissions and filters. Closes #1683 --- docs/api-guide/permissions.md | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 50f669a2..c44b22de 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -36,6 +36,12 @@ For example: self.check_object_permissions(self.request, obj) return obj +#### Limitations of object level permissions + +For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects. + +Often when you're using object level permissions you'll also want to [filter the queryset][filtering] appropriately, to ensure that users only have visibility onto instances that they are permitted to view. + ## Setting the permission policy The default permission policy may be set globally, using the `DEFAULT_PERMISSION_CLASSES` setting. For example. @@ -237,6 +243,7 @@ The [REST Condition][rest-condition] package is another extension for building c [cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html [authentication]: authentication.md [throttling]: throttling.md +[filtering]: filtering.md [contribauth]: https://docs.djangoproject.com/en/1.0/topics/auth/#permissions [objectpermissions]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#handling-object-permissions [guardian]: https://github.com/lukaszb/django-guardian -- cgit v1.2.3 From 680fabe9dd2307014862beb1c2d77625e808788d Mon Sep 17 00:00:00 2001 From: Dave King Date: Thu, 17 Jul 2014 11:46:59 +0100 Subject: Update fields.md obj.__class__ will return the actual Class object, we want to serialise a string (accessed with obj.__class__.__name__)--- docs/api-guide/fields.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 58dbf977..6d1adcb0 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -347,7 +347,7 @@ As an example, let's create a field that can be used represent the class name of """ Serialize the object's class name. """ - return obj.__class__ + return obj.__class__.__name__ # Third party packages -- cgit v1.2.3 From 81d15aa9be72ac8b805fc728bd86f930ff1b17e7 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 20 Jul 2014 15:45:45 +0100 Subject: Add link to drf-extra-fields. Closes #1698 --- docs/api-guide/fields.md | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 58dbf977..cebfaac9 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -357,9 +357,16 @@ The following third party packages are also available. The [drf-compound-fields][drf-compound-fields] package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the `many=True` option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type. +## DRF Extra Fields + +The [drf-extra-fields][drf-extra-fields] package provides extra serializer fields for REST framework, including `Base64ImageField` and `PointField` classes. + + + [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 [drf-compound-fields]: http://drf-compound-fields.readthedocs.org +[drf-extra-fields]: https://github.com/Hipo/drf-extra-fields \ No newline at end of file -- cgit v1.2.3 From 48b02f016a827bc254aba2aedb81b472189c2165 Mon Sep 17 00:00:00 2001 From: Kyle Valade Date: Sun, 27 Jul 2014 14:01:43 -0700 Subject: Issue #1707: Add documentation to api-docs.viewsets notifying users that they should use the get_queryset() method when overriding a ModelViewSet method, such as list(). Otherwise, since queryset is a static property, the value will be cached for every instance of that ViewSet. --- docs/api-guide/viewsets.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 23b16575..774e11b7 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -70,6 +70,21 @@ There are two main advantages of using a `ViewSet` class over using a `View` cla 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. +## Overriding ModelViewSet Methods + +Overriding the ModelViewSet is the same as overriding anything else, except you will need to remember to clone `self.queryset` before you use it, which you can do by using the built-in `get_queryset` method. For example: + + class UserViewSet(viewsets.ModelViewSet): + """ + A viewset for viewing and editing user instances. + """ + queryset = User.objects.all() + + def list(self, request): + queryset = self.get_queryset() + serializer = UserSerializer(queryset, many=True) + return Response(serializer.data) + ## 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: @@ -142,7 +157,7 @@ The `@action` decorator will route `POST` requests by default, but may also acce @action(methods=['POST', 'DELETE']) def unset_password(self, request, pk=None): ... - + The two new actions will then be available at the urls `^users/{pk}/set_password/$` and `^users/{pk}/unset_password/$` -- cgit v1.2.3 From e40ffd60d44d736d7e27ff454cba1905f0becc26 Mon Sep 17 00:00:00 2001 From: Kyle Date: Mon, 28 Jul 2014 10:11:40 -0700 Subject: Issue #1707 - Add documentation about the caching of `GenericAPIView.queryset` to the `queryset` property, `get_queryset()`, and do generic-views.md; remove changes to the viewsets.md documentation from my last commit. --- docs/api-guide/generic-views.md | 8 +++++++- docs/api-guide/viewsets.md | 15 --------------- 2 files changed, 7 insertions(+), 16 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 7d06f246..b76c18cf 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -43,6 +43,12 @@ For more complex cases you might also want to override various methods on the vi return 20 return 100 + def list(self, request): + # Note the use of `get_queryset()` instead of `self.queryset` + queryset = self.get_queryset() + serializer = UserSerializer(queryset, many=True) + return Response(serializer.data) + For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something the following entry. url(r'^/users/', ListCreateAPIView.as_view(model=User), name='user-list') @@ -63,7 +69,7 @@ Each of the concrete generic views provided is built by combining `GenericAPIVie 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. +* `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. If you are overriding a view method, it is important that you call `get_queryset()` instead of accessing this property directly, as `queryset` will get evaluated once, and those results will be cached for all subsequent requests. * `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 model field that should be used to for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value. * `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`. diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 774e11b7..4f345abb 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -70,21 +70,6 @@ There are two main advantages of using a `ViewSet` class over using a `View` cla 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. -## Overriding ModelViewSet Methods - -Overriding the ModelViewSet is the same as overriding anything else, except you will need to remember to clone `self.queryset` before you use it, which you can do by using the built-in `get_queryset` method. For example: - - class UserViewSet(viewsets.ModelViewSet): - """ - A viewset for viewing and editing user instances. - """ - queryset = User.objects.all() - - def list(self, request): - queryset = self.get_queryset() - serializer = UserSerializer(queryset, many=True) - return Response(serializer.data) - ## 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: -- cgit v1.2.3 From fc8eb76c2259ea64a19876f040db4d93e834d39d Mon Sep 17 00:00:00 2001 From: Kyle Date: Mon, 28 Jul 2014 10:19:42 -0700 Subject: Issue #1707 - Add info about queryset property caching to get_queryset() docs. Add documentation to the get_queryset() method of generic-views.md regarding the caching of the queryset property. --- docs/api-guide/generic-views.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index b76c18cf..43c5782f 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -99,6 +99,8 @@ The following attributes are used to control pagination when used with list view 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. +This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests. + May be overridden to provide dynamic behavior such as returning a queryset that is specific to the user making the request. For example: -- cgit v1.2.3 From 57d6e04ff5512f11594e29bf49c47b610594666c Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 30 Jul 2014 12:50:36 +0100 Subject: Add django-rest-framework-mongoengine link. Closes #1722 Closes #1562 Closes #1545 --- docs/api-guide/serializers.md | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index cedf1ff7..72568e53 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -580,7 +580,16 @@ The following custom model serializer could be used as a base class for model se def get_pk_field(self, model_field): return None +--- + +# Third party packages + +The following third party packages are also available. + +## MongoengineModelSerializer +The [django-rest-framework-mongoengine][mongoengine] package provides a `MongoEngineModelSerializer` serializer class that supports using MongoDB as the storage layer for Django REST framework. [cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion [relations]: relations.md +[mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine -- cgit v1.2.3 From c0f002b09d07275d8dbba7266d1180623b78f6a5 Mon Sep 17 00:00:00 2001 From: Kevin London Date: Thu, 31 Jul 2014 12:41:15 -0700 Subject: Updated Permissions doc link to Django docs The previous link went to version 1 docs so it was a dead link.--- docs/api-guide/permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index c44b22de..38ae3d0a 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -244,7 +244,7 @@ The [REST Condition][rest-condition] package is another extension for building c [authentication]: authentication.md [throttling]: throttling.md [filtering]: filtering.md -[contribauth]: https://docs.djangoproject.com/en/1.0/topics/auth/#permissions +[contribauth]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#custom-permissions [objectpermissions]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#handling-object-permissions [guardian]: https://github.com/lukaszb/django-guardian [get_objects_for_user]: http://pythonhosted.org/django-guardian/api/guardian.shortcuts.html#get-objects-for-user -- cgit v1.2.3 From 3217842346cebda578e9398b89fe60fed7d1b2d8 Mon Sep 17 00:00:00 2001 From: Rob Terhaar Date: Wed, 6 Aug 2014 18:55:08 -0400 Subject: minor doc fix, @api_view() needs an iterable --- docs/api-guide/throttling.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index b7c320f0..92f4c22b 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -58,7 +58,7 @@ using the `APIView` class based views. Or, if you're using the `@api_view` decorator with function based views. - @api_view('GET') + @api_view(['GET']) @throttle_classes([UserRateThrottle]) def example_view(request, format=None): content = { -- cgit v1.2.3 From 5eb901cd2a7dc2e33034f49e076bf7af7656655a Mon Sep 17 00:00:00 2001 From: Federico Capoano Date: Fri, 8 Aug 2014 14:25:02 +0200 Subject: docs: added reference to DRF-gis in fields added django-rest-framework-gis to third party packages section in /docs/api-guide/fields.md--- docs/api-guide/fields.md | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 813fc381..dd279541 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -361,6 +361,9 @@ The [drf-compound-fields][drf-compound-fields] package provides "compound" seria The [drf-extra-fields][drf-extra-fields] package provides extra serializer fields for REST framework, including `Base64ImageField` and `PointField` classes. +## django-rest-framework-gis + +The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer. [cite]: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data @@ -370,3 +373,4 @@ The [drf-extra-fields][drf-extra-fields] package provides extra serializer field [iso8601]: http://www.w3.org/TR/NOTE-datetime [drf-compound-fields]: http://drf-compound-fields.readthedocs.org [drf-extra-fields]: https://github.com/Hipo/drf-extra-fields +[django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis -- cgit v1.2.3 From c462a43a872b45d27def08a3d17799b930950860 Mon Sep 17 00:00:00 2001 From: Federico Capoano Date: Fri, 8 Aug 2014 14:39:56 +0200 Subject: docs: added reference to gis serializer added reference to GeoFeatureModelSerializer of django-rest-framework-gis--- docs/api-guide/serializers.md | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 72568e53..29b7851b 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -590,6 +590,11 @@ The following third party packages are also available. The [django-rest-framework-mongoengine][mongoengine] package provides a `MongoEngineModelSerializer` serializer class that supports using MongoDB as the storage layer for Django REST framework. +## GeoFeatureModelSerializer + +The [django-rest-framework-gis][django-rest-framework-gis] package provides a `GeoFeatureModelSerializer` serializer class that supports GeoJSON both for read and write operations. + [cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion [relations]: relations.md [mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine +[django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis -- cgit v1.2.3 From 6edbabe0e1ffa8111284c0af94a8f878f7056413 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 18 Aug 2014 10:58:00 +0100 Subject: Link to Django docs on widgets. Closes #1760. --- docs/api-guide/fields.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index dd279541..b41e0ebc 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -62,7 +62,7 @@ A dictionary of error codes to error messages. ### `widget` Used only if rendering the field to HTML. -This argument sets the widget that should be used to render the field. +This argument sets the widget that should be used to render the field. For more details, and a list of available widgets, see [the Django documentation on form widgets][django-widgets]. ### `label` @@ -370,6 +370,7 @@ The [django-rest-framework-gis][django-rest-framework-gis] package provides geog [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 +[django-widgets]: https://docs.djangoproject.com/en/dev/ref/forms/widgets/ [iso8601]: http://www.w3.org/TR/NOTE-datetime [drf-compound-fields]: http://drf-compound-fields.readthedocs.org [drf-extra-fields]: https://github.com/Hipo/drf-extra-fields -- cgit v1.2.3 From ae2ab496c2fa42ed60d325df4579b1ba38d3bfb5 Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Mon, 18 Aug 2014 13:48:46 +0200 Subject: Updated docs for South v1.0 --- docs/api-guide/authentication.md | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index ad6257dd..ee59b375 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -204,18 +204,11 @@ Note that the default `obtain_auth_token` view explicitly uses JSON requests and #### Schema migrations -The `rest_framework.authtoken` app includes both a Django native migration (for Django versions >1.7) and a south migration that will create the authtoken table. +The `rest_framework.authtoken` app includes both Django native migrations (for Django versions >1.7) and South migrations (for Django versions <1.7) that will create the authtoken table. ---- -**Note** By default both Django (>1.7) and South will look for a module named `migrations`. To avoid a collision here, in order to use South you **must** provide the `SOUTH_MIGRATION_MODULES` option in your `settings.py`: - - - SOUTH_MIGRATION_MODULES = { - 'authtoken': 'rest_framework.authtoken.south_migrations', - } - -This tells South to look in the `south_migrations` module for the `authtoken` app. +**Note**: From REST Framework v2.4.0 using South with Django <1.7 requires upgrading South v1.0+ ---- -- cgit v1.2.3 From db4426fc35a92d2b0e263fd8a5702203cb3e06ed Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Mon, 18 Aug 2014 13:52:57 +0200 Subject: Alter other reference to migrations. --- docs/api-guide/authentication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index ee59b375..bc2ca4b6 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -129,7 +129,7 @@ To use the `TokenAuthentication` scheme you'll need to [configure the authentica --- -**Note:** Make sure to run `manage.py syncdb` after changing your settings. Both Django native (from v1.7) and South migrations for the `authtoken` database tables are provided. See [Schema migrations](#schema-migrations) below. +**Note:** Make sure to run `manage.py syncdb` after changing your settings. The 'rest_framework.authtoken' provides both Django (from v1.7) and South database migrations. See [Schema migrations](#schema-migrations) below. --- -- cgit v1.2.3 From 556948661acc4bf038ecdd0cb17b1e19f2080061 Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Mon, 18 Aug 2014 13:54:46 +0200 Subject: Improve wording. --- docs/api-guide/authentication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index bc2ca4b6..343466ee 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -129,7 +129,7 @@ To use the `TokenAuthentication` scheme you'll need to [configure the authentica --- -**Note:** Make sure to run `manage.py syncdb` after changing your settings. The 'rest_framework.authtoken' provides both Django (from v1.7) and South database migrations. See [Schema migrations](#schema-migrations) below. +**Note:** Make sure to run `manage.py syncdb` after changing your settings. The `rest_framework.authtoken` app provides both Django (from v1.7) and South database migrations. See [Schema migrations](#schema-migrations) below. --- -- cgit v1.2.3 From 0c65e028b604490d498e43083fc3b46da05144fe Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 19 Aug 2014 23:25:12 +0100 Subject: Release notes --- docs/api-guide/viewsets.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index b32f5a80..9030e3ee 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -146,7 +146,7 @@ The decorators can additionally take extra arguments that will be set for the ro def set_password(self, request, pk=None): ... -The `@action` decorator will route `POST` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example: +Theses decorators will route `GET` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example: @detail_route(methods=['post', 'delete']) def unset_password(self, request, pk=None): -- cgit v1.2.3 From 4d8c63abc996bcb44d7a68dd7a7234b0d9f148a0 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 20 Aug 2014 17:15:46 +0100 Subject: Deprecate .model in related routers/permissions --- docs/api-guide/permissions.md | 10 ++++++++-- docs/api-guide/routers.md | 4 ++-- 2 files changed, 10 insertions(+), 4 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 38ae3d0a..e867a456 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -114,7 +114,7 @@ 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 *is authenticated* and has the *relevant model permissions* assigned. +This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that has a `.queryset` property set. 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. @@ -124,6 +124,12 @@ The default behaviour can also be overridden to support custom model permissions To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details. +#### Using with views that do not include a `queryset` attribute. + +If you're using this permission with a view that uses an overridden `get_queryset()` method there may not be a `queryset` attribute on the view. In this case we suggest also marking the view with a sential queryset, so that this class can determine the required permissions. For example: + + queryset = User.objects.none() # Required for DjangoModelPermissions + ## DjangoModelPermissionsOrAnonReadOnly Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API. @@ -132,7 +138,7 @@ Similar to `DjangoModelPermissions`, but also allows unauthenticated users to ha This permission class ties into Django's standard [object permissions framework][objectpermissions] that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as [django-guardian][guardian]. -When applied to a view that has a `.model` property, authorization will only be granted if the user *is authenticated* and has the *relevant per-object permissions* and *relevant model permissions* assigned. +As with `DjangoModelPermissions`, this permission must only be applied to views that have a `.queryset` property. Authorization will only be granted if the user *is authenticated* and has the *relevant per-object permissions* and *relevant model permissions* assigned. * `POST` requests require the user to have the `add` permission on the model instance. * `PUT` and `PATCH` requests require the user to have the `change` permission on the model instance. diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 2d760ca4..61a476b8 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -41,9 +41,9 @@ The example above would generate the following URL patterns: **Note**: The `base_name` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part. -Typically you won't *need* to specify the `base-name` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have any `.model` or `.queryset` attribute set. If you try to register that viewset you'll see an error like this: +Typically you won't *need* to specify the `base-name` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this: - 'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.model' or '.queryset' attribute. + 'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute. This means you'll need to explicitly set the `base_name` argument when registering the viewset, as it could not be automatically determined from the model name. -- cgit v1.2.3 From 8b2052172cf7138203e683731c30bd279c6e722a Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 21 Aug 2014 12:25:20 +0100 Subject: Add .model deprecation to release notes --- docs/api-guide/generic-views.md | 8 ++++---- docs/api-guide/settings.md | 6 ------ 2 files changed, 4 insertions(+), 10 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index e9efe709..cab382fb 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -74,10 +74,6 @@ The following attributes control the basic view behavior. * `lookup_field` - The model field that should be used to for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value. * `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`. -**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 `DEFAULT_MODEL_SERIALIZER_CLASS` setting will determine the base serializer class. Note that `model` is only ever used for generating a default queryset or serializer class - the `queryset` and `serializer_class` attributes are always preferred if provided. - **Pagination**: The following attributes are used to control pagination when used with list views. @@ -91,6 +87,10 @@ The following attributes are used to control pagination when used with list view * `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. +**Deprecated attributes**: + +* `model` - This shortcut may be used instead of setting either (or both) of the `queryset`/`serializer_class` attributes. The explicit style is preferred over the `.model` shortcut, and usage of this attribute is now deprecated. + ### Methods **Base methods**: diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 8bde4d87..27a09163 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -100,12 +100,6 @@ Default: `'rest_framework.negotiation.DefaultContentNegotiation'` *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 A class the determines the default serialization style for paginated responses. -- cgit v1.2.3 From 8e3f7700f6ed6fbe1338afc68e27c06d702fac8d Mon Sep 17 00:00:00 2001 From: Federico Capoano Date: Mon, 25 Aug 2014 12:29:10 +0200 Subject: docs: added drf-hstore to third party fields added a reference to django-rest-framework-hstore in docs/api-guide/fields.md--- docs/api-guide/fields.md | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 95d9fad3..bfbff2ad 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -366,6 +366,9 @@ The [drf-extra-fields][drf-extra-fields] package provides extra serializer field The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer. +## django-rest-framework-hstore + +The [django-rest-framework-hstore][django-rest-framework-hstore] package provides an `HStoreField` to support [django-hstore][django-hstore] `DictionaryField` model field. [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 @@ -376,3 +379,5 @@ The [django-rest-framework-gis][django-rest-framework-gis] package provides geog [drf-compound-fields]: http://drf-compound-fields.readthedocs.org [drf-extra-fields]: https://github.com/Hipo/drf-extra-fields [django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis +[django-rest-framework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore +[django-hstore]: https://github.com/djangonauts/django-hstore -- cgit v1.2.3 From eb81c55d16435537ff7801839cc4d2704526914f Mon Sep 17 00:00:00 2001 From: Federico Capoano Date: Mon, 25 Aug 2014 12:32:44 +0200 Subject: docs: added HStoreSerializer to third party serializers added a reference to django-rest-framework-hstore in docs/api-guide/serializers.md--- docs/api-guide/serializers.md | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 29b7851b..a3694510 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -594,7 +594,13 @@ The [django-rest-framework-mongoengine][mongoengine] package provides a `MongoEn The [django-rest-framework-gis][django-rest-framework-gis] package provides a `GeoFeatureModelSerializer` serializer class that supports GeoJSON both for read and write operations. +## HStoreSerializer + +The [django-rest-framework-hstore][django-rest-framework-hstore] package provides an `HStoreSerializer` to support [django-hstore][django-hstore] `DictionaryField` model field and its `schema-mode` feature. + [cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion [relations]: relations.md [mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine [django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis +[django-rest-framework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore +[django-hstore]: https://github.com/djangonauts/django-hstore -- cgit v1.2.3 From 19076510f4039aa6886854679e21352fffb5354f Mon Sep 17 00:00:00 2001 From: Nathan Hubbell Date: Tue, 26 Aug 2014 17:31:08 -0700 Subject: Update generic-views.md --- docs/api-guide/generic-views.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index e9efe709..48b77a6e 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -49,7 +49,7 @@ For more complex cases you might also want to override various methods on the vi serializer = UserSerializer(queryset, many=True) return Response(serializer.data) -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. +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 like the following entry: url(r'^/users/', ListCreateAPIView.as_view(model=User), name='user-list') -- cgit v1.2.3 From be21cafd2bbca36bcf9e55b1565ba57c9e3f76d6 Mon Sep 17 00:00:00 2001 From: Nathan Hubbell Date: Wed, 27 Aug 2014 17:57:40 -0700 Subject: Update generic-views.md Small grammar changes.--- docs/api-guide/generic-views.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 48b77a6e..2ceb2d57 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -101,7 +101,7 @@ Returns the queryset that should be used for list views, and that should be used This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests. -May be overridden to provide dynamic behavior such as returning a queryset that is specific to the user making the request. +May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request. For example: @@ -113,7 +113,7 @@ For example: 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. +May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg. For example: @@ -133,7 +133,7 @@ Note that if your API doesn't include any object level permissions, you may opti Returns the classes that should be used to filter the queryset. Defaults to returning the `filter_backends` attribute. -May be override to provide more complex behavior with filters, as using different (or even exlusive) lists of filter_backends depending on different criteria. +May be overridden to provide more complex behavior with filters, such as using different (or even exlusive) lists of filter_backends depending on different criteria. For example: @@ -149,7 +149,7 @@ For example: 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 users. +May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users. For example: @@ -162,7 +162,7 @@ For example: Returns the page size to use with pagination. By default this uses the `paginate_by` attribute, and may be overridden by the client 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. +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: @@ -204,7 +204,7 @@ You won't typically need to override the following methods, although you might n # Mixins -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. +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 -- cgit v1.2.3 From d8eb9e6d45c227582559ec4318b1f92562c718da Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 10:48:16 +0100 Subject: Docs whitespace fix. --- docs/api-guide/generic-views.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index b1c4e65a..d30b7f9b 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -19,8 +19,8 @@ Typically when using the generic views, you'll override the view, and set severa from django.contrib.auth.models import User from myapp.serializers import UserSerializer - from rest_framework import generics - from rest_framework.permissions import IsAdminUser + from rest_framework import generics + from rest_framework.permissions import IsAdminUser class UserList(generics.ListCreateAPIView): queryset = User.objects.all() -- cgit v1.2.3 From 0f8fdf4e72b67ff46474c13c8b532bf319a58099 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 10:57:24 +0100 Subject: Remove `allow_empty`. Closes #1774. --- docs/api-guide/generic-views.md | 2 -- 1 file changed, 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index d30b7f9b..49be0cae 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -212,8 +212,6 @@ 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` response, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`. - ## CreateModelMixin Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance. -- cgit v1.2.3 From baa518cd890103173dd18857c609432bd47c6be4 Mon Sep 17 00:00:00 2001 From: Jharrod LaFon Date: Fri, 5 Sep 2014 15:30:01 -0700 Subject: Moved OAuth support out of DRF and into a separate package, per #1767 --- docs/api-guide/authentication.md | 99 ---------------------------------------- docs/api-guide/permissions.md | 17 ------- 2 files changed, 116 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 343466ee..3d4e0f72 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -247,105 +247,6 @@ 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', - ) - -Then add `OAuth2Authentication` to your global `DEFAULT_AUTHENTICATION` setting: - - 'DEFAULT_AUTHENTICATION_CLASSES': ( - 'rest_framework.authentication.OAuth2Authentication', - ), - -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/ - -### Alternative OAuth 2 implementations - -Note that [Django OAuth Toolkit][django-oauth-toolkit] is an alternative external package that also includes OAuth 2.0 support for REST framework. - --- # Custom authentication diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index e867a456..a32db4a2 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -148,21 +148,6 @@ Note that `DjangoObjectPermissions` **does not** require the `django-guardian` p As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoModelPermissions` and setting the `.perms_map` property. Refer to the source code for details. Note that if you add a custom `view` permission for `GET`, `HEAD` and `OPTIONS` requests, you'll probably also want to consider adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions. -## 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 @@ -254,8 +239,6 @@ The [REST Condition][rest-condition] package is another extension for building c [objectpermissions]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#handling-object-permissions [guardian]: https://github.com/lukaszb/django-guardian [get_objects_for_user]: http://pythonhosted.org/django-guardian/api/guardian.shortcuts.html#get-objects-for-user -[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 [drf-any-permissions]: https://github.com/kevin-brown/drf-any-permissions -- cgit v1.2.3 From fe06d96dec0182f56fd4e72bcd71a26c923bb834 Mon Sep 17 00:00:00 2001 From: Darren Maki Date: Sun, 7 Sep 2014 12:53:21 -0400 Subject: Fixing quotes in filtering.md Incorrect quotes used in examples.--- docs/api-guide/filtering.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index ec5ab61f..cfeb4334 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -193,7 +193,7 @@ filters using `Manufacturer` name. For example: class ProductFilter(django_filters.FilterSet): class Meta: model = Product - fields = ['category', 'in_stock', 'manufacturer__name`] + fields = ['category', 'in_stock', 'manufacturer__name'] This enables us to make queries like: @@ -211,7 +211,7 @@ This is nice, but it exposes the Django's double underscore convention as part o class Meta: model = Product - fields = ['category', 'in_stock', 'manufacturer`] + fields = ['category', 'in_stock', 'manufacturer'] And now you can execute: -- cgit v1.2.3 From e76f56a3d687159327b8bef5bf9bc2ad28c99ea3 Mon Sep 17 00:00:00 2001 From: S. Andrew Sheppard Date: Wed, 10 Sep 2014 11:55:43 -0500 Subject: add django rest pandas --- docs/api-guide/renderers.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 7a3429bf..20eed70d 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -444,6 +444,11 @@ Comma-separated values are a plain-text tabular data format, that can be easily [djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy]. +## Pandas (CSV, Excel, PNG) + +[Django REST Pandas] provides a serializer and renderers that support additional data processing and output via the [Pandas] DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both `.xls` and `.xlsx`), and a number of [other formats]. It is maintained by [S. Andrew Sheppard][sheppard] as part of the [wq Project][wq]. + + [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process [conneg]: content-negotiation.md [browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers @@ -466,4 +471,9 @@ Comma-separated values are a plain-text tabular data format, that can be easily [ultrajson]: https://github.com/esnme/ultrajson [hzy]: https://github.com/hzy [drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer -[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case \ No newline at end of file +[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case +[Django REST Pandas]: https://github.com/wq/django-rest-pandas +[Pandas]: http://pandas.pydata.org/ +[other formats]: https://github.com/wq/django-rest-pandas#supported-formats +[sheppard]: https://github.com/sheppard +[wq]: https://github.com/wq -- cgit v1.2.3 From 19b8f779de82fa4737b37fb4359145af0b07a56c Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 11 Sep 2014 20:43:44 +0100 Subject: Throttles now use Retry-After header and no longer support the custom style --- docs/api-guide/throttling.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index 832304f1..16a7457b 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -178,6 +178,8 @@ To create a custom throttle, override `BaseThrottle` and implement `.allow_reque Optionally you may also override the `.wait()` method. If implemented, `.wait()` should return a recommended number of seconds to wait before attempting the next request, or `None`. The `.wait()` method will only be called if `.allow_request()` has previously returned `False`. +If the `.wait()` method is implemented and the request is throttled, then a `Retry-After` header will be included in the response. + ## Example The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests. -- cgit v1.2.3 From f95e7fae38968f58e742b93842bda9110a61b9f7 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 12 Sep 2014 12:40:53 +0100 Subject: Updating docs --- docs/api-guide/renderers.md | 29 +++++---------------------- docs/api-guide/settings.md | 48 ++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 50 insertions(+), 27 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 7a3429bf..b1adf31f 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -74,37 +74,18 @@ If your API includes views that can serve both regular webpages and API response Renders the request data into `JSON`, using utf-8 encoding. -Note that non-ascii characters will be rendered using JSON's `\uXXXX` character escape. For example: +Note that the default style is to include unicode characters, and render the response using a compact style with no uneccessary whitespace: - {"unicode black star": "\u2605"} + {"unicode black star":"★","value":999} The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`. { - "unicode black star": "\u2605" + "unicode black star": "★", + "value": 999 } -**.media_type**: `application/json` - -**.format**: `'.json'` - -**.charset**: `None` - -## UnicodeJSONRenderer - -Renders the request data into `JSON`, using utf-8 encoding. - -Note that non-ascii characters will not be character escaped. For example: - - {"unicode black star": "★"} - -The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`. - - { - "unicode black star": "★" - } - -Both the `JSONRenderer` and `UnicodeJSONRenderer` styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. +The default JSON encoding style can be altered using the `UNICODE_JSON` and `COMPACT_JSON` settings keys. **.media_type**: `application/json` diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 27a09163..6a855c92 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -265,7 +265,7 @@ A format string that should be used by default for rendering the output of `Date May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string. -Default: `None` +Default: `'iso-8601'` #### DATETIME_INPUT_FORMATS @@ -281,7 +281,7 @@ A format string that should be used by default for rendering the output of `Date May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string. -Default: `None` +Default: `'iso-8601'` #### DATE_INPUT_FORMATS @@ -297,7 +297,7 @@ A format string that should be used by default for rendering the output of `Time May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string. -Default: `None` +Default: `'iso-8601'` #### TIME_INPUT_FORMATS @@ -309,6 +309,46 @@ Default: `['iso-8601']` --- +## Encodings + +#### UNICODE_JSON + +When set to `True`, JSON responses will allow unicode characters in responses. For example: + + {"unicode black star":"★"} + +When set to `False`, JSON responses will escape non-ascii characters, like so: + + {"unicode black star":"\u2605"} + +Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. The unicode style is prefered as being more user-friendly when inspecting API responses. + +Default: `True` + +#### COMPACT_JSON + +When set to `True`, JSON responses will return compact representations, with no spacing after `':'` and `','` characters. For example: + + {"is_admin":false,"email":"jane@example"} + +When set to `False`, JSON responses will return slightly more verbose representations, like so: + + {"is_admin": false, "email": "jane@example"} + +The default style is to return minified responses, in line with [Heroku's API design guidelines][heroku-minified-json]. + +Default: `True` + +#### COERCE_DECIMAL_TO_STRING + +When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations. + +When set to `True`, the serializer `DecimalField` class will return strings instead of `Decimal` objects. When set to `False`, serializers will return `Decimal` objects, which the default JSON encoder will return as floats. + +Default: `True` + +--- + ## View names and descriptions **The following settings are used to generate the view names and descriptions, as used in responses to `OPTIONS` requests, and as used in the browsable API.** @@ -378,4 +418,6 @@ An integer of 0 or more, that may be used to specify the number of application p Default: `None` [cite]: http://www.python.org/dev/peps/pep-0020/ +[rfc4627]: http://www.ietf.org/rfc/rfc4627.txt +[heroku-minified-json]: https://github.com/interagent/http-api-design#keep-json-minified-in-all-responses [strftime]: http://docs.python.org/2/library/time.html#time.strftime -- cgit v1.2.3 From 4fceceae7d1abf4d841677daee2636273ff09de8 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 12 Sep 2014 20:09:08 +0100 Subject: DecimalField documentation --- docs/api-guide/fields.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index bfbff2ad..f0778318 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -274,7 +274,27 @@ Corresponds to `django.db.models.fields.FloatField`. ## DecimalField -A decimal representation. +A decimal representation, represented in Python by a Decimal instance. + +Has two required arguments: + +- `max_digits` The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places. + +- `decimal_places` The number of decimal places to store with the number. + +For example, to validate numbers up to 999 with a resolution of 2 decimal places, you would use: + + serializers.DecimalField(max_digits=5, decimal_places=2) + +And to validate numbers up to anything lesss than one billion with a resolution of 10 decimal places: + + serializers.DecimalField(max_digits=19, decimal_places=10) + +This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer. + +If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise. + +**Signature:** `DecimalField(max_digits, decimal_places, coerce_to_string=None)` Corresponds to `django.db.models.fields.DecimalField`. -- cgit v1.2.3 From e5af0bbb353e772473b1d9fcfc896bfd7365db2a Mon Sep 17 00:00:00 2001 From: Matthew J Morrison Date: Wed, 17 Sep 2014 07:49:54 -0500 Subject: Clarify "raised inside REST framework" I ran into an issue today where I was not seeing the rest_framework.views.exception_handler do what I thought it should be doing. It turned out that I had imported View from rest_framework.views rather than importing APIView from rest_framework.views. The phrase "raised inside REST framework" was confusing as I was debugging this issue. I was unsure if that meant that I could raise those exceptions in my code or if it had to originate from within framework code. I'm not sure if the proposed wording is ideal, I just wanted to point out what I found to be confusing.--- docs/api-guide/exceptions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 66e18173..33c4dc91 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -84,7 +84,7 @@ Note that the exception handler will only be called for responses generated by r **Signature:** `APIException()` -The **base class** for all exceptions raised inside REST framework. +The **base class** for all exceptions raised inside an APIView class or @api_view. To provide a custom exception, subclass `APIException` and set the `.status_code` and `.default_detail` properties on the class. -- cgit v1.2.3 From 764366b2e11ad9ad85dd34500e95721011cae7d4 Mon Sep 17 00:00:00 2001 From: Matthew J Morrison Date: Wed, 17 Sep 2014 11:29:15 -0500 Subject: Fixed code formatting --- docs/api-guide/exceptions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 33c4dc91..e61dcfa9 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -84,7 +84,7 @@ Note that the exception handler will only be called for responses generated by r **Signature:** `APIException()` -The **base class** for all exceptions raised inside an APIView class or @api_view. +The **base class** for all exceptions raised inside an `APIView` class or `@api_view`. To provide a custom exception, subclass `APIException` and set the `.status_code` and `.default_detail` properties on the class. -- cgit v1.2.3 From da385c9c1f9deeeefd705154a6e6612d6d62f41b Mon Sep 17 00:00:00 2001 From: Collin Anderson Date: Tue, 23 Sep 2014 17:08:38 -0400 Subject: remove patterns and strings from urls #1898 --- docs/api-guide/authentication.md | 7 ++++--- docs/api-guide/format-suffixes.md | 13 +++++++------ 2 files changed, 11 insertions(+), 9 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 343466ee..0ec5bad1 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -190,9 +190,10 @@ If you've already created some users, you can generate tokens for all existing u 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') - ) + from rest_framework.authtoken import views + urlpatterns += [ + url(r'^api-token-auth/', views.obtain_auth_token) + ] Note that the URL part of the pattern can be whatever you want to use. diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md index 529738e3..76a3367b 100644 --- a/docs/api-guide/format-suffixes.md +++ b/docs/api-guide/format-suffixes.md @@ -26,12 +26,13 @@ Arguments: Example: from rest_framework.urlpatterns import format_suffix_patterns - - urlpatterns = patterns('blog.views', - url(r'^/$', 'api_root'), - url(r'^comments/$', 'comment_list'), - url(r'^comments/(?P[0-9]+)/$', 'comment_detail') - ) + from blog import views + + urlpatterns = [ + url(r'^/$', views.apt_root), + url(r'^comments/$', views.comment_list), + url(r'^comments/(?P[0-9]+)/$', views.comment_detail) + ] urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) -- cgit v1.2.3 From dfab9af294972720f59890967cd9ae1a6c0796b6 Mon Sep 17 00:00:00 2001 From: Craig de Stigter Date: Fri, 3 Oct 2014 08:41:18 +1300 Subject: Minor: fix spelling and grammar, mostly in 3.0 announcement --- docs/api-guide/fields.md | 2 +- docs/api-guide/renderers.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index f0778318..292a51d8 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -286,7 +286,7 @@ For example, to validate numbers up to 999 with a resolution of 2 decimal places serializers.DecimalField(max_digits=5, decimal_places=2) -And to validate numbers up to anything lesss than one billion with a resolution of 10 decimal places: +And to validate numbers up to anything less than one billion with a resolution of 10 decimal places: serializers.DecimalField(max_digits=19, decimal_places=10) diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 2e1c892f..db7436c2 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -74,7 +74,7 @@ If your API includes views that can serve both regular webpages and API response Renders the request data into `JSON`, using utf-8 encoding. -Note that the default style is to include unicode characters, and render the response using a compact style with no uneccessary whitespace: +Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace: {"unicode black star":"★","value":999} -- cgit v1.2.3 From 6637b2fae0dab65447ff0bfd5ac0ba68644446eb Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 9 Oct 2014 11:08:26 +0100 Subject: Document the Metadata API --- docs/api-guide/metadata.md | 103 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 docs/api-guide/metadata.md (limited to 'docs/api-guide') diff --git a/docs/api-guide/metadata.md b/docs/api-guide/metadata.md new file mode 100644 index 00000000..c3f036b7 --- /dev/null +++ b/docs/api-guide/metadata.md @@ -0,0 +1,103 @@ + + +# Metadata + +> [The `OPTIONS`] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. +> +> — [RFC7231, Section 4.3.7.][cite] + +REST framework includes a configurable mechanism for determining how your API should respond to `OPTIONS` requests. This allows you to return API schema or other resource information. + +There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP `OPTIONS` requests, so we provide an ad-hoc style that returns some useful information. + +Here's an example response that demonstrates the information that is returned by default. + + HTTP 200 OK + Allow: GET, POST, HEAD, OPTIONS + Content-Type: application/json + + { + "name": "To Do List", + "description": "List existing 'To Do' items, or create a new item.", + "renders": [ + "application/json", + "text/html" + ], + "parses": [ + "application/json", + "application/x-www-form-urlencoded", + "multipart/form-data" + ], + "actions": { + "POST": { + "note": { + "type": "string", + "required": false, + "read_only": false, + "label": "title", + "max_length": 100 + } + } + } + } + +## Setting the metadata scheme + +You can set the metadata class globally using the `'DEFAULT_METADATA_CLASS'` settings key: + + REST_FRAMEWORK = { + 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata' + } + +Or you can set the metadata class individually for a view: + + class APIRoot(APIView): + metadata_class = APIRootMetadata + + def get(self, request, format=None): + return Response({ + ... + }) + +The REST framework package only includes a single metadata class implementation, named `SimpleMetadata`. If you want to use an alternative style you'll need to implement a custom metadata class. + +## Creating schema endpoints + +If you have specific requirements for creating schema endpoints that are accessed with regular `GET` requests, you might consider re-using the metadata API for doing so. + +For example, the following additional route could be used on a viewset to provide a linkable schema endpoint. + + @list_route(methods=['GET']) + def schema(self, request): + meta = self.metadata_class() + data = meta.determine_metadata(request, self) + return Response(data) + +There are a couple of reasons that you might choose to take this approach, including that `OPTIONS` responses [are not cacheable][no-options]. + +--- + +# Custom metadata classes + +If you want to provide a custom metadata class you should override `BaseMetadata` and implement the `determine_metadata(self, request, view)` method. + +Useful things that you might want to do could include returning schema information, using a format such as [JSON schema][json-schema], or returning debug information to admin users. + +## Example + +The following class could be used to limit the information that is returned to `OPTIONS` requests. + + class MinimalMetadata(BaseMetadata): + """ + Don't include field and other information for `OPTIONS` requests. + Just return the name and description. + """ + def determine_metadata(self, request, view): + return { + 'name': view.get_view_name(), + 'description': view.get_view_description() + } + +[cite]: http://tools.ietf.org/html/rfc7231#section-4.3.7 +[no-options]: https://www.mnot.net/blog/2012/10/29/NO_OPTIONS +[json-schema]: http://json-schema.org/ -- cgit v1.2.3 From babdc78e61ac915fa4a01bdfb04e11a32dbf5d79 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 9 Oct 2014 11:39:01 +0100 Subject: Typo --- docs/api-guide/validators.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 docs/api-guide/validators.md (limited to 'docs/api-guide') diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md new file mode 100644 index 00000000..e69de29b -- cgit v1.2.3 From 113a28ed8ad65d912180e8be7a92b679251b0249 Mon Sep 17 00:00:00 2001 From: konradhalas Date: Thu, 16 Oct 2014 13:48:18 +0200 Subject: Add djoser to authentication docs. --- docs/api-guide/authentication.md | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 0ec5bad1..b355012e 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -415,6 +415,10 @@ The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let y HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] package which provides an easy to use HTTP Signature Authentication mechanism. +## Djoser + +[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system. + [cite]: http://jacobian.org/writing/rest-worst-practices/ [http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2 [http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4 @@ -449,3 +453,4 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a [hawk]: https://github.com/hueniverse/hawk [mohawk]: http://mohawk.readthedocs.org/en/latest/ [mac]: http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05 +[djoser]: https://github.com/sunscrapers/djoser -- cgit v1.2.3 From f25f05dde58908ca6885c88499e4d5984f0f3502 Mon Sep 17 00:00:00 2001 From: Andrew Conti Date: Wed, 29 Oct 2014 16:31:36 -0400 Subject: Update authentication.md Based on the [new documentation](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.get_user_model) for Django 1.7 we should now use: ```python @receiver(post_save, sender=settings.AUTH_USER_MODEL) ``` instead of: ```python @receiver(post_save, sender=get_user_model()) ``` because `get_user_model()` only works once Django has imported all models. Otherwise you'll get: ```python django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. ``` When trying to start your sever after adding token authentication. From the Docs, ( linked above as well ) : >New in Django 1.7: >When connecting to signals sent by the User model, you should specify the custom model using the AUTH_USER_MODEL setting.--- docs/api-guide/authentication.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index b355012e..3a5156fd 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -168,12 +168,13 @@ The `curl` command line tool may be useful for testing token authenticated APIs. If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal. + from django.conf import settings from django.contrib.auth import get_user_model from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token - @receiver(post_save, sender=get_user_model()) + @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) -- cgit v1.2.3 From 27622058872c00e357deb7d7e86619a793ef4b41 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 31 Oct 2014 13:47:36 +0000 Subject: Validator documentation and tweaks --- docs/api-guide/validators.md | 183 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index e69de29b..52c9e082 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -0,0 +1,183 @@ + + +# Validators + +> Validators can be useful for re-using validation logic between different types of fields. +> +> — [Django documentation][cite] + +Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes. + +Sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes. + +## Validation in REST framework + +Validation in Django REST framework serializers is handled a little differently to how validation works in Django's `ModelForm` class. + +With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons: + +* It introduces a proper separation of concerns, making your code behaviour more obvious. +* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behaviour being used for `ModelSerializer` is simple to replicate. +* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behaviour being called on the model instance. + +When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using a `Serializer` classes instead, then you need to define the validation rules explicitly. + +#### Example + +As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint. + + class CustomerReportRecord(models.Model): + time_raised = models.DateTimeField(default=timezone.now, editable=False) + reference = models.CharField(unique=True, max_length=20) + description = models.TextField() + +Here's a basic `ModelSerializer` that we can use for creating or updating instances of `CustomerReportRecord`: + + class CustomerReportSerializer(serializers.ModelSerializer): + class Meta: + model = CustomerReportRecord + +If we open up the Django shell using `manage.py shell` we can now + + >>> from project.example.serializers import CustomerReportSerializer + >>> serializer = CustomerReportSerializer() + >>> print(repr(serializer)) + CustomerReportSerializer(): + id = IntegerField(label='ID', read_only=True) + time_raised = DateTimeField(read_only=True) + reference = CharField(max_length=20, validators=[]) + description = CharField(style={'type': 'textarea'}) + +The interesting bit here is the `reference` field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field. + +Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below. + +--- + +## UniqueValidator + +This validator can be used to enforce the `unique=True` constraint on model fields. +It takes a single required argument, and an optional `messages` argument: + +* `queryset` *required* - This is the queryset against which uniqueness should be enforced. +* `message` - The error message that should be used when validation fails. + +This validator should be applied to *serializer fields*, like so: + + slug = SlugField( + max_length=100, + validators=[UniqueValidator(queryset=BlogPost.objects.all())] + ) + +## UniqueTogetherValidator + +This validator can be used to enforce `unique_together` constraints on model instances. +It has two required arguments, and a single optional `messages` argument: + +* `queryset` *required* - This is the queryset against which uniqueness should be enforced. +* `fields` *required* - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class. +* `message` - The error message that should be used when validation fails. + +The validator should be applied to *serializer classes*, like so: + + class ExampleSerializer(serializers.Serializer): + # ... + class Meta: + # ToDo items belong to a parent list, and have an ordering defined + # by the 'position' field. No two items in a given list may share + # the same position. + validators = [ + UniqueTogetherValidator( + queryset=ToDoItem.objects.all(), + fields=('list', 'position') + ) + ] + +## UniqueForDateValidator + +## UniqueForMonthValidator + +## UniqueForYearValidator + +These validators can be used to enforce the `unique_for_date`, `unique_for_month` and `unique_for_year` constraints on model instances. They take the following arguments: + +* `queryset` *required* - This is the queryset against which uniqueness should be enforced. +* `field` *required* - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class. +* `date_field` *required* - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class. +* `message` - The error message that should be used when validation fails. + +The validator should be applied to *serializer classes*, like so: + + class ExampleSerializer(serializers.Serializer): + # ... + class Meta: + # Blog posts should have a slug that is unique for the current year. + validators = [ + UniqueForYearValidator( + queryset=BlogPostItem.objects.all(), + field='slug', + date_field='published' + ) + ] + +The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class `default=...`, because the value being used for the default wouldn't be generated until after the validation has run. + +There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using `ModelSerializer` you'll probably simply rely on the defaults that REST framework generates for you, but if you are using `Serializer` or simply want more explicit control, use on of the styles demonstrated below. + +#### Using with a writable date field. + +If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a `default` argument, or by setting `required=True`. + + published = serializers.DateTimeField(required=True) + +#### Using with a read-only date field. + +If you want the date field to be visible, but not editable by the user, then set `read_only=True` and additionally set a `default=...` argument. + + published = serializers.DateTimeField(read_only=True, default=timezone.now) + +The field will not be writable to the user, but the default value will still be passed through to the `validated_data`. + +#### Using with a hidden date field. + +If you want the date field to be entirely hidden from the user, then use `HiddenField`. This field type does not accept user input, but instead always returns it's default value to the `validated_data` in the serializer. + + published = serializers.HiddenField(default=timezone.now) + +--- + +# Writing custom validators + +You can use any of Django's existing validators, or write your own custom validators. + +## Function based + +A validator may be any callable that raises a `serializers.ValidationError` on failure. + + def even_number(value): + if value % 2 != 0: + raise serializers.ValidationError('This field must be an even number.') + +## Class based + +To write a class based validator, use the `__call__` method. Class based validators are useful as they allow you to parameterize and reuse behavior. + + class MultipleOf: + def __init__(self, base): + self.base = base + + def __call__(self, value): + if value % self.base != 0 + message = 'This field must be a multiple of %d.' % self.base + raise serializers.ValidationError(message) + +#### Using `set_context()` + +In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a `set_context` method on a class based validator. + + def set_context(self, serializer_field): + # Determine if this is an update or a create operation. + # In `__call__` we can then use that information to modify the validation behavior. + self.is_update = serializer_field.parent.instance is not None + +[cite]: https://docs.djangoproject.com/en/dev/ref/validators/ -- cgit v1.2.3 From 254701230d85612cf0210d4549c2d74f410a181d Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 31 Oct 2014 13:58:40 +0000 Subject: Fix up validators docs --- docs/api-guide/validators.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index 52c9e082..6a0ef4ff 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -8,7 +8,7 @@ Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes. -Sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes. +However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes. ## Validation in REST framework -- cgit v1.2.3 From d27b8cc09b83bac10346effa1021493d2835b794 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Nov 2014 12:00:19 +0000 Subject: PUT as create docs, and move mixin out to external gist --- docs/api-guide/generic-views.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 49be0cae..d2836fa6 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -368,6 +368,20 @@ If you are using a mixin across multiple views, you can take this a step further 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. +--- + +# PUT as create + +Prior to version 3.0 the REST framework mixins treated `PUT` as either an update or a create operation, depending on if the object already existed or not. + +Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existance of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses. + +Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious. + +If you need to generic PUT-as-create behavior you may want to include something like [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views. + +--- + # Third party packages The following third party packages provide additional generic view implementations. -- cgit v1.2.3 From 21d06a4103d1966cd6e19f7cc6f3c6e450cc1680 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Nov 2014 15:03:10 +0000 Subject: Added NON_FIELD_ERRORS_KEY to serializer docs. Closes #1971. --- docs/api-guide/settings.md | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 6a855c92..2144a2ed 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -399,6 +399,12 @@ This should be a function with the following signature: Default: `'rest_framework.views.exception_handler'` +#### NON_FIELD_ERRORS_KEY + +A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors. + +Default: `'non_field_errors'` + #### URL_FIELD_NAME A string representing the key that should be used for the URL fields generated by `HyperlinkedModelSerializer`. -- cgit v1.2.3 From 78ac332f18c51bb151ae32f1f3d207595b0b3ca2 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Nov 2014 15:08:19 +0000 Subject: Add docs on Meta inheritance. Closes #1926. --- docs/api-guide/serializers.md | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index a3694510..eeeffa13 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -413,6 +413,16 @@ Alternative representations include serializing using hyperlinks, serializing co For full details see the [serializer relations][relations] documentation. +## Inheritance of the 'Meta' class + +The inner `Meta` class on serializers is not inherited from parent classes by default. This is the same behaviour as with Django's `Model` and `ModelForm` classes. If you want the `Meta` class to inherit from a parent class you must do so explicitly. For example: + + class AccountSerializer(MyBaseSerializer): + class Meta(MyBaseSerializer.Meta): + model = Account + +Typically we would recommend *not* using inheritance on inner Meta classes, but instead declaring all options explicitly. + --- # HyperlinkedModelSerializer -- cgit v1.2.3 From 09f3eedb235b476202cbd4e5a94b883898f3f661 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Nov 2014 15:23:16 +0000 Subject: Add notes re view-level and instance-level permissions checks. Closes #1819. --- docs/api-guide/permissions.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index e867a456..f3ae8171 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -183,11 +183,7 @@ If you need to test if a request is a read operation or a write operation, you s --- -**Note**: In versions 2.0 and 2.1, the signature for the permission checks always included an optional `obj` parameter, like so: `.has_permission(self, request, view, obj=None)`. The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required. - -As of version 2.2 this signature has now been replaced with two separate method calls, which is more explicit and obvious. The old style signature continues to work, but its use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed. - -For more details see the [2.2 release announcement][2.2-announcement]. +**Note**: The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default. --- -- cgit v1.2.3 From 571440e143870cf38230eea7c3a49df23d1eaa7c Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 5 Nov 2014 10:53:46 +0000 Subject: Stronger calling out of 'DjangoObjectPermissionsFilter'. Closes #1934. --- docs/api-guide/permissions.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index f3ae8171..446e362e 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -146,7 +146,13 @@ As with `DjangoModelPermissions`, this permission must only be applied to views Note that `DjangoObjectPermissions` **does not** require the `django-guardian` package, and should support other object-level backends equally well. -As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoModelPermissions` and setting the `.perms_map` property. Refer to the source code for details. Note that if you add a custom `view` permission for `GET`, `HEAD` and `OPTIONS` requests, you'll probably also want to consider adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions. +As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoModelPermissions` and setting the `.perms_map` property. Refer to the source code for details. + +--- + +**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests, you'll want to consider also adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions. + +--- ## TokenHasReadWriteScope -- cgit v1.2.3 From 52507006595af4f9da34491e4211bf7ae447a457 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 5 Nov 2014 11:14:41 +0000 Subject: Add docs on request.accepted_renderer and .accepted_media_type --- docs/api-guide/requests.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md index 0696fedf..87425ed1 100644 --- a/docs/api-guide/requests.md +++ b/docs/api-guide/requests.md @@ -49,6 +49,20 @@ If a client sends a request with a content-type that cannot be parsed then a `Un --- +# Content negotiation + +The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialisation schemes for different media types. + +## .accepted_renderer + +The renderer instance what was selected by the content negotiation stage. + +## .accepted_media_type + +A string representing the media type that was accepted by the content negotiation stage. + +--- + # Authentication REST framework provides flexible, per-request authentication, that gives you the ability to: -- cgit v1.2.3 From b44def465054345b6099aae7bdd34b623fdc124c Mon Sep 17 00:00:00 2001 From: Brett Koonce Date: Thu, 6 Nov 2014 23:19:26 -0800 Subject: minor spelling tweaks --- docs/api-guide/authentication.md | 2 +- docs/api-guide/generic-views.md | 2 +- docs/api-guide/relations.md | 2 +- docs/api-guide/settings.md | 6 +++--- docs/api-guide/throttling.md | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 3a5156fd..01774c10 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -398,7 +398,7 @@ HTTP digest authentication is a widely implemented scheme that was intended to r ## Django OAuth Toolkit -The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by [Evonove][evonove] and uses the excelllent [OAuthLib][oauthlib]. The package is well documented, and comes as a recommended alternative for OAuth 2.0 support. +The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by [Evonove][evonove] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and comes as a recommended alternative for OAuth 2.0 support. ## Django OAuth2 Consumer diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index d2836fa6..49a5e58f 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -374,7 +374,7 @@ Using custom base classes is a good option if you have custom behavior that cons Prior to version 3.0 the REST framework mixins treated `PUT` as either an update or a create operation, depending on if the object already existed or not. -Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existance of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses. +Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses. Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious. diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index cc4f5585..d03a75ae 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -202,7 +202,7 @@ This field is always read-only. **Arguments**: -* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this wil be a string with the format `-detail`. **required**. +* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `-detail`. **required**. * `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. diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 2144a2ed..48af30a5 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -154,13 +154,13 @@ Default: `None` ### SEARCH_PARAM -The name of a query paramater, which can be used to specify the search term used by `SearchFilter`. +The name of a query parameter, which can be used to specify the search term used by `SearchFilter`. Default: `search` #### ORDERING_PARAM -The name of a query paramater, which can be used to specify the ordering of results returned by `OrderingFilter`. +The name of a query parameter, which can be used to specify the ordering of results returned by `OrderingFilter`. Default: `ordering` @@ -321,7 +321,7 @@ When set to `False`, JSON responses will escape non-ascii characters, like so: {"unicode black star":"\u2605"} -Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. The unicode style is prefered as being more user-friendly when inspecting API responses. +Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses. Default: `True` diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index 16a7457b..147c16ff 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -74,7 +74,7 @@ If you need to strictly identify unique client IP addresses, you'll need to firs It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client. -Further context on how the `X-Forwarded-For` header works, and identifing a remote client IP can be [found here][identifing-clients]. +Further context on how the `X-Forwarded-For` header works, and identifying a remote client IP can be [found here][identifing-clients]. ## Setting up the cache @@ -85,7 +85,7 @@ If you need to use a cache other than `'default'`, you can do so by creating a c class CustomAnonRateThrottle(AnonRateThrottle): cache = get_cache('alternate') -You'll need to rememeber to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute. +You'll need to remember to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute. --- -- cgit v1.2.3 From f387cd89da55ef88fcac504f5795ea9b591f3fba Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 10 Nov 2014 12:21:27 +0000 Subject: Uniqueness constraints imply a forced 'required=True'. Refs #1945 --- docs/api-guide/validators.md | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index 6a0ef4ff..bb073f57 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -93,6 +93,12 @@ The validator should be applied to *serializer classes*, like so: ) ] +--- + +**Note**: The `UniqueTogetherValidation` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input. + +--- + ## UniqueForDateValidator ## UniqueForMonthValidator @@ -146,6 +152,10 @@ If you want the date field to be entirely hidden from the user, then use `Hidden --- +**Note**: The `UniqueForValidation` classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input. + +--- + # Writing custom validators You can use any of Django's existing validators, or write your own custom validators. -- cgit v1.2.3 From fd7db776addbd5e30f132fe6846ec5c5caab5c40 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 10 Nov 2014 12:32:03 +0000 Subject: Bring UniqueValidator implementation in line with other uniquness validators. --- docs/api-guide/validators.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index bb073f57..a50636bc 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -16,9 +16,9 @@ Validation in Django REST framework serializers is handled a little differently With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons: -* It introduces a proper separation of concerns, making your code behaviour more obvious. -* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behaviour being used for `ModelSerializer` is simple to replicate. -* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behaviour being called on the model instance. +* It introduces a proper separation of concerns, making your code behavior more obvious. +* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate. +* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance. When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using a `Serializer` classes instead, then you need to define the validation rules explicitly. -- cgit v1.2.3 From 0f508c58211051c873aae5a2d1c65a0c595e732a Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 17 Nov 2014 18:36:32 +0000 Subject: Docs for advanced default argument usage. Closes #1945 --- docs/api-guide/validators.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index a50636bc..ac2f3248 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -156,6 +156,38 @@ If you want the date field to be entirely hidden from the user, then use `Hidden --- +# Advanced 'default' argument usage + +Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that *is* available as input to the validator. + +Two patterns that you may want to use for this sort of validation include: + +* Using `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation. +* Using a standard field with `read_only=True`, but that also includes a `default=…` argument. This field *will* be used in the serializer output representation, but cannot be set directly by the user. + +REST framework includes a couple of defaults that may be useful in this context. + +#### CurrentUserDefault + +A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer. + + owner = serializers.HiddenField( + default=CurrentUserDefault() + ) + +#### CreateOnlyDefault + +A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted. + +It takes a single argument, which is the default value or callable that should be used during create operations. + + created_at = serializers.DateTimeField( + read_only=True, + default=CreateOnlyDefault(timezone.now) + ) + +--- + # Writing custom validators You can use any of Django's existing validators, or write your own custom validators. -- cgit v1.2.3 From 8e940a22fb292ed6b20b9e4b5da607ffca1dba2f Mon Sep 17 00:00:00 2001 From: Matthew Dapena-Tretter Date: Fri, 21 Nov 2014 15:58:31 -0500 Subject: Clarify how permission classes are composed all/every/AND or any/OR? all/every/AND! --- docs/api-guide/settings.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 48af30a5..96d715ea 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -74,7 +74,7 @@ Default: #### DEFAULT_PERMISSION_CLASSES -A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. +A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list. Default: -- cgit v1.2.3 From 2e726e22a394347b7337eb38a2a3a1b0ccde88bc Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 25 Nov 2014 11:42:43 +0000 Subject: request.DATA, request.FILES -> request.data --- docs/api-guide/exceptions.md | 4 ++-- docs/api-guide/parsers.md | 20 ++++++++++---------- docs/api-guide/requests.md | 21 ++++++++++++--------- docs/api-guide/settings.md | 2 +- docs/api-guide/viewsets.md | 2 +- 5 files changed, 26 insertions(+), 23 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index e61dcfa9..8a99abb9 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -100,7 +100,7 @@ For example, if your API relies on a third party service that may sometimes be u **Signature:** `ParseError(detail=None)` -Raised if the request contains malformed data when accessing `request.DATA` or `request.FILES`. +Raised if the request contains malformed data when accessing `request.data`. By default this exception results in a response with the HTTP status code "400 Bad Request". @@ -140,7 +140,7 @@ By default this exception results in a response with the HTTP status code "405 M **Signature:** `UnsupportedMediaType(media_type, detail=None)` -Raised if there are no parsers that can handle the content type of the request data when accessing `request.DATA` or `request.FILES`. +Raised if there are no parsers that can handle the content type of the request data when accessing `request.data`. By default this exception results in a response with the HTTP status code "415 Unsupported Media Type". diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 72a4af64..a50b5240 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -12,7 +12,7 @@ REST framework includes a number of built in Parser classes, that allow you to a ## How the parser is determined -The set of valid parsers for a view is always defined as a list of classes. When either `request.DATA` or `request.FILES` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content. +The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content. --- @@ -48,7 +48,7 @@ using the `APIView` class based views. parser_classes = (YAMLParser,) def post(self, request, format=None): - return Response({'received data': request.DATA}) + return Response({'received data': request.data}) Or, if you're using the `@api_view` decorator with function based views. @@ -58,7 +58,7 @@ Or, if you're using the `@api_view` decorator with function based views. """ A view that can accept POST requests with YAML content. """ - return Response({'received data': request.DATA}) + return Response({'received data': request.data}) --- @@ -92,7 +92,7 @@ Requires the `defusedxml` package to be installed. ## FormParser -Parses HTML form content. `request.DATA` will be populated with a `QueryDict` of data, `request.FILES` will be populated with an empty `QueryDict` of data. +Parses HTML form content. `request.data` will be populated with a `QueryDict` of data. You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data. @@ -100,7 +100,7 @@ You will typically want to use both `FormParser` and `MultiPartParser` together ## MultiPartParser -Parses multipart HTML form content, which supports file uploads. Both `request.DATA` and `request.FILES` will be populated with a `QueryDict`. +Parses multipart HTML form content, which supports file uploads. Both `request.data` will be populated with a `QueryDict`. You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data. @@ -108,7 +108,7 @@ You will typically want to use both `FormParser` and `MultiPartParser` together ## 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. +Parses raw file upload content. The `request.data` property 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`. @@ -126,7 +126,7 @@ If the view used with `FileUploadParser` is called with a `filename` URL keyword parser_classes = (FileUploadParser,) def put(self, request, filename, format=None): - file_obj = request.FILES['file'] + file_obj = request.data['file'] # ... # do some staff with uploaded file # ... @@ -139,7 +139,7 @@ If the view used with `FileUploadParser` is called with a `filename` URL keyword To implement a custom parser, you should override `BaseParser`, set the `.media_type` property, and implement the `.parse(self, stream, media_type, parser_context)` method. -The method should return the data that will be used to populate the `request.DATA` property. +The method should return the data that will be used to populate the `request.data` property. The arguments passed to `.parse()` are: @@ -161,7 +161,7 @@ By default this will include the following keys: `view`, `request`, `args`, `kwa ## Example -The following is an example plaintext parser that will populate the `request.DATA` property with a string representing the body of the request. +The following is an example plaintext parser that will populate the `request.data` property with a string representing the body of the request. class PlainTextParser(BaseParser): """ @@ -197,4 +197,4 @@ The following third party packages are also available. [juanriaza]: https://github.com/juanriaza [vbabiy]: https://github.com/vbabiy [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack -[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case \ No newline at end of file +[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md index 87425ed1..d659e17a 100644 --- a/docs/api-guide/requests.md +++ b/docs/api-guide/requests.md @@ -14,26 +14,29 @@ REST framework's `Request` class extends the standard `HttpRequest`, adding supp REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data. -## .DATA +## .data -`request.DATA` returns the parsed content of the request body. This is similar to the standard `request.POST` attribute except that: +`request.data` returns the parsed content of the request body. This is similar to the standard `request.POST` and `request.FILES` attributes except that: +* It includes all parsed content, including *file and non-file* inputs. * It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests. * It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data. For more details see the [parsers documentation]. -## .FILES +## .query_params -`request.FILES` returns any uploaded files that may be present in the content of the request body. This is the same as the standard `HttpRequest` behavior, except that the same flexible request parsing is used for `request.DATA`. +`request.query_params` is a more correctly named synonym for `request.GET`. -For more details see the [parsers documentation]. +For clarity inside your code, we recommend using `request.query_params` instead of the Django's standard `request.GET`. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just `GET` requests. -## .QUERY_PARAMS +## .DATA and .FILES -`request.QUERY_PARAMS` is a more correctly named synonym for `request.GET`. +The old-style version 2.x `request.data` and `request.FILES` attributes are still available, but are now pending deprecation in favor of the unified `request.data` attribute. + +## .QUERY_PARAMS -For clarity inside your code, we recommend using `request.QUERY_PARAMS` instead of the usual `request.GET`, as *any* HTTP method type may include query parameters. +The old-style version 2.x `request.QUERY_PARAMS` attribute is still available, but is now pending deprecation in favor of the more pythonic `request.query_params`. ## .parsers @@ -43,7 +46,7 @@ You won't typically need to access this property. --- -**Note:** If a client sends malformed content, then accessing `request.DATA` or `request.FILES` may raise a `ParseError`. By default REST framework's `APIView` class or `@api_view` decorator will catch the error and return a `400 Bad Request` response. +**Note:** If a client sends malformed content, then accessing `request.data` may raise a `ParseError`. By default REST framework's `APIView` class or `@api_view` decorator will catch the error and return a `400 Bad Request` response. If a client sends a request with a content-type that cannot be parsed then a `UnsupportedMediaType` exception will be raised, which by default will be caught and return a `415 Unsupported Media Type` response. diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 96d715ea..ba470f8b 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -51,7 +51,7 @@ Default: #### DEFAULT_PARSER_CLASSES -A list or tuple of parser classes, that determines the default set of parsers used when accessing the `request.DATA` property. +A list or tuple of parser classes, that determines the default set of parsers used when accessing the `request.data` property. Default: diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 9030e3ee..f60d4a47 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -124,7 +124,7 @@ For example: @detail_route(methods=['post']) def set_password(self, request, pk=None): user = self.get_object() - serializer = PasswordSerializer(data=request.DATA) + serializer = PasswordSerializer(data=request.data) if serializer.is_valid(): user.set_password(serializer.data['password']) user.save() -- cgit v1.2.3 From a3c0c8fb90f084d494cdf46551c8a6228ca5ffd0 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 25 Nov 2014 12:04:35 +0000 Subject: Add missing period. --- docs/api-guide/generic-views.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 49a5e58f..16ae8c55 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -352,7 +352,7 @@ You can then simply apply this mixin to a view or viewset anytime you need to ap serializer_class = UserSerializer lookup_fields = ('account', 'username') -Using custom mixins is a good option if you have custom behavior that needs to be used +Using custom mixins is a good option if you have custom behavior that needs to be used. ## Creating custom base classes -- cgit v1.2.3 From c4dff54ecc487b192d17763e48adc0bfcaa620d3 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 25 Nov 2014 12:04:46 +0000 Subject: Docs on ValidationError --- docs/api-guide/exceptions.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 8a99abb9..33eb74c8 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -152,5 +152,23 @@ Raised when an incoming request fails the throttling checks. By default this exception results in a response with the HTTP status code "429 Too Many Requests". +## ValidationError + +**Signature:** `ValidationError(detail)` + +The `ValidationError` exception is slightly different from the other `APIException` classes: + +* The `detail` argument is mandatory, not optional. +* The `detail` argument may be a list or dictionary of error details, and may also be a nested data structure. +* By convention you should import the serializers module and use a fully qualified `ValidationError` style, in order to differentiate it from Django's built-in validation error. For example. `raise serializers.ValidationError('This field must be an integer value.')` + +The `ValidationError` class should be used for serializer and field validation, and by validator classes. It is also raised when calling `serializer.is_valid` with the `raise_exception` keyword argument: + + serializer.is_valid(raise_exception=True) + +The generic views use the `raise_exception=True` flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above. + +By default this exception results in a response with the HTTP status code "400 Bad Request". + [cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html [authentication]: authentication.md -- cgit v1.2.3 From 16d442dda3ee9d4ff40d067d76706959aac4c6a3 Mon Sep 17 00:00:00 2001 From: José Padilla Date: Fri, 31 Oct 2014 09:04:39 -0400 Subject: Use MkDocs meta.source to render source code links --- docs/api-guide/authentication.md | 2 +- docs/api-guide/content-negotiation.md | 6 +++--- docs/api-guide/exceptions.md | 2 +- docs/api-guide/fields.md | 4 ++-- docs/api-guide/filtering.md | 24 ++++++++++----------- docs/api-guide/format-suffixes.md | 12 +++++------ docs/api-guide/generic-views.md | 4 ++-- docs/api-guide/pagination.md | 6 +++--- docs/api-guide/parsers.md | 6 +++--- docs/api-guide/permissions.md | 8 +++---- docs/api-guide/relations.md | 40 +++++++++++++++++------------------ docs/api-guide/renderers.md | 14 ++++++------ docs/api-guide/requests.md | 8 +++---- docs/api-guide/responses.md | 4 ++-- docs/api-guide/reverse.md | 4 ++-- docs/api-guide/routers.md | 8 +++---- docs/api-guide/serializers.md | 34 ++++++++++++++--------------- docs/api-guide/settings.md | 2 +- docs/api-guide/status-codes.md | 6 +++--- docs/api-guide/testing.md | 6 +++--- docs/api-guide/throttling.md | 10 ++++----- docs/api-guide/views.md | 7 +++--- docs/api-guide/viewsets.md | 2 +- 23 files changed, 110 insertions(+), 109 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 01774c10..b04858e3 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -1,4 +1,4 @@ - +source: authentication.py # Authentication diff --git a/docs/api-guide/content-negotiation.md b/docs/api-guide/content-negotiation.md index 94dd59ca..bc3b09fb 100644 --- a/docs/api-guide/content-negotiation.md +++ b/docs/api-guide/content-negotiation.md @@ -1,4 +1,4 @@ - +source: negotiation.py # Content negotiation @@ -29,7 +29,7 @@ The priorities for each of the given media types would be: If the requested view was only configured with renderers for `YAML` and `HTML`, then REST framework would select whichever renderer was listed first in the `renderer_classes` list or `DEFAULT_RENDERER_CLASSES` setting. -For more information on the `HTTP Accept` header, see [RFC 2616][accept-header] +For more information on the `HTTP Accept` header, see [RFC 2616][accept-header] --- @@ -62,7 +62,7 @@ request when selecting the appropriate parser or renderer. Select the first parser in the `.parser_classes` list. """ return parsers[0] - + def select_renderer(self, request, renderers, format_suffix): """ Select the first renderer in the `.renderer_classes` list. diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index e61dcfa9..8e0b1958 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -1,4 +1,4 @@ - +source: exceptions.py # Exceptions diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 292a51d8..354ec966 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -1,4 +1,4 @@ - +source: fields.py # Serializer fields @@ -62,7 +62,7 @@ A dictionary of error codes to error messages. ### `widget` Used only if rendering the field to HTML. -This argument sets the widget that should be used to render the field. For more details, and a list of available widgets, see [the Django documentation on form widgets][django-widgets]. +This argument sets the widget that should be used to render the field. For more details, and a list of available widgets, see [the Django documentation on form widgets][django-widgets]. ### `label` diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index cfeb4334..83977048 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -1,4 +1,4 @@ - +source: filters.py # Filtering @@ -26,7 +26,7 @@ For example: class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer - + def get_queryset(self): """ This view should return a list of all the purchases @@ -38,7 +38,7 @@ For example: ## Filtering against the URL -Another style of filtering might involve restricting the queryset based on some part of the URL. +Another style of filtering might involve restricting the queryset based on some part of the URL. For example if your URL config contained an entry like this: @@ -48,7 +48,7 @@ You could then write a view that returned a purchase queryset filtered by the us class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer - + def get_queryset(self): """ This view should return a list of all the purchases for @@ -57,7 +57,7 @@ You could then write a view that returned a purchase queryset filtered by the us username = self.kwargs['username'] return Purchase.objects.filter(purchaser__username=username) -## Filtering against query parameters +## Filtering against query parameters A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url. @@ -65,7 +65,7 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/ class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer - + def get_queryset(self): """ Optionally restricts the returned purchases to a given user, @@ -113,7 +113,7 @@ For instance, given the previous example, and a product with an id of `4675`, th http://example.com/api/products/4675/?category=clothing&max_price=10.00 ## Overriding the initial queryset - + Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this: class PurchasedProductsList(generics.ListAPIView): @@ -124,7 +124,7 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering model = Product serializer_class = ProductSerializer filter_class = ProductFilter - + def get_queryset(self): user = self.request.user return user.purchase_set.all() @@ -135,7 +135,7 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering ## DjangoFilterBackend -The `DjangoFilterBackend` class supports highly customizable field filtering, using the [django-filter package][django-filter]. +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`. @@ -216,7 +216,7 @@ This is nice, but it exposes the Django's double underscore convention as part o And now you can execute: http://example.com/api/products?manufacturer=foo - + For more details on using filter sets see the [django-filter documentation][django-filter-docs]. --- @@ -224,7 +224,7 @@ For more details on using filter sets see the [django-filter documentation][djan **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].) +* 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. * For Django 1.3 support, make sure to install `django-filter` version 0.5.4, as later versions drop support for 1.3. @@ -316,7 +316,7 @@ Typically you'd instead control this by setting `order_by` on the initial querys queryset = User.objects.all() serializer_class = UserSerializer filter_backends = (filters.OrderingFilter,) - ordering = ('username',) + ordering = ('username',) The `ordering` attribute may be either a string or a list/tuple of strings. diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md index 76a3367b..20c1e995 100644 --- a/docs/api-guide/format-suffixes.md +++ b/docs/api-guide/format-suffixes.md @@ -1,4 +1,4 @@ - +source: urlpatterns.py # Format suffixes @@ -7,7 +7,7 @@ used all the time. > > — Roy Fielding, [REST discuss mailing list][cite] -A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation. +A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation. Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf. @@ -21,7 +21,7 @@ Arguments: * **urlpatterns**: Required. A URL pattern list. * **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default. -* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. +* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. Example: @@ -33,7 +33,7 @@ Example: url(r'^comments/$', views.comment_list), url(r'^comments/(?P[0-9]+)/$', views.comment_detail) ] - + urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example: @@ -56,12 +56,12 @@ The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` se Also note that `format_suffix_patterns` does not support descending into `include` URL patterns. --- - + ## Accept headers vs. format suffixes There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead. -It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators: +It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators: “That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, [REST discuss mailing list][cite2] diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 49a5e58f..648ece82 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -1,5 +1,5 @@ - - +source: mixins.py + generics.py # Generic views diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index e57aed1a..9b7086c5 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -1,4 +1,4 @@ - +source: pagination.py # Pagination @@ -6,7 +6,7 @@ > > — [Django documentation][cite] -REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types. +REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types. ## Paginating basic data @@ -33,7 +33,7 @@ The `context` argument of the `PaginationSerializer` class may optionally includ request = RequestFactory().get('/foobar') serializer = PaginationSerializer(instance=page, context={'request': request}) serializer.data - # {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']} + # {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']} We could now return that data in a `Response` object, and it would be rendered into the correct media type. diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 72a4af64..42d77b22 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -1,4 +1,4 @@ - +source: parsers.py # Parsers @@ -161,7 +161,7 @@ By default this will include the following keys: `view`, `request`, `args`, `kwa ## Example -The following is an example plaintext parser that will populate the `request.DATA` property with a string representing the body of the request. +The following is an example plaintext parser that will populate the `request.DATA` property with a string representing the body of the request. class PlainTextParser(BaseParser): """ @@ -197,4 +197,4 @@ The following third party packages are also available. [juanriaza]: https://github.com/juanriaza [vbabiy]: https://github.com/vbabiy [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack -[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case \ No newline at end of file +[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 446e362e..f068f0f7 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -1,4 +1,4 @@ - +source: permissions.py # Permissions @@ -12,7 +12,7 @@ Permission checks are always run at the very start of the view, before any other ## How permissions are determined -Permissions in REST framework are always defined as a list of permission classes. +Permissions in REST framework are always defined as a list of permission classes. Before running the main body of the view each permission in the list is checked. If any permission check fails an `exceptions.PermissionDenied` exception will be raised, and the main body of the view will not run. @@ -220,9 +220,9 @@ As well as global permissions, that are run against all incoming requests, you c def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. - if request.method in permissions.SAFE_METHODS: + if request.method in permissions.SAFE_METHODS: return True - + # Instance must have an attribute named `owner`. return obj.owner == request.user diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index d03a75ae..ad981b2b 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -1,4 +1,4 @@ - +source: relations.py # Serializer relations @@ -33,7 +33,7 @@ In order to explain the various types of relational fields, we'll use a couple o class Meta: unique_together = ('album', 'order') order_by = 'order' - + def __unicode__(self): return '%d: %s' % (self.order, self.title) @@ -42,10 +42,10 @@ In order to explain the various types of relational fields, we'll use a couple o `RelatedField` may be used to represent the target of the relationship using its `__unicode__` method. For example, the following serializer. - + class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.RelatedField(many=True) - + class Meta: model = Album fields = ('album_name', 'artist', 'tracks') @@ -74,10 +74,10 @@ This field is read only. `PrimaryKeyRelatedField` may be used to represent the target of the relationship using its primary key. For example, the following serializer: - + class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) - + class Meta: model = Album fields = ('album_name', 'artist', 'tracks') @@ -108,11 +108,11 @@ By default this field is read-write, although you can change this behavior using `HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink. For example, the following serializer: - + class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='track-detail') - + class Meta: model = Album fields = ('album_name', 'artist', 'tracks') @@ -146,11 +146,11 @@ By default this field is read-write, although you can change this behavior using `SlugRelatedField` may be used to represent the target of the relationship using a field on the target. For example, the following serializer: - + class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.SlugRelatedField(many=True, read_only=True, slug_field='title') - + class Meta: model = Album fields = ('album_name', 'artist', 'tracks') @@ -222,10 +222,10 @@ For example, the following serializer: class Meta: model = Track fields = ('order', 'title') - + class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) - + class Meta: model = Album fields = ('album_name', 'artist', 'tracks') @@ -262,7 +262,7 @@ For, example, we could define a relational field, to serialize a track to a cust class AlbumSerializer(serializers.ModelSerializer): tracks = TrackListingField(many=True) - + class Meta: model = Album fields = ('album_name', 'artist', 'tracks') @@ -302,7 +302,7 @@ If you have not set a related name for the reverse relationship, you'll need to class AlbumSerializer(serializers.ModelSerializer): class Meta: - fields = ('track_set', ...) + fields = ('track_set', ...) See the Django documentation on [reverse relationships][reverse-relationships] for more details. @@ -315,14 +315,14 @@ For example, given the following model for a tag, which has a generic relationsh class TaggedItem(models.Model): """ Tags arbitrary model instances using a generic relation. - + See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/ """ tag_name = models.SlugField() content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() tagged_object = GenericForeignKey('content_type', 'object_id') - + def __unicode__(self): return self.tag @@ -353,7 +353,7 @@ We could define a custom field that could be used to serialize tagged instances, def to_native(self, value): """ Serialize tagged objects to a simple textual representation. - """ + """ if isinstance(value, Bookmark): return 'Bookmark: ' + value.url elif isinstance(value, Note): @@ -366,7 +366,7 @@ If you need the target of the relationship to have a nested representation, you """ Serialize bookmark instances using a bookmark serializer, and note instances using a note serializer. - """ + """ if isinstance(value, Bookmark): serializer = BookmarkSerializer(value) elif isinstance(value, Note): @@ -391,7 +391,7 @@ to ``True``. ## Advanced Hyperlinked fields -If you have very specific requirements for the style of your hyperlinked relationships you can override `HyperlinkedRelatedField`. +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. @@ -411,7 +411,7 @@ 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: +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): diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index db7436c2..035ec1d2 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -1,4 +1,4 @@ - +source: renderers.py # Renderers @@ -115,7 +115,7 @@ The `jsonp` approach is essentially a browser hack, and is [only appropriate for ## YAMLRenderer -Renders the request data into `YAML`. +Renders the request data into `YAML`. Requires the `pyyaml` package to be installed. @@ -131,7 +131,7 @@ Note that non-ascii characters will be rendered using `\uXXXX` character escape. ## UnicodeYAMLRenderer -Renders the request data into `YAML`. +Renders the request data into `YAML`. Requires the `pyyaml` package to be installed. @@ -184,7 +184,7 @@ An example of a view that uses `TemplateHTMLRenderer`: def get(self, request, *args, **kwargs): self.object = self.get_object() return Response({'user': self.object}, template_name='user_detail.html') - + You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint. If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers. @@ -205,7 +205,7 @@ An example of a view that uses `TemplateHTMLRenderer`: @api_view(('GET',)) @renderer_classes((StaticHTMLRenderer,)) - def simple_html_view(request): + def simple_html_view(request): data = '

Hello, world

' return Response(data) @@ -300,7 +300,7 @@ The following is an example plaintext renderer that will return a response with class PlainTextRenderer(renderers.BaseRenderer): media_type = 'text/plain' format = 'txt' - + def render(self, data, media_type=None, renderer_context=None): return data.encode(self.charset) @@ -340,7 +340,7 @@ You can do some pretty flexible things using REST framework's renderers. Some e * Provide either flat or nested representations from the same endpoint, depending on the requested media type. * Serve both regular HTML webpages, and JSON based API responses from the same endpoints. * Specify multiple types of HTML representation for API clients to use. -* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response. +* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response. ## Varying behaviour by media type diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md index 87425ed1..8713fa2a 100644 --- a/docs/api-guide/requests.md +++ b/docs/api-guide/requests.md @@ -1,4 +1,4 @@ - +source: request.py # Requests @@ -105,7 +105,7 @@ REST framework supports a few browser enhancements such as browser-based `PUT`, Browser-based `PUT`, `PATCH` and `DELETE` forms are transparently supported. -For more information see the [browser enhancements documentation]. +For more information see the [browser enhancements documentation]. ## .content_type @@ -115,7 +115,7 @@ You won't typically need to directly access the request's content type, as you'l If you do need to access the content type of the request you should use the `.content_type` property in preference to using `request.META.get('HTTP_CONTENT_TYPE')`, as it provides transparent support for browser-based non-form content. -For more information see the [browser enhancements documentation]. +For more information see the [browser enhancements documentation]. ## .stream @@ -125,7 +125,7 @@ You won't typically need to directly access the request's content, as you'll nor If you do need to access the raw content directly, you should use the `.stream` property in preference to using `request.content`, as it provides transparent support for browser-based non-form content. -For more information see the [browser enhancements documentation]. +For more information see the [browser enhancements documentation]. --- diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md index 5a42aa92..97f31271 100644 --- a/docs/api-guide/responses.md +++ b/docs/api-guide/responses.md @@ -1,4 +1,4 @@ - +source: response.py # Responses @@ -90,6 +90,6 @@ The `Response` class extends `SimpleTemplateResponse`, and all the usual attribu As with any other `TemplateResponse`, this method is called to render the serialized data of the response into the final response content. When `.render()` is called, the response content will be set to the result of calling the `.render(data, accepted_media_type, renderer_context)` method on the `accepted_renderer` instance. You won't typically need to call `.render()` yourself, as it's handled by Django's standard response cycle. - + [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/ [statuscodes]: status-codes.md diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md index 383eca4c..71fb83f9 100644 --- a/docs/api-guide/reverse.md +++ b/docs/api-guide/reverse.md @@ -1,4 +1,4 @@ - +source: reverse.py # Returning URLs @@ -30,7 +30,7 @@ You should **include the request as a keyword argument** to the function, for ex from rest_framework.reverse import reverse from rest_framework.views import APIView from django.utils.timezone import now - + class APIRootView(APIView): def get(self, request): year = now().year diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 61a476b8..080230fa 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -1,4 +1,4 @@ - +source: routers.py # Routers @@ -56,10 +56,10 @@ For example, given a method like this on the `UserViewSet` class: from myapp.permissions import IsAdminOrIsSelf from rest_framework.decorators import detail_route - + class UserViewSet(ModelViewSet): ... - + @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf]) def set_password(self, request, pk=None): ... @@ -228,7 +228,7 @@ For another example of setting the `.routes` attribute, see the source code for ## 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 inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute. +If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute. You may also want to override the `get_default_base_name(self, viewset)` method, or else always explicitly set the `base_name` argument when registering your viewsets with the router. diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index eeeffa13..2d0ff79a 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -1,4 +1,4 @@ - +source: serializers.py # Serializers @@ -21,7 +21,7 @@ Let's start by creating a simple object we can use for example purposes: self.email = email self.content = content self.created = created or datetime.datetime.now() - + comment = Comment(email='leila@example.com', content='foo bar') We'll declare a serializer that we can use to serialize and deserialize `Comment` objects. @@ -45,7 +45,7 @@ Declaring a serializer looks very similar to declaring a form: instance.content = attrs.get('content', instance.content) instance.created = attrs.get('created', instance.created) return instance - return Comment(**attrs) + 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. @@ -83,8 +83,8 @@ If you need to customize the serialized value of a particular field, you can do These methods are essentially the reverse of `validate_` (see *Validation* below.) ## Deserializing objects - -Deserialization is similar. First we parse a stream into Python native datatypes... + +Deserialization is similar. First we parse a stream into Python native datatypes... from StringIO import StringIO from rest_framework.parsers import JSONParser @@ -174,7 +174,7 @@ To save the deserialized objects created by a serializer, call the `.save()` met 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. +The generic views provided by REST framework call the `.save()` method when updating or creating entities. ## Dealing with nested objects @@ -288,12 +288,12 @@ By default the serializer class will use the `id` key on the incoming data to de 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. """ @@ -361,7 +361,7 @@ The `depth` option should be set to an integer value that indicates the depth of If you want to customize the way the serialization is done (e.g. using `allow_add_remove`) you'll need to define the field yourself. -## Specifying which fields should be read-only +## 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: @@ -371,9 +371,9 @@ You may wish to specify multiple fields as read-only. Instead of adding each fi 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. +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 which fields should be write-only +## Specifying which fields should be write-only You may wish to specify multiple fields as write-only. Instead of adding each field explicitly with the `write_only=True` attribute, you may use the `write_only_fields` Meta option, like so: @@ -387,12 +387,12 @@ You may wish to specify multiple fields as write-only. Instead of adding each f """ Instantiate a new User instance. """ - assert instance is None, 'Cannot update users with CreateUserSerializer' + assert instance is None, 'Cannot update users with CreateUserSerializer' user = User(email=attrs['email'], username=attrs['username']) user.set_password(attrs['password']) return user - -## Specifying fields explicitly + +## Specifying fields explicitly You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class. @@ -524,10 +524,10 @@ For example, if you wanted to be able to set which fields should be used by a se def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) - + # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) - + if fields: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) @@ -550,7 +550,7 @@ This would then allow you to do the following: ## Customising the default fields -The `field_mapping` attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes. +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. 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`. diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 96d715ea..0aa4b6a9 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -1,4 +1,4 @@ - +source: settings.py # Settings diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md index 64c46434..d81e092c 100644 --- a/docs/api-guide/status-codes.md +++ b/docs/api-guide/status-codes.md @@ -1,4 +1,4 @@ - +source: status.py # Status Codes @@ -27,7 +27,7 @@ The module also includes a set of helper functions for testing if a status code url = reverse('index') response = self.client.get(url) self.assertTrue(status.is_success(response.status_code)) - + For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616] and [RFC 6585][rfc6585]. @@ -51,7 +51,7 @@ This class of status code indicates that the client's request was successfully r HTTP_205_RESET_CONTENT HTTP_206_PARTIAL_CONTENT -## Redirection - 3xx +## Redirection - 3xx This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index 72c33961..d059fdab 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -1,4 +1,4 @@ - +source: test.py # Testing @@ -170,7 +170,7 @@ This can be a useful shortcut if you're testing the API but don't want to have t To unauthenticate subsequent requests, call `force_authenticate` setting the user and/or token to `None`. - client.force_authenticate(user=None) + client.force_authenticate(user=None) ## CSRF validation @@ -197,7 +197,7 @@ You can use any of REST framework's test case classes as you would for the regul from django.core.urlresolvers import reverse from rest_framework import status - from rest_framework.test import APITestCase + from rest_framework.test import APITestCase class AccountTests(APITestCase): def test_create_account(self): diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index 147c16ff..3f668867 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -1,4 +1,4 @@ - +source: throttling.py # Throttling @@ -83,7 +83,7 @@ The throttle classes provided by REST framework use Django's cache backend. You If you need to use a cache other than `'default'`, you can do so by creating a custom throttle class and setting the `cache` attribute. For example: class CustomAnonRateThrottle(AnonRateThrottle): - cache = get_cache('alternate') + cache = get_cache('alternate') You'll need to remember to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute. @@ -147,15 +147,15 @@ For example, given the following views... class ContactListView(APIView): throttle_scope = 'contacts' ... - + class ContactDetailView(ApiView): throttle_scope = 'contacts' ... - class UploadView(APIView): + class UploadView(APIView): throttle_scope = 'uploads' ... - + ...and the following settings. REST_FRAMEWORK = { diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md index 194a7a6b..31c62682 100644 --- a/docs/api-guide/views.md +++ b/docs/api-guide/views.md @@ -1,4 +1,5 @@ - +source: decorators.py + views.py # Class Based Views @@ -26,7 +27,7 @@ For example: class ListUsers(APIView): """ View to list all users in the system. - + * Requires token authentication. * Only admin users are able to access this view. """ @@ -54,7 +55,7 @@ The following attributes control the pluggable aspects of API views. ### .permission_classes -### .content_negotiation_class +### .content_negotiation_class ## API policy instantiation methods diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 9030e3ee..9249d875 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -1,4 +1,4 @@ - +source: viewsets.py # ViewSets -- cgit v1.2.3 From 8c91e7b742067b6d4e4ed6d476bfe2cf5839ac8b Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 25 Nov 2014 15:52:13 +0000 Subject: Add missing options --- docs/api-guide/fields.md | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 292a51d8..aef7792b 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -22,7 +22,7 @@ Each serializer field class constructor takes at least these arguments. Some Fi The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `Field(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `Field(source='user.email')`. -The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations. (See the implementation of the `PaginationSerializer` class for an example.) +The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. Defaults to the name of the field. @@ -45,25 +45,28 @@ Set to false if this field is not required to be present during deserialization. Defaults to `True`. +### `allow_null` + +Normally an error will be raise if `None` is passed to a serializer field. Set this keyword argument to `True` if `None` should be considered a valid value. + +Defaults to `False` + ### `default` If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all. May be set to a function or other callable, in which case the value will be evaluated each time it is used. +Note that setting a `default` value implies that the field is not required. Including both the `default` and `required` keyword arguments is invalid and will raise an error. + ### `validators` -A list of Django validators that should be used to validate deserialized values. +A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise `serializers.ValidationError`, but Django's built-in `ValidationError` is also supported for compatibility with validators defined in the Django codebase or third party Django packages. ### `error_messages` A dictionary of error codes to error messages. -### `widget` - -Used only if rendering the field to HTML. -This argument sets the widget that should be used to render the field. For more details, and a list of available widgets, see [the Django documentation on form widgets][django-widgets]. - ### `label` A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. @@ -72,6 +75,29 @@ A short text string that may be used as the name of the field in HTML form field A text string that may be used as a description of the field in HTML form fields or other descriptive elements. +### `initial` + +A value that should be used for pre-populating the value of HTML form fields. + +### `style` + +A dictionary of key-value pairs that can be used to control how renderers should render the field. The API for this should still be considered experimental, and will be formalized with the 3.1 release. + +Two options are currently used in HTML form generation, `'input_type'` and `'base_template'`. + + # Use for the input. + password = serializers.CharField( + style={'input_type': 'password'} + ) + + # Use a radio input instead of a select input. + color_channel = serializers.ChoiceField( + choices=['red', 'green', 'blue'] + style = {'base_template': 'radio.html'} + } + +**Note**: The `style` argument replaces the old-style version 2.x `widget` keyword argument. Because REST framework 3 now uses templated HTML form generation, the `widget` option that was used to support Django built-in widgets can no longer be supported. Version 3.1 is planned to include public API support for customizing HTML form generation. + --- # Generic Fields -- cgit v1.2.3 From 31536566d7fee430fb549621b4e324ddec4081fd Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 25 Nov 2014 17:35:27 +0000 Subject: Updating fields docs --- docs/api-guide/fields.md | 254 +++++++++++++++++++++++++++++++---------------- 1 file changed, 166 insertions(+), 88 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 68cdc622..17a65ab8 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -47,7 +47,7 @@ Defaults to `True`. ### `allow_null` -Normally an error will be raise if `None` is passed to a serializer field. Set this keyword argument to `True` if `None` should be considered a valid value. +Normally an error will be raised if `None` is passed to a serializer field. Set this keyword argument to `True` if `None` should be considered a valid value. Defaults to `False` @@ -100,10 +100,6 @@ Two options are currently used in HTML form generation, `'input_type'` and `'bas --- -# Generic Fields - -These generic fields are used for representing arbitrary model fields or the output of model methods. - ## Field A generic, **read-only** field. You can use this field for any attribute that does not need to support write operations. @@ -146,96 +142,143 @@ By default, the `Field` class will perform a basic translation of the source val You can customize this behavior by overriding the `.to_native(self, value)` method. -## WritableField +**TODO**: Note removal of `WritableField` -A field that supports both read and write operations. By itself `WritableField` does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the `.to_native(self, value)` and `.from_native(self, value)` methods. +--- -## ModelField +# Boolean fields -A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. +## BooleanField -The `ModelField` class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model. For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))` +A boolean representation. -**Signature:** `ModelField(model_field=)` +Corresponds to `django.db.models.fields.BooleanField`. -## SerializerMethodField +## NullBooleanField -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: +A boolean representation that also accepts `None` as a valid value. - from django.contrib.auth.models import User - from django.utils.timezone import now - from rest_framework import serializers +Corresponds to `django.db.models.fields.NullBooleanField`. - class UserSerializer(serializers.ModelSerializer): - days_since_joined = serializers.SerializerMethodField('get_days_since_joined') +--- - class Meta: - model = User +# String fields - def get_days_since_joined(self, obj): - return (now() - obj.date_joined).days +## CharField ---- +A text representation. Optionally validates the text to be shorter than `max_length` and longer than `min_length`. -# Typed Fields +Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.TextField`. -These fields represent basic datatypes, and support both reading and writing values. +**Signature:** `CharField(max_length=None, min_length=None, allow_none=False)` -## BooleanField +## EmailField -A Boolean representation. +A text representation, validates the text to be a valid e-mail address. -Corresponds to `django.db.models.fields.BooleanField`. +Corresponds to `django.db.models.fields.EmailField` -## CharField +**Signature:** `EmailField(max_length=None, min_length=None)` -A text representation, optionally validates the text to be shorter than `max_length` and longer than `min_length`. -If `allow_none` is `False` (default), `None` values will be converted to an empty string. +## RegexField -Corresponds to `django.db.models.fields.CharField` -or `django.db.models.fields.TextField`. +A text representation, that validates the given value matches against a certain regular expression. -**Signature:** `CharField(max_length=None, min_length=None, allow_none=False)` +The mandatory `regex` argument may either be a string, or a compiled python regular expression object. -## URLField +Uses Django's `django.core.validators.RegexValidator` for validation. -Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation. +Corresponds to `django.forms.fields.RegexField` -**Signature:** `URLField(max_length=200, min_length=None)` +**Signature:** `RegexField(regex, max_length=None, min_length=None)` ## SlugField +A `RegexField` that validates the input against the pattern `[a-zA-Z0-9_-]+`. + Corresponds to `django.db.models.fields.SlugField`. **Signature:** `SlugField(max_length=50, min_length=None)` -## ChoiceField +## URLField -A field that can accept a value out of a limited set of choices. Optionally takes a `blank_display_value` parameter that customizes the display value of an empty choice. +A `RegexField` that validates the input against a URL matching pattern. Expects fully qualified URLs of the form `http:///`. -**Signature:** `ChoiceField(choices=(), blank_display_value=None)` +Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation. -## EmailField +**Signature:** `URLField(max_length=200, min_length=None)` -A text representation, validates the text to be a valid e-mail address. +--- -Corresponds to `django.db.models.fields.EmailField` +# Numeric fields -## RegexField +## IntegerField -A text representation, that validates the given value matches against a certain regular expression. +An integer representation. -Uses Django's `django.core.validators.RegexValidator` for validation. +Has two optional arguments: -Corresponds to `django.forms.fields.RegexField` +- `max_value` Validate that the number provided is no greater than this value. -**Signature:** `RegexField(regex, max_length=None, min_length=None)` +- `min_value` Validate that the number provided is no less than this value. + +Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField`. + +## FloatField + +A floating point representation. + +Has two optional arguments: + +- `max_value` Validate that the number provided is no greater than this value. + +- `min_value` Validate that the number provided is no less than this value. + +Corresponds to `django.db.models.fields.FloatField`. + +## DecimalField + +A decimal representation, represented in Python by a Decimal instance. + +Has two required arguments, and three optional arguments: + +- `max_digits` The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places. + +- `decimal_places` The number of decimal places to store with the number. + +- `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. + +- `max_value` Validate that the number provided is no greater than this value. + +- `min_value` Validate that the number provided is no less than this value. + +#### Example usage + +To validate numbers up to 999 with a resolution of 2 decimal places, you would use: + + serializers.DecimalField(max_digits=5, decimal_places=2) + +And to validate numbers up to anything less than one billion with a resolution of 10 decimal places: + + serializers.DecimalField(max_digits=19, decimal_places=10) + +This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer. + +If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise. + +**Signature:** `DecimalField(max_digits, decimal_places, coerce_to_string=None)` + +Corresponds to `django.db.models.fields.DecimalField`. + +--- + +# Date and time fields ## DateTimeField A date and time representation. -Corresponds to `django.db.models.fields.DateTimeField` +Corresponds to `django.db.models.fields.DateTimeField`. When using `ModelSerializer` or `HyperlinkedModelSerializer`, note that any model fields with `auto_now=True` or `auto_now_add=True` will use serializer fields that are `read_only=True` by default. @@ -253,10 +296,10 @@ In the case of JSON this means the default datetime representation uses the [ECM **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. +* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. 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 specify 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'`) +**DateTimeField format strings**: Format strings may either be [Python strftime formats][strftime] which explicitly specify 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 @@ -266,63 +309,47 @@ 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. +* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATE_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `date` objects should be returned by `to_representation`. 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 specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`) +**DateField format strings**: Format strings may either be [Python strftime formats][strftime] which explicitly specify 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. +* `format` - A string representing the output format. If not specified, this defaults to the same value as the `TIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `time` objects should be returned by `to_representation`. 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 specify 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. - -Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField` +**TimeField format strings**: Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`) -## FloatField - -A floating point representation. - -Corresponds to `django.db.models.fields.FloatField`. +--- -## DecimalField +# Choice selection fields -A decimal representation, represented in Python by a Decimal instance. - -Has two required arguments: +## ChoiceField -- `max_digits` The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places. +A field that can accept a value out of a limited set of choices. Takes a single mandatory argument. -- `decimal_places` The number of decimal places to store with the number. +- `choices` - A list of valid values, or a list of `(key, display_name)` tuples. -For example, to validate numbers up to 999 with a resolution of 2 decimal places, you would use: +**Signature:** `ChoiceField(choices=())` - serializers.DecimalField(max_digits=5, decimal_places=2) +## MultipleChoiceField -And to validate numbers up to anything less than one billion with a resolution of 10 decimal places: +A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. `to_internal_representation` returns a `set` containing the selected values. - serializers.DecimalField(max_digits=19, decimal_places=10) +- `choices` - A list of valid values, or a list of `(key, display_name)` tuples. -This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer. +**Signature:** `MultipleChoiceField(choices=())` -If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise. +--- -**Signature:** `DecimalField(max_digits, decimal_places, coerce_to_string=None)` - -Corresponds to `django.db.models.fields.DecimalField`. +# File upload fields ## FileField @@ -330,15 +357,17 @@ A file representation. Performs Django's standard FileField validation. Corresponds to `django.forms.fields.FileField`. -**Signature:** `FileField(max_length=None, allow_empty_file=False)` +**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)` + + - `max_length` - designates the maximum length for the file name. - - `max_length` designates the maximum length for the file name. + - `allow_empty_file` - designates if empty files are allowed. - - `allow_empty_file` designates if empty files are allowed. +- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. ## ImageField -An image representation. +An image representation. Validates the uploaded file content as matching a known image format. Corresponds to `django.forms.fields.ImageField`. @@ -348,11 +377,60 @@ Signature and validation is the same as with `FileField`. --- -**Note:** `FileFields` and `ImageFields` are only suitable for use with MultiPartParser, since e.g. json doesn't support file uploads. +**Note:** `FileFields` and `ImageFields` are only suitable for use with `MultiPartParser` or `FileUploadParser`. Most parsers, such as e.g. JSON don't support file uploads. Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files. --- +# Composite fields + +## ListField + +**TODO** + +--- + +# Miscellaneous fields + +## ReadOnlyField + +**TODO** + +## HiddenField + +**TODO** + +## ModelField + +A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. + +The `ModelField` class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model. For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))` + +**Signature:** `ModelField(model_field=)` + +## 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 constructor accepts a single optional argument, which is the name of the method on the serializer to be called. If not included this defaults to `get_`. + +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 django.contrib.auth.models import User + from django.utils.timezone import now + from rest_framework import serializers + + class UserSerializer(serializers.ModelSerializer): + days_since_joined = serializers.SerializerMethodField() + + class Meta: + model = User + + def get_days_since_joined(self, obj): + return (now() - obj.date_joined).days + +--- + # 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 initial datatype, and a primitive, serializable datatype. Primitive 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 primitive objects. -- cgit v1.2.3 From c01c631ef2c5a0f303460c505810c4987371dbcc Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 26 Nov 2014 09:04:48 +0000 Subject: perform_create, perform_update, perform_destroy hooks --- docs/api-guide/fields.md | 19 ++++++++++++------- docs/api-guide/generic-views.md | 28 ++++++++++++++-------------- 2 files changed, 26 insertions(+), 21 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 17a65ab8..1e856853 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -433,9 +433,9 @@ The method should accept a single argument (in addition to `self`), which is the # 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 initial datatype, and a primitive, serializable datatype. Primitive 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 primitive objects. +If you want to create a custom field, you'll probably want to override either one or both of the `.to_representation()` and `.to_internal_value()` methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive 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 primitive objects. -The `.to_native()` method is called to convert the initial datatype into a primitive, serializable datatype. The `from_native()` method is called to restore a primitive datatype into its initial representation. +The `.to_representation()` method is called to convert the initial datatype into a primitive, serializable datatype. The `to_internal_value()` method is called to restore a primitive datatype into its internal python representation. ## Examples @@ -450,25 +450,30 @@ Let's look at an example of serializing a class that represents an RGB color val assert(red < 256 and green < 256 and blue < 256) self.red, self.green, self.blue = red, green, blue - class ColourField(serializers.WritableField): + class ColorField(serializers.Field): """ Color objects are serialized into "rgb(#, #, #)" notation. """ - def to_native(self, obj): + def to_representation(self, obj): return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue) - def from_native(self, data): + def to_internal_value(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()`. +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 `.get_attribute()` and/or `.get_value()`. 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): + def get_attribute(self, obj): + # We pass the object instance onto `to_representation`, + # not just the field attribute. + return obj + + def to_representation(self, obj): """ Serialize the object's class name. """ diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 489b628f..dc51189c 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -7,7 +7,7 @@ source: mixins.py > > — [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 behavior. 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. @@ -171,24 +171,24 @@ For example: return 20 return 100 -**Save / deletion hooks**: +**Save and deletion 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. +The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior. -* `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. -* `pre_delete(self, obj)` - A hook that is called before deleting an object. -* `post_delete(self, obj)` - A hook that is called after deleting an object. +* `perform_create(self, serializer)` - Called by `CreateModelMixin` when saving a new object instance. +* `perform_update(self, serializer)` - Called by `UpdateModelMixin` when saving an existing object instance. +* `perform_destroy(self, instance)` - Called by `DestroyModelMixin` when deleting an object instance. -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. +These hooks are particularly useful 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. - def pre_save(self, obj): - """ - Set the object's owner, based on the incoming request. - """ - obj.owner = self.request.user + def perform_create(self, serializer): + serializer.save(user=self.request.user) + +These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update. -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. + def perform_update(self, serializer): + instance = serializer.save() + send_email_confirmation(user=self.request.user, modified=instance) **Other methods**: -- cgit v1.2.3 From 0f5338ada90ca2c6e53b9e095bec6a3b853d107b Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 26 Nov 2014 09:06:15 +0000 Subject: Call out removal of pre_save/post_save more strongly --- docs/api-guide/generic-views.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index dc51189c..8c1b7dc9 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -190,6 +190,8 @@ These override points are also particularly useful for adding behavior that occu instance = serializer.save() send_email_confirmation(user=self.request.user, modified=instance) +**Note**: These methods replace the old-style version 2.x `pre_save`, `post_save`, `pre_delete` and `post_delete` methods, which are no longer available. + **Other methods**: 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`. -- cgit v1.2.3 From e1b14cbe4acafa47154acf66c21cd9e627c7ba1a Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 26 Nov 2014 10:27:29 +0000 Subject: 3.0 docs for serializer fields --- docs/api-guide/fields.md | 251 +++++++++++++++++++++++++---------------------- 1 file changed, 132 insertions(+), 119 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 1e856853..ca551540 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -10,7 +10,7 @@ Serializer fields handle converting between primitive values and internal dataty --- -**Note:** The serializer fields are declared in fields.py, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.`. +**Note:** The serializer fields are declared in `fields.py`, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.`. --- @@ -18,14 +18,6 @@ Serializer fields handle converting between primitive values and internal dataty Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: -### `source` - -The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `Field(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `Field(source='user.email')`. - -The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. - -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 creating or updating an instance during deserialization. @@ -59,6 +51,14 @@ May be set to a function or other callable, in which case the value will be eval Note that setting a `default` value implies that the field is not required. Including both the `default` and `required` keyword arguments is invalid and will raise an error. +### `source` + +The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField('get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. + +The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. + +Defaults to the name of the field. + ### `validators` A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise `serializers.ValidationError`, but Django's built-in `ValidationError` is also supported for compatibility with validators defined in the Django codebase or third party Django packages. @@ -100,52 +100,6 @@ Two options are currently used in HTML form generation, `'input_type'` and `'bas --- -## Field - -A generic, **read-only** field. You can use this field for any attribute that does not need to support write operations. - -For example, using the following model. - - from django.db import models - from django.utils.timezone import now - - class Account(models.Model): - owner = models.ForeignKey('auth.user') - name = models.CharField(max_length=100) - created = models.DateTimeField(auto_now_add=True) - payment_expiry = models.DateTimeField() - - def has_expired(self): - return now() > self.payment_expiry - -A serializer definition that looked like this: - - from rest_framework import serializers - - class AccountSerializer(serializers.HyperlinkedModelSerializer): - expired = serializers.Field(source='has_expired') - - class Meta: - model = Account - fields = ('url', 'owner', 'name', 'expired') - -Would produce output similar to: - - { - 'url': 'http://example.com/api/accounts/3/', - 'owner': 'http://example.com/api/users/12/', - 'name': 'FooCorp business account', - 'expired': True - } - -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 behavior by overriding the `.to_native(self, value)` method. - -**TODO**: Note removal of `WritableField` - ---- - # Boolean fields ## BooleanField @@ -154,12 +108,16 @@ A boolean representation. Corresponds to `django.db.models.fields.BooleanField`. +**Signature:** `BooleanField()` + ## NullBooleanField A boolean representation that also accepts `None` as a valid value. Corresponds to `django.db.models.fields.NullBooleanField`. +**Signature:** `NullBooleanField()` + --- # String fields @@ -170,7 +128,13 @@ A text representation. Optionally validates the text to be shorter than `max_len Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.TextField`. -**Signature:** `CharField(max_length=None, min_length=None, allow_none=False)` +**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False)` + +- `max_length` - Validates that the input contains no more than this number of characters. +- `min_length` - Validates that the input contains no fewer than this number of characters. +- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. + +The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs. ## EmailField @@ -178,19 +142,19 @@ A text representation, validates the text to be a valid e-mail address. Corresponds to `django.db.models.fields.EmailField` -**Signature:** `EmailField(max_length=None, min_length=None)` +**Signature:** `EmailField(max_length=None, min_length=None, allow_blank=False)` ## RegexField A text representation, that validates the given value matches against a certain regular expression. -The mandatory `regex` argument may either be a string, or a compiled python regular expression object. +Corresponds to `django.forms.fields.RegexField`. -Uses Django's `django.core.validators.RegexValidator` for validation. +**Signature:** `RegexField(regex, max_length=None, min_length=None, allow_blank=False)` -Corresponds to `django.forms.fields.RegexField` +The mandatory `regex` argument may either be a string, or a compiled python regular expression object. -**Signature:** `RegexField(regex, max_length=None, min_length=None)` +Uses Django's `django.core.validators.RegexValidator` for validation. ## SlugField @@ -198,7 +162,7 @@ A `RegexField` that validates the input against the pattern `[a-zA-Z0-9_-]+`. Corresponds to `django.db.models.fields.SlugField`. -**Signature:** `SlugField(max_length=50, min_length=None)` +**Signature:** `SlugField(max_length=50, min_length=None, allow_blank=False)` ## URLField @@ -206,7 +170,7 @@ A `RegexField` that validates the input against a URL matching pattern. Expects Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation. -**Signature:** `URLField(max_length=200, min_length=None)` +**Signature:** `URLField(max_length=200, min_length=None, allow_blank=False)` --- @@ -216,40 +180,36 @@ Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.v An integer representation. -Has two optional arguments: +Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField`. -- `max_value` Validate that the number provided is no greater than this value. +**Signature**: `IntegerField(max_value=None, min_value=None)` +- `max_value` Validate that the number provided is no greater than this value. - `min_value` Validate that the number provided is no less than this value. -Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField`. - ## FloatField A floating point representation. -Has two optional arguments: +Corresponds to `django.db.models.fields.FloatField`. + +**Signature**: `FloatField(max_value=None, min_value=None)` - `max_value` Validate that the number provided is no greater than this value. - - `min_value` Validate that the number provided is no less than this value. -Corresponds to `django.db.models.fields.FloatField`. - ## DecimalField -A decimal representation, represented in Python by a Decimal instance. +A decimal representation, represented in Python by a `Decimal` instance. -Has two required arguments, and three optional arguments: +Corresponds to `django.db.models.fields.DecimalField`. -- `max_digits` The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places. +**Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)` +- `max_digits` The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places. - `decimal_places` The number of decimal places to store with the number. - - `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. - - `max_value` Validate that the number provided is no greater than this value. - - `min_value` Validate that the number provided is no less than this value. #### Example usage @@ -266,10 +226,6 @@ This field also takes an optional argument, `coerce_to_string`. If set to `True` If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise. -**Signature:** `DecimalField(max_digits, decimal_places, coerce_to_string=None)` - -Corresponds to `django.db.models.fields.DecimalField`. - --- # Date and time fields @@ -280,26 +236,30 @@ A date and time representation. Corresponds to `django.db.models.fields.DateTimeField`. -When using `ModelSerializer` or `HyperlinkedModelSerializer`, note that any model fields with `auto_now=True` or `auto_now_add=True` will use serializer fields that are `read_only=True` by default. +**Signature:** `DateTimeField(format=None, input_formats=None)` -If you want to override this behavior, you'll need to declare the `DateTimeField` explicitly on the serializer. For example: +* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. 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']`. - class CommentSerializer(serializers.ModelSerializer): - created = serializers.DateTimeField() +#### `DateTimeField` format strings. - class Meta: - model = Comment +Format strings may either be [Python strftime formats][strftime] which explicitly specify 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'`) -Note that by default, datetime representations are determined by the renderer in use, although this can be explicitly overridden as detailed below. +When a value of `None` is used for the format `datetime` objects will be returned by `to_representation` and the final output representation will determined by the renderer class. 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)` +#### `auto_now` and `auto_now_add` model fields. -* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. 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']`. +When using `ModelSerializer` or `HyperlinkedModelSerializer`, note that any model fields with `auto_now=True` or `auto_now_add=True` will use serializer fields that are `read_only=True` by default. + +If you want to override this behavior, you'll need to declare the `DateTimeField` explicitly on the serializer. For example: + + class CommentSerializer(serializers.ModelSerializer): + created = serializers.DateTimeField() -**DateTimeField format strings**: Format strings may either be [Python strftime formats][strftime] which explicitly specify 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'`) + class Meta: + model = Comment ## DateField @@ -312,7 +272,9 @@ Corresponds to `django.db.models.fields.DateField` * `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATE_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `date` objects should be returned by `to_representation`. 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']`. -**DateField format strings**: Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`) +#### `DateField` format strings + +Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`) ## TimeField @@ -325,7 +287,9 @@ Corresponds to `django.db.models.fields.TimeField` * `format` - A string representing the output format. If not specified, this defaults to the same value as the `TIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `time` objects should be returned by `to_representation`. 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']`. -**TimeField format strings**: Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`) +#### `TimeField` format strings + +Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`) --- @@ -333,24 +297,31 @@ Corresponds to `django.db.models.fields.TimeField` ## ChoiceField -A field that can accept a value out of a limited set of choices. Takes a single mandatory argument. +A field that can accept a value out of a limited set of choices. -- `choices` - A list of valid values, or a list of `(key, display_name)` tuples. +Used by `ModelSerializer` to automatically generate fields if the corresponding model field includes a `choices=…` argument. -**Signature:** `ChoiceField(choices=())` +**Signature:** `ChoiceField(choices)` + +- `choices` - A list of valid values, or a list of `(key, display_name)` tuples. ## MultipleChoiceField A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. `to_internal_representation` returns a `set` containing the selected values. -- `choices` - A list of valid values, or a list of `(key, display_name)` tuples. +**Signature:** `MultipleChoiceField(choices)` -**Signature:** `MultipleChoiceField(choices=())` +- `choices` - A list of valid values, or a list of `(key, display_name)` tuples. --- # File upload fields +#### Parsers and file uploads. + +The `FileField` and `ImageField` classes are only suitable for use with `MultiPartParser` or `FileUploadParser`. Most parsers, such as e.g. JSON don't support file uploads. +Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files. + ## FileField A file representation. Performs Django's standard FileField validation. @@ -359,10 +330,8 @@ Corresponds to `django.forms.fields.FileField`. **Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)` - - `max_length` - designates the maximum length for the file name. - - - `allow_empty_file` - designates if empty files are allowed. - + - `max_length` - Designates the maximum length for the file name. + - `allow_empty_file` - Designates if empty files are allowed. - `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. ## ImageField @@ -371,14 +340,13 @@ An image representation. Validates the uploaded file content as matching a known Corresponds to `django.forms.fields.ImageField`. -Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained. +**Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)` -Signature and validation is the same as with `FileField`. - ---- + - `max_length` - Designates the maximum length for the file name. + - `allow_empty_file` - Designates if empty files are allowed. +- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. -**Note:** `FileFields` and `ImageFields` are only suitable for use with `MultiPartParser` or `FileUploadParser`. Most parsers, such as e.g. JSON don't support file uploads. -Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files. +Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained. --- @@ -386,7 +354,24 @@ Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files. ## ListField -**TODO** +A field class that validates a list of objects. + +**Signature**: `ListField(child)` + +- `child` - A field instance that should be used for validating the objects in the list. + +For example, to validate a list of integers you might use something like the following: + + scores = serializers.ListField( + child=serializers.IntegerField(min_value=0, max_value=100) + ) + +The `ListField` class also supports a declarative style that allows you to write reusable list field classes. + + class StringListField(serializers.ListField): + child = serializers.CharField() + +We can now reuse our custom `StringListField` class throughout our application, without having to provide a `child` argument to it. --- @@ -394,27 +379,52 @@ Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files. ## ReadOnlyField -**TODO** +A field class that simply returns the value of the field without modification. + +This field is used by default with `ModelSerializer` when including field names that relate to an attribute rather than a model field. + +**Signature**: `ReadOnlyField()` + +For example, is `has_expired` was a property on the `Account` model, then the following serializer would automatically generate it as a `ReadOnlyField`: + + class AccountSerializer(serializers.ModelSerializer): + class Meta: + model = Account + fields = ('id', 'account_name', 'has_expired') ## HiddenField -**TODO** +A field class that does not take a value based on user input, but instead takes its value from a default value or callable. + +**Signature**: `HiddenField()` + +For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following: + + modified = serializer.HiddenField(default=timezone.now) + +The `HiddenField` class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user. + +For further examples on `HiddenField` see the [validators](validators.md) documentation. ## ModelField -A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. +A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. -The `ModelField` class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model. For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))` +This field is used by `ModelSerializer` to correspond to custom model field classes. **Signature:** `ModelField(model_field=)` +The `ModelField` class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model. For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))` + ## 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 constructor accepts a single optional argument, which is the name of the method on the serializer to be called. If not included this defaults to `get_`. +**Signature**: `SerializerMethodField(method_name=None)` + +- `method-name` - The name of the method on the serializer to be called. If not included this defaults to `get_`. -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: +The serializer method referred to by the `method_name` argument 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 django.contrib.auth.models import User from django.utils.timezone import now @@ -433,9 +443,13 @@ The method should accept a single argument (in addition to `self`), which is the # Custom fields -If you want to create a custom field, you'll probably want to override either one or both of the `.to_representation()` and `.to_internal_value()` methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive 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 primitive objects. +If you want to create a custom field, you'll need to subclass `Field` and then override either one or both of the `.to_representation()` and `.to_internal_value()` methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, `date`/`time`/`datetime` or `None`. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using. -The `.to_representation()` method is called to convert the initial datatype into a primitive, serializable datatype. The `to_internal_value()` method is called to restore a primitive datatype into its internal python representation. +The `.to_representation()` method is called to convert the initial datatype into a primitive, serializable datatype. + +The `to_internal_value()` method is called to restore a primitive datatype into its internal python representation. + +Note that the `WritableField` class that was present in version 2.x no longer exists. You should subclass `Field` and override `to_internal_value()` if the field supports data input. ## Examples @@ -462,7 +476,6 @@ Let's look at an example of serializing a class that represents an RGB color val 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 `.get_attribute()` and/or `.get_value()`. As an example, let's create a field that can be used represent the class name of the object being serialized: -- cgit v1.2.3 From 5a5a73c7fef49899a37721e6c68228ef605e11f8 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 26 Nov 2014 11:30:49 +0000 Subject: 3.0 docs and tidy-up for serializer relationships --- docs/api-guide/relations.md | 81 +++++++++++++++++++++++---------------------- 1 file changed, 41 insertions(+), 40 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index ad981b2b..7d19eba2 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -16,6 +16,20 @@ Relational fields are used to represent model relationships. They can be applie --- +#### Inspecting automatically generated relationships. + +When using the `ModelSerializer` class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style. + +To do so, open the Django shell, using `python manage.py shell`, then import the serializer class, instantiate it, and print the object representation… + + >>> from myapp.serializers import AccountSerializer + >>> serializer = AccountSerializer() + >>> print repr(serializer) # Or `print(repr(serializer))` in Python 3.x. + AccountSerializer(): + id = IntegerField(label='ID', read_only=True) + name = CharField(allow_blank=True, max_length=100, required=False) + owner = PrimaryKeyRelatedField(queryset=User.objects.all()) + # API Reference In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album. @@ -37,14 +51,14 @@ In order to explain the various types of relational fields, we'll use a couple o def __unicode__(self): return '%d: %s' % (self.order, self.title) -## RelatedField +## StringRelatedField -`RelatedField` may be used to represent the target of the relationship using its `__unicode__` method. +`StringRelatedField` may be used to represent the target of the relationship using its `__unicode__` method. For example, the following serializer. class AlbumSerializer(serializers.ModelSerializer): - tracks = serializers.RelatedField(many=True) + tracks = serializers.StringRelatedField(many=True) class Meta: model = Album @@ -99,9 +113,9 @@ By default this field is read-write, although you can change this behavior using **Arguments**: +* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`. * `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`. +* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`. ## HyperlinkedRelatedField @@ -110,8 +124,11 @@ By default this field is read-write, although you can change this behavior using For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): - tracks = serializers.HyperlinkedRelatedField(many=True, read_only=True, - view_name='track-detail') + tracks = serializers.HyperlinkedRelatedField( + many=True, + read_only=True, + view_name='track-detail' + ) class Meta: model = Album @@ -134,11 +151,12 @@ By default this field is read-write, although you can change this behavior using **Arguments**: -* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this wil be a string with the format `-detail`. **required**. +* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `-detail`. **required**. +* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`. * `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`. +* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`. * `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'`. +* `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as `lookup_field`. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. ## SlugRelatedField @@ -148,8 +166,11 @@ By default this field is read-write, although you can change this behavior using For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): - tracks = serializers.SlugRelatedField(many=True, read_only=True, - slug_field='title') + tracks = serializers.SlugRelatedField( + many=True, + read_only=True, + slug_field='title' + ) class Meta: model = Album @@ -175,9 +196,9 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e **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`. **required** +* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`. * `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`. +* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`. ## HyperlinkedIdentityField @@ -245,9 +266,9 @@ Would serialize to a nested representation like this: # Custom relational fields -To implement a custom relational field, you should override `RelatedField`, and implement the `.to_native(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. +To implement a custom relational field, you should override `RelatedField`, and implement the `.to_representation(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. The `value` argument will typically be a model instance. -If you want to implement a read-write relational field, you must also implement the `.from_native(self, data)` method, and add `read_only = False` to the class definition. +If you want to implement a read-write relational field, you must also implement the `.to_internal_value(self, data)` method. ## Example @@ -256,7 +277,7 @@ For, example, we could define a relational field, to serialize a track to a cust import time class TrackListingField(serializers.RelatedField): - def to_native(self, value): + def to_representation(self, value): duration = time.strftime('%M:%S', time.gmtime(value.duration)) return 'Track %d: %s (%s)' % (value.order, value.name, duration) @@ -350,7 +371,7 @@ We could define a custom field that could be used to serialize tagged instances, A custom field to use for the `tagged_object` generic relationship. """ - def to_native(self, value): + def to_representation(self, value): """ Serialize tagged objects to a simple textual representation. """ @@ -360,9 +381,9 @@ We could define a custom field that could be used to serialize tagged instances, return 'Note: ' + value.text raise Exception('Unexpected type of tagged object') -If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_native()` method: +If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_native()` method: - def to_native(self, value): + def to_representation(self, value): """ Serialize bookmark instances using a bookmark serializer, and note instances using a note serializer. @@ -404,7 +425,6 @@ 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. @@ -425,25 +445,6 @@ For example, if all your object URLs used both a account and a slug in the the U --- -## Deprecated APIs - -The following classes have been deprecated, in favor of the `many=` syntax. -They continue to function, but their usage will raise a `PendingDeprecationWarning`, which is silent by default. - -* `ManyRelatedField` -* `ManyPrimaryKeyRelatedField` -* `ManyHyperlinkedRelatedField` -* `ManySlugRelatedField` - -The `null=` flag has been deprecated in favor of the `required=` flag. It will continue to function, but will raise a `PendingDeprecationWarning`. - -In the 2.3 release, these warnings will be escalated to a `DeprecationWarning`, which is loud by default. -In the 2.4 release, these parts of the API will be removed entirely. - -For more details see the [2.2 release announcement][2.2-announcement]. - ---- - # Third Party Packages The following third party packages are also available. -- cgit v1.2.3 From 786cab705a37f6b2196560d0e476e5c849420a61 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 26 Nov 2014 11:38:48 +0000 Subject: Tweak to 3.0 relationship docs --- docs/api-guide/relations.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 7d19eba2..17009bbc 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -245,7 +245,7 @@ For example, the following serializer: fields = ('order', 'title') class AlbumSerializer(serializers.ModelSerializer): - tracks = TrackSerializer(many=True) + tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album @@ -305,6 +305,16 @@ This custom field would then serialize to the following representation. # Further notes +## The `queryset` argument + +The `queryset` argument is only ever required for *writable* relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance. + +In version 2.x a serializer class could *sometimes* automatically determine the `queryset` argument *if* a `ModelSerializer` class was being used. + +This behavior is now replaced with *always* using an explicit `queryset` argument for writable relational fields. + +Doing so reduces the amount of hidden 'magic' that `ModelSerializer` provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the `ModelSerializer` shortcut, or using fully explicit `Serializer` classes. + ## Reverse relations 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: -- cgit v1.2.3 From 0262262feefc1a8130cb852a6b710a16ebc24cb9 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 27 Nov 2014 08:09:58 +0000 Subject: 3.0 serializer docs --- docs/api-guide/serializers.md | 335 ++++++++++++++++++++++++++---------------- 1 file changed, 206 insertions(+), 129 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 2d0ff79a..e476d957 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -10,7 +10,7 @@ will take some serious design work. Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into `JSON`, `XML` or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. -REST framework's serializers work very similarly to Django's `Form` and `ModelForm` classes. It provides a `Serializer` class which gives you a powerful, generic way to control the output of your responses, as well as a `ModelSerializer` class which provides a useful shortcut for creating serializers that deal with model instances and querysets. +The serializers in REST framework work very similarly to Django's `Form` and `ModelForm` classes. We provide a `Serializer` class which gives you a powerful, generic way to control the output of your responses, as well as a `ModelSerializer` class which provides a useful shortcut for creating serializers that deal with model instances and querysets. ## Declaring Serializers @@ -24,7 +24,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. +We'll declare a serializer that we can use to serialize and deserialize data that corresponds to `Comment` objects. Declaring a serializer looks very similar to declaring a form: @@ -35,25 +35,9 @@ Declaring a serializer looks very similar to declaring a form: content = serializers.CharField(max_length=200) 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.email = attrs.get('email', instance.email) - 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 into fully fledged object instances. If we don't define this method, then deserializing data will simply return a dictionary of items. - ## Serializing objects -We can now use `CommentSerializer` to serialize a comment, or list of comments. Again, using the `Serializer` class looks a lot like using a `Form` class. +We can now use `CommentSerializer` to serialize a comment, or list of comments. Again, using the `Serializer` class looks a lot like using a `Form` class. serializer = CommentSerializer(comment) serializer.data @@ -67,24 +51,9 @@ At this point we've translated the model instance into Python native datatypes. json # '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}' -### Customizing field representation - -Sometimes when serializing objects, you may not want to represent everything exactly the way it is in your model. - -If you need to customize the serialized value of a particular field, you can do this by creating a `transform_` method. For example if you needed to render some markdown from a text field: - - description = serializers.CharField() - description_html = serializers.CharField(source='description', read_only=True) - - def transform_description_html(self, obj, value): - from django.contrib.markup.templatetags.markup import markdown - return markdown(value) - -These methods are essentially the reverse of `validate_` (see *Validation* below.) - ## Deserializing objects -Deserialization is similar. First we parse a stream into Python native datatypes... +Deserialization is similar. First we parse a stream into Python native datatypes... from StringIO import StringIO from rest_framework.parsers import JSONParser @@ -92,26 +61,90 @@ Deserialization is similar. First we parse a stream into Python native datatype stream = StringIO(json) data = JSONParser().parse(stream) -...then we restore those native datatypes into a fully populated object instance. +...then we restore those native datatypes into a dictionary of validated data. serializer = CommentSerializer(data=data) serializer.is_valid() # True - serializer.object - # + serializer.validated_data + # {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)} + +## Saving instances + +If we want to be able to return complete object instances based on the validated data we need to implement one or both of the `.create()` and `update()` methods. For example: + + class CommentSerializer(serializers.Serializer): + email = serializers.EmailField() + content = serializers.CharField(max_length=200) + created = serializers.DateTimeField() + + def create(self, validated_data): + return Comment(**validated_data) + + def update(self, instance, validated_data): + instance.email = validated_data.get('email', instance.email) + instance.content = validated_data.get('content', instance.content) + instance.created = validated_data.get('created', instance.created) + return instance + +If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if `Comment` was a Django model, the methods might look like this: + + def create(self, validated_data): + return Comment.objcts.create(**validated_data) + + def update(self, instance, validated_data): + instance.email = validated_data.get('email', instance.email) + instance.content = validated_data.get('content', instance.content) + instance.created = validated_data.get('created', instance.created) + instance.save() + return instance + +Now when deserializing data, we can call `.save()` to return an object instance, based on the validated data. + + comment = serializer.save() + +Calling `.save()` will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class: + + # .save() will create a new instance. + serializer = CommentSerializer(data=data) + + # .save() will update the existing `comment` instance. + serializer = CommentSerializer(comment, data=data) -When deserializing data, we can either create a new instance, or update an existing instance. +Both the `.create()` and `.update()` methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class. - serializer = CommentSerializer(data=data) # Create new instance - serializer = CommentSerializer(comment, data=data) # Update `comment` +#### Passing additional attributes to `.save()` -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. +Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data. - serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `comment` with partial data +You can do so by including additional keyword arguments when calling `.save()`. For example: + + serializer.save(owner=request.user) + +Any additional keyword arguments will be included in the `validated_data` argument when `.create()` or `.update()` are called. + +#### Overriding `.save()` directly. + +In some cases the `.create()` and `.update()` method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message. + +In these cases you might instead choose to override `.save()` directly, as being more readable and meaningful. + +For example: + + class ContactForm(serializers.Serializer): + email = serializers.EmailField() + message = serializers.CharField() + + def save(self): + email = self.validated_data['email'] + message = self.validated_data['message'] + send_email(from=email, message=message) + +Note that in the case above we're now having to access the serializer `.validated_data` property directly. ## 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` property will contain a dictionary representing the resulting error messages. For example: +When deserializing data, you always need to call `is_valid()` before attempting to access the validated data, or save an object instance. If any validation errors occur, the `.errors` property will contain a dictionary representing the resulting error messages. For example: serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'}) serializer.is_valid() @@ -119,17 +152,26 @@ When deserializing data, you always need to call `is_valid()` before attempting 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. +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. The name of the `non_field_errors` key may be customized using the `NON_FIELD_ERRORS_KEY` REST framework setting. When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items. +#### Raising an exception on invalid data + +The `.is_valid()` method takes an optional `raise_exception` flag that will cause it to raise a `serializers.ValidationError` exception if there are validation errors. + +These exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return `HTTP 400 Bad Request` responses by default. + + # Return a 400 response if the data was invalid. + serializer.is_valid(raise_exception=True) + #### Field-level validation -You can specify custom field-level validation by adding `.validate_` methods to your `Serializer` subclass. These are analogous to `.clean_` methods on Django forms, but accept slightly different arguments. +You can specify custom field-level validation by adding `.validate_` methods to your `Serializer` subclass. These are similar to the `.clean_` methods on Django forms. -They take a dictionary of deserialized attributes as a first argument, and the field name in that dictionary as a second argument (which will be either the name of the field or the value of the `source` argument to the field, if one was provided). +These methods take a single argument, which is the field value that requires validation. -Your `validate_` methods should either just return the `attrs` dictionary or raise a `ValidationError`. For example: +Your `validate_` methods should return the validated value or raise a `ValidationError`. For example: from rest_framework import serializers @@ -137,18 +179,17 @@ Your `validate_` methods should either just return the `attrs` dictio title = serializers.CharField(max_length=100) content = serializers.CharField() - def validate_title(self, attrs, source): + def validate_title(self, value): """ Check that the blog post is about Django. """ - value = attrs[source] - if "django" not in value.lower(): + if 'django' not in value.lower(): raise serializers.ValidationError("Blog post is not about Django") - return attrs + return value #### 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: +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 a dictionary of field values. It should raise a `ValidationError` if necessary, or just return the validated values. For example: from rest_framework import serializers @@ -157,24 +198,48 @@ To do any other validation that requires access to multiple fields, add a method start = serializers.DateTimeField() finish = serializers.DateTimeField() - def validate(self, attrs): + def validate(self, data): """ Check that the start is before the stop. """ - if attrs['start'] > attrs['finish']: + if data['start'] > data['finish']: raise serializers.ValidationError("finish must occur after start") - return attrs + return data + +#### Validators + +Individual fields on a serializer can include validators, by declaring them on the field instance, for example: + + def multiple_of_ten(value): + if value % 10 != 0: + raise serializers.ValidationError('Not a multiple of ten') -## Saving object state + class GameRecord(serializers.Serializer): + score = IntegerField(validators=[multiple_of_ten]) + ... -To save the deserialized objects created by a serializer, call the `.save()` method: +Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner `Meta` class, like so: + + class EventSerializer(serializers.Serializer): + name = serializers.CharField() + room_number = serializers.IntegerField(choices=[101, 102, 103, 201]) + date = serializers.DateField() + + class Meta: + # Each room only has one event per day. + validators = UniqueTogetherValidator( + queryset=Event.objects.all(), + fields=['room_number', 'date'] + ) - if serializer.is_valid(): - serializer.save() +For more information see the [validators documentation](validators.md). -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. +## Partial updates -The generic views provided by REST framework call the `.save()` method when updating or creating entities. +By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the `partial` argument in order to allow partial updates. + + # Update `comment` with partial data + serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) ## Dealing with nested objects @@ -214,6 +279,8 @@ Validation of nested objects will work the same as before. Errors with nested o serializer.errors # {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']} +**TODO** Document create and update for nested serializers + ## Dealing with multiple objects The `Serializer` class can also handle serializing or deserializing lists of objects. @@ -233,6 +300,8 @@ To serialize a queryset or list of objects instead of a single object instance, #### Deserializing multiple objects for creation +**TODO** + 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. @@ -250,6 +319,8 @@ For example: #### Deserializing multiple objects for update +**TODO** + 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. @@ -278,32 +349,6 @@ When performing a bulk update you may want to allow new items to be created, and 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. @@ -314,28 +359,46 @@ You can provide arbitrary additional context by passing a `context` argument whe serializer.data # {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'} -The context dictionary can be used within any serializer field logic, such as a custom `.to_native()` method, by accessing the `self.context` attribute. +The context dictionary can be used within any serializer field logic, such as a custom `.to_representation()` method, by accessing the `self.context` attribute. + +--- -- # 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. +Often you'll want serializer classes that map closely to Django model definitions. + +The `ModelSerializer` class provides a shortcut that lets you automatically create a `Serializer` class with fields that correspond to the Model fields. + +**The `ModelSerializer` class is the same as a regular `Serializer` class, except that**: + +* It will automatically generate a set of fields for you, based on the model. +* It will automatically generate validators for the serializer, such as unique_together validators. +* It includes simple default implementations of `.create()` and `.update()`. + +Declaring a `ModelSerializer` looks like this: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account -By default, all the model fields on the class will be mapped to corresponding serializer fields. +By default, all the model fields on the class will be mapped to a corresponding serializer fields. -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. +Any relationships such as foreign keys on the model will be mapped to `PrimaryKeyRelatedField`. Reverse relationships are not included by default unless explicitly included as described below. ---- +#### Inspecting the generated `ModelSerializer` class. -**Note**: When validation is applied to a `ModelSerializer`, both the serializer fields, and their corresponding model fields must correctly validate. If you have optional fields on your model, make sure to correctly set `blank=True` on the model field, as well as setting `required=False` on the serializer field. +Serializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with `ModelSerializers` where you want to determine what set of fields and validators are being automatically created for you. ---- +To do so, open the Django shell, using `python manage.py shell`, then import the serializer class, instantiate it, and print the object representation… + >>> from myapp.serializers import AccountSerializer + >>> serializer = AccountSerializer() + >>> print repr(serializer) # Or `print(repr(serializer))` in Python 3.x. + AccountSerializer(): + id = IntegerField(label='ID', read_only=True) + name = CharField(allow_blank=True, max_length=100, required=False) + owner = PrimaryKeyRelatedField(queryset=User.objects.all()) + ## 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`. @@ -347,6 +410,10 @@ For example: model = Account fields = ('id', 'account_name', 'users', 'created') +The names in the `fields` option will normally map to model fields on the model class. + +Alternatively names in the `fields` options can map to properties or methods which take no arguments that exist on the model class. + ## Specifying nested serialization The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option: @@ -361,9 +428,24 @@ The `depth` option should be set to an integer value that indicates the depth of If you want to customize the way the serialization is done (e.g. using `allow_add_remove`) you'll need to define the field yourself. +## Specifying fields explicitly + +You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class. + + class AccountSerializer(serializers.ModelSerializer): + url = serializers.CharField(source='get_absolute_url', read_only=True) + groups = serializers.PrimaryKeyRelatedField(many=True) + + class Meta: + model = Account + +Extra fields can correspond to any property or callable on the model. + ## 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: +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 shortcut Meta option, `read_only_fields`. + +This option should be a list or tuple of field names, and is declared as follows: class AccountSerializer(serializers.ModelSerializer): class Meta: @@ -373,38 +455,27 @@ You may wish to specify multiple fields as read-only. Instead of adding each fi 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 which fields should be write-only +## Specifying additional keyword arguments for fields. + +There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the `extra_kwargs` option. Similarly to `read_only_fields` this means you do not need to explicitly declare the field on the serializer. -You may wish to specify multiple fields as write-only. Instead of adding each field explicitly with the `write_only=True` attribute, you may use the `write_only_fields` Meta option, like so: +This option is a dictionary, mapping field names to a dictionary of keyword arguments. For example: class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'username', 'password') - write_only_fields = ('password',) # Note: Password field is write-only - - def restore_object(self, attrs, instance=None): - """ - Instantiate a new User instance. - """ - assert instance is None, 'Cannot update users with CreateUserSerializer' - user = User(email=attrs['email'], username=attrs['username']) - user.set_password(attrs['password']) + extra_kwargs = {'password': {'write_only': True}} + + def create(self, validated_data): + user = User( + email=validated_data['email'], + username=validated_data['username'] + ) + user.set_password(validated_data['password']) + user.save() return user -## Specifying fields explicitly - -You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class. - - class AccountSerializer(serializers.ModelSerializer): - url = serializers.CharField(source='get_absolute_url', read_only=True) - groups = serializers.PrimaryKeyRelatedField(many=True) - - class Meta: - model = Account - -Extra fields can correspond to any property or callable on the model. - ## Relational fields When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for `ModelSerializer` is to use the primary keys of the related instances. @@ -415,7 +486,7 @@ For full details see the [serializer relations][relations] documentation. ## Inheritance of the 'Meta' class -The inner `Meta` class on serializers is not inherited from parent classes by default. This is the same behaviour as with Django's `Model` and `ModelForm` classes. If you want the `Meta` class to inherit from a parent class you must do so explicitly. For example: +The inner `Meta` class on serializers is not inherited from parent classes by default. This is the same behavior as with Django's `Model` and `ModelForm` classes. If you want the `Meta` class to inherit from a parent class you must do so explicitly. For example: class AccountSerializer(MyBaseSerializer): class Meta(MyBaseSerializer.Meta): @@ -446,7 +517,7 @@ There needs to be a way of determining which views should be used for hyperlinki 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 a field on the model. For example: +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 a field on the model. For example: class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: @@ -460,8 +531,8 @@ For more specific requirements such as specifying a different lookup for each fi class AccountSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( - view_name='account_detail', - lookup_field='account_name' + view_name='account-detail', + lookup_field='slug' ) users = serializers.HyperlinkedRelatedField( view_name='user-detail', @@ -486,7 +557,7 @@ You can also override this on a per-serializer basis by using the `url_field_nam fields = ('account_url', 'account_name', 'users', 'created') url_field_name = 'account_url' -**Note**: The generic view implementations normally generate a `Location` header in response to successful `POST` requests. Serializers using `url_field_name` option will not have this header automatically included by the view. If you need to do so you will ned to also override the view's `get_success_headers()` method. +**Note**: The generic view implementations normally generate a `Location` header in response to successful `POST` requests. Serializers using `url_field_name` option will not have this header automatically included by the view. If you need to do so you will ned to also override the view's `get_success_headers()` method. You can also override the URL field's view name and lookup field without overriding the field explicitly, by using the `view_name` and `lookup_field` options, like so: @@ -499,8 +570,12 @@ You can also override the URL field's view name and lookup field without overrid --- +**TODO**: ListSerializer, BaseSerializer, overriding `to_representation` on serializers. + # Advanced serializer usage +**TODO**: Tweak section below + 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. @@ -528,7 +603,7 @@ For example, if you wanted to be able to set which fields should be used by a se # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) - if fields: + if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) @@ -548,7 +623,9 @@ This would then allow you to do the following: >>> print UserSerializer(user, fields=('id', 'email')) {'id': 2, 'email': 'jon@example.com'} -## Customising the default fields +## Customizing the default fields + +**TODO**: Remove and note incoming API. 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. -- cgit v1.2.3 From 34ca8cd2a5c030d9acc89720876ba9583c1dc988 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 28 Nov 2014 09:56:44 +0000 Subject: Moar docs. Amazing. --- docs/api-guide/serializers.md | 306 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 262 insertions(+), 44 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index e476d957..6c370f75 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -167,11 +167,11 @@ These exceptions are automatically dealt with by the default exception handler t #### Field-level validation -You can specify custom field-level validation by adding `.validate_` methods to your `Serializer` subclass. These are similar to the `.clean_` methods on Django forms. +You can specify custom field-level validation by adding `.validate_` methods to your `Serializer` subclass. These are similar to the `.clean_` methods on Django forms. These methods take a single argument, which is the field value that requires validation. -Your `validate_` methods should return the validated value or raise a `ValidationError`. For example: +Your `validate_` methods should return the validated value or raise a `serializers.ValidationError`. For example: from rest_framework import serializers @@ -317,6 +317,20 @@ For example: # True serializer.save() # `.save()` will be called on each deserialized instance +The default implementation for multiple object creation is to simply call `.create()` for each item in the list. If you want to customize this behavior, you'll need to customize the `.create()` method on `ListSerializer` class that is used when `many=True` is passed. + +For example: + + class BookListSerializer(serializers.ListSerializer): + def create(self, validated_data): + books = [Book(**item) for item in validated_data] + return Book.objects.bulk_create(books) + + class BookSerializer(serializers.Serializer): + … + class Meta: + list_serializer_class = BookListSerializer + #### Deserializing multiple objects for update **TODO** @@ -570,15 +584,253 @@ You can also override the URL field's view name and lookup field without overrid --- -**TODO**: ListSerializer, BaseSerializer, overriding `to_representation` on serializers. +# ListSerializer + +The `ListSerializer` class provides the behavior for serializing and validating multiple objects at once. You won't *typically* need to use `ListSerializer` directly, but should instead simply pass `many=True` when instantiating a serializer. + +When a serializer is instantiated and `many=True` is passed, a `ListSerializer` instance will be created. The serializer class then becomes a child of the parent `ListSerializer` + +There *are* a few use cases when you might want to customize the `ListSerializer` behavior. For example: + +* You want to provide particular validation of the lists, such as always ensuring that there is at least one element in a list. +* You want to customize the create or update behavior of multiple objects. + +For these cases you can modify the class that is used when `many=True` is passed, by using the `list_serializer_class` option on the serializer `Meta` class. + +For example: + + class CustomListSerializer(serializers.ListSerializer): + ... + + class CustomSerializer(serializers.Serializer): + ... + class Meta: + list_serializer_class = CustomListSerializer + +#### Customizing `.create()` for multiple objects. + +The default implementation for multiple object creation is to simply call `.create()` for each item in the list. If you want to customize this behavior, you'll need to customize the `.create()` method on `ListSerializer` class that is used when `many=True` is passed. + +For example: + + class BookListSerializer(serializers.ListSerializer): + def create(self, validated_data): + books = [Book(**item) for item in validated_data] + return Book.objects.bulk_create(books) + + class BookSerializer(serializers.Serializer): + ... + class Meta: + list_serializer_class = BookListSerializer + +#### Customizing `.update()` for multiple objects. + +By default the `ListSerializer` class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous. + +To support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind: + +* How do you determine which instance should be updated for each item in the list of data? +* How should insertions be handled? Are they invalid, or do they create new objects? +* How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid? +* How should ordering be handled? Does changing the position of two items imply any state change or is it ignored? + +Here's an example of how you might choose to implement multiple updates: + + class BookListSerializer(serializers.ListSerializer): + def update(self, instance, validated_data): + # Maps for id->instance and id->data item. + book_mapping = {book.id: book for book in instance} + data_mapping = {item['id']: item for item in validated_data} + + # Perform creations and updates. + ret = [] + for book_id, data in data_mapping.items(): + book = book_mapping.get(book_id, None): + if book is None: + ret.append(self.child.create(data)) + else: + ret.append(self.child.update(book, data)) + + # Perform deletions. + for book_id, book in book_mapping.items(): + if book_id not in data_mapping: + book.delete() + + return ret + + class BookSerializer(serializers.Serializer): + ... + class Meta: + list_serializer_class = BookListSerializer + +--- + +# BaseSerializer + +`BaseSerializer` class that can be used to easily support alternative serialization and deserialization styles. + +This class implements the same basic API as the `Serializer` class: + +* `.data` - Returns the outgoing primitive representation. +* `.is_valid()` - Deserializes and validates incoming data. +* `.validated_data` - Returns the validated incoming data. +* `.errors` - Returns an errors during validation. +* `.save()` - Persists the validated data into an object instance. + +There are four methods that can be overridden, depending on what functionality you want the serializer class to support: + +* `.to_representation()` - Override this to support serialization, for read operations. +* `.to_internal_value()` - Override this to support deserialization, for write operations. +* `.create()` and `.update()` - Overide either or both of these to support saving instances. + +Because this class provides the same interface as the `Serializer` class, you can use it with the existing generic class based views exactly as you would for a regular `Serializer` or `ModelSerializer`. + +The only difference you'll notice when doing so is the `BaseSerializer` classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input. + +##### Read-only `BaseSerializer` classes. + +To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model: + + class HighScore(models.Model): + created = models.DateTimeField(auto_now_add=True) + player_name = models.CharField(max_length=10) + score = models.IntegerField() + +It's simple to create a read-only serializer for converting `HighScore` instances into primitive data types. + + class HighScoreSerializer(serializers.BaseSerializer): + def to_representation(self, obj): + return { + 'score': obj.score, + 'player_name': obj.player_name + } + +We can now use this class to serialize single `HighScore` instances: + + @api_view(['GET']) + def high_score(request, pk): + instance = HighScore.objects.get(pk=pk) + serializer = HighScoreSerializer(instance) + return Response(serializer.data) + +Or use it to serialize multiple instances: + + @api_view(['GET']) + def all_high_scores(request): + queryset = HighScore.objects.order_by('-score') + serializer = HighScoreSerializer(queryset, many=True) + return Response(serializer.data) + +##### Read-write `BaseSerializer` classes. + +To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `ValidationError` if the supplied data is in an incorrect format. + +Once you've implemented `.to_internal_value()`, the basic validation API will be available on the serializer, and you will be able to use `.is_valid()`, `.validated_data` and `.errors`. + +If you want to also support `.save()` you'll need to also implement either or both of the `.create()` and `.update()` methods. + +Here's a complete example of our previous `HighScoreSerializer`, that's been updated to support both read and write operations. + + class HighScoreSerializer(serializers.BaseSerializer): + def to_internal_value(self, data): + score = data.get('score') + player_name = data.get('player_name') + + # Perform the data validation. + if not score: + raise ValidationError({ + 'score': 'This field is required.' + }) + if not player_name: + raise ValidationError({ + 'player_name': 'This field is required.' + }) + if len(player_name) > 10: + raise ValidationError({ + 'player_name': 'May not be more than 10 characters.' + }) + + # Return the validated values. This will be available as + # the `.validated_data` property. + return { + 'score': int(score), + 'player_name': player_name + } + + def to_representation(self, obj): + return { + 'score': obj.score, + 'player_name': obj.player_name + } + + def create(self, validated_data): + return HighScore.objects.create(**validated_data) + +#### Creating new generic serializers with `BaseSerializer`. + +The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends. + +The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations. + + class ObjectSerializer(serializers.BaseSerializer): + """ + A read-only serializer that coerces arbitrary complex objects + into primitive representations. + """ + def to_representation(self, obj): + for attribute_name in dir(obj): + attribute = getattr(obj, attribute_name) + if attribute_name('_'): + # Ignore private attributes. + pass + elif hasattr(attribute, '__call__'): + # Ignore methods and other callables. + pass + elif isinstance(attribute, (str, int, bool, float, type(None))): + # Primitive types can be passed through unmodified. + output[attribute_name] = attribute + elif isinstance(attribute, list): + # Recursively deal with items in lists. + output[attribute_name] = [ + self.to_representation(item) for item in attribute + ] + elif isinstance(attribute, dict): + # Recursively deal with items in dictionaries. + output[attribute_name] = { + str(key): self.to_representation(value) + for key, value in attribute.items() + } + else: + # Force anything else to its string representation. + output[attribute_name] = str(attribute) + +--- # Advanced serializer usage -**TODO**: Tweak section below +## Overriding serialization and deserialization behavior -You can create customized subclasses of `ModelSerializer` or `HyperlinkedModelSerializer` that use a different set of default fields. +If you need to alter the serialization, deserialization or validation of a serializer class you can do so by overriding the `.to_representation()` or `.to_internal_value()` methods. -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. +Some reasons this might be useful include... + +* Adding new behavior for new serializer base classes. +* Modifying the behavior slightly for an existing class. +* Improving serialization performance for a frequently accessed API endpoint that returns lots of data. + +The signatures for these methods are as follows: + +#### `.to_representation(self, obj)` + +Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API. + +#### ``.to_internal_value(self, data)`` + +Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class. + +If any of the validation fails, then the method should raise a `serializers.ValidationError(errors)`. Typically the `errors` argument here will be a dictionary mapping field names to error messages. + +The `data` argument passed to this method will normally be the value of `request.data`, so the datatype it provides will depend on the parser classes you have configured for your API. ## Dynamically modifying fields @@ -625,47 +877,13 @@ This would then allow you to do the following: ## Customizing the default fields -**TODO**: Remove and note incoming API. - -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. - -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 - -**Signature**: `.get_pk_field(self, model_field)` - -Returns the field instance that should be used to represent the pk field. +REST framework 2 provided an API to allow developers to override how a `ModelSerializer` class would automatically generate the default set of fields. -### get_nested_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, 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 +This API included the `.get_field()`, `.get_pk_field()` and other methods. -The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default. +Because the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change. - class NoPKModelSerializer(serializers.ModelSerializer): - def get_pk_field(self, model_field): - return None +A new interface for controlling this behavior is currently planned for REST framework 3.1. --- -- cgit v1.2.3 From 276a2a52eedb97a15d85e059424870bf2d21854d Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 28 Nov 2014 11:26:35 +0000 Subject: Docs on nested creates/updates and suchlike --- docs/api-guide/serializers.md | 166 +++++++++++++++++++++++++----------------- 1 file changed, 100 insertions(+), 66 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 6c370f75..cd076b4f 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -271,7 +271,9 @@ Similarly if a nested representation should be a list of items, you should pass content = serializers.CharField(max_length=200) created = serializers.DateTimeField() -Validation of nested objects will work the same as before. Errors with nested objects will be nested under the field name of the nested object. +## Writable nested representations + +When dealing with nested representations that support deserializing the data, an errors with nested objects will be nested under the field name of the nested object. serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'}) serializer.is_valid() @@ -279,89 +281,117 @@ Validation of nested objects will work the same as before. Errors with nested o serializer.errors # {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']} -**TODO** Document create and update for nested serializers +Similarly, the `.validated_data` property will include nested data structures. -## Dealing with multiple objects +#### Writing `.create()` methods for nested representations -The `Serializer` class can also handle serializing or deserializing lists of objects. +If you're supporting writable nested representations you'll need to write `.create()` or `.update()` methods that handle saving multiple objects. -#### Serializing multiple objects +The following example demonstrates how you might handle creating a user with a nested profile object. -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. + class UserSerializer(serializers.ModelSerializer): + profile = ProfileSerializer() - 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'} - # ] + class Meta: + model = User + fields = ('username', 'email', 'profile') -#### Deserializing multiple objects for creation + def create(self, validated_data): + profile_data = validated_data.pop('profile') + user = User.objects.create(**validated_data) + Profile.objects.create(user=user, **profile_data) + return user -**TODO** +#### Writing `.update()` methods for nested representations -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. +For updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is `None`, or not provided, which of the following should occur? -This allows you to write views that create multiple items when a `POST` request is made. +* Set the relationship to `NULL` in the database. +* Delete the associated instance. +* Ignore the data and leave the instance as it is. +* Raise a validation error. -For example: +Here's an example for an `update()` method on our previous `UserSerializer` class. - 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 + def update(self, instance, validated_data): + profile_data = validated_data.pop('profile') + # Unless the application properly enforces that this field is + # always set, the follow could raise a `DoesNotExist`, which + # would need to be handled. + profile = instance.profile + + user.username = validated_data.get('username', instance.username) + user.email = validated_data.get('email', instance.email) + user.save() -The default implementation for multiple object creation is to simply call `.create()` for each item in the list. If you want to customize this behavior, you'll need to customize the `.create()` method on `ListSerializer` class that is used when `many=True` is passed. + profile.is_premium_member = profile_data.get( + 'is_premium_member', + profile.is_premium_member + ) + profile.has_support_contract = profile_data.get( + 'has_support_contract', + profile.has_support_contract + ) + profile.save() -For example: + return user - class BookListSerializer(serializers.ListSerializer): - def create(self, validated_data): - books = [Book(**item) for item in validated_data] - return Book.objects.bulk_create(books) +Because the behavior of nested creates and updates can be ambiguous, and may require complex dependancies between related models, REST framework 3 requires you to always write these methods explicitly. The default `ModelSerializer` `.create()` and `.update()` methods do not include support for writable nested representations. - class BookSerializer(serializers.Serializer): - … - class Meta: - list_serializer_class = BookListSerializer +It is possible that a third party package, providing automatic support some kinds of automatic writable nested representations may be released alongside the 3.1 release. -#### Deserializing multiple objects for update +#### Handling saving related instances in model manager classes -**TODO** +An alternative to saving multiple related instances in the serializer is to write custom model manager classes handle creating the correct instances. -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. +For example, suppose we wanted to ensure that `User` instances and `Profile` instances are always created together as a pair. We might write a custom manager class that looks something like this: -This allows you to write views that update or create multiple items when a `PUT` request is made. + class UserManager(models.Manager): + ... - # 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 - serializer.save() # `.save()` will be called on each updated or newly created instance. + def create(self, username, email, is_premium_member=False, has_support_contract=False): + user = User(username=username, email=email) + user.save() + profile = Profile( + user=user, + is_premium_member=is_premium_member, + has_support_contract=has_support_contract + ) + profile.save() + return user -By default bulk updates will be limited to updating instances that already exist in the provided queryset. +This manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our `.create()` method on the serializer class can now be re-written to use the new manager method. -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. + def create(self, validated_data): + return User.objects.create( + username=validated_data['username'], + email=validated_data['email'] + is_premium_member=validated_data['profile']['is_premium_member'] + has_support_contract=validated_data['profile']['has_support_contract'] + ) - 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`. +For more details on this approach see the Django documentation on [model managers](model-managers), and [this blogpost on using model and manger classes](encapsulation-blogpost). -Passing `allow_add_remove=True` ensures that any update operations will completely overwrite the existing queryset, rather than simply updating existing objects. +## 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 + +The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the [ListSerializer](#ListSerializer) documentation below. ## Including extra context @@ -399,7 +429,7 @@ By default, all the model fields on the class will be mapped to a corresponding Any relationships such as foreign keys on the model will be mapped to `PrimaryKeyRelatedField`. Reverse relationships are not included by default unless explicitly included as described below. -#### Inspecting the generated `ModelSerializer` class. +#### Inspecting a `ModelSerializer` Serializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with `ModelSerializers` where you want to determine what set of fields and validators are being automatically created for you. @@ -607,7 +637,7 @@ For example: class Meta: list_serializer_class = CustomListSerializer -#### Customizing `.create()` for multiple objects. +#### Customizing multiple create The default implementation for multiple object creation is to simply call `.create()` for each item in the list. If you want to customize this behavior, you'll need to customize the `.create()` method on `ListSerializer` class that is used when `many=True` is passed. @@ -623,7 +653,7 @@ For example: class Meta: list_serializer_class = BookListSerializer -#### Customizing `.update()` for multiple objects. +#### Customizing multiple update By default the `ListSerializer` class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous. @@ -663,6 +693,8 @@ Here's an example of how you might choose to implement multiple updates: class Meta: list_serializer_class = BookListSerializer +It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the `allow_add_remove` behavior that was present in REST framework 2. + --- # BaseSerializer @@ -687,7 +719,7 @@ Because this class provides the same interface as the `Serializer` class, you ca The only difference you'll notice when doing so is the `BaseSerializer` classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input. -##### Read-only `BaseSerializer` classes. +##### Read-only `BaseSerializer` classes To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model: @@ -721,7 +753,7 @@ Or use it to serialize multiple instances: serializer = HighScoreSerializer(queryset, many=True) return Response(serializer.data) -##### Read-write `BaseSerializer` classes. +##### Read-write `BaseSerializer` classes To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `ValidationError` if the supplied data is in an incorrect format. @@ -766,7 +798,7 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd def create(self, validated_data): return HighScore.objects.create(**validated_data) -#### Creating new generic serializers with `BaseSerializer`. +#### Creating new base classes The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends. @@ -905,6 +937,8 @@ The [django-rest-framework-hstore][django-rest-framework-hstore] package provide [cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion [relations]: relations.md +[model-managers]: https://docs.djangoproject.com/en/dev/topics/db/managers/ +[encapsulation-blogpost]: http://www.dabapps.com/blog/django-models-and-encapsulation/ [mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine [django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis [django-rest-framework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore -- cgit v1.2.3 From 8e549a76ea0ff6b44e1dcf08ba733a5fbfc004ed Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 28 Nov 2014 14:26:03 +0000 Subject: Add 2.x notes and links --- docs/api-guide/fields.md | 6 ++++++ docs/api-guide/generic-views.md | 6 ++++++ docs/api-guide/metadata.md | 6 ++++++ docs/api-guide/relations.md | 6 ++++++ docs/api-guide/requests.md | 6 ++++++ docs/api-guide/serializers.md | 6 ++++++ docs/api-guide/validators.md | 6 ++++++ 7 files changed, 42 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index ca551540..391a52e5 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -1,5 +1,11 @@ source: fields.py +--- + +**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. + +--- + # 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. diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 8c1b7dc9..f5bbdfdd 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -1,6 +1,12 @@ source: mixins.py generics.py +--- + +**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. + +--- + # Generic views > Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself. diff --git a/docs/api-guide/metadata.md b/docs/api-guide/metadata.md index c3f036b7..c3e51148 100644 --- a/docs/api-guide/metadata.md +++ b/docs/api-guide/metadata.md @@ -1,5 +1,11 @@ +--- + +**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. + +--- + # Metadata > [The `OPTIONS`] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 17009bbc..a79b6ea5 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -1,5 +1,11 @@ source: relations.py +--- + +**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. + +--- + # Serializer relations > Bad programmers worry about the code. diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md index 433d666c..77000ffa 100644 --- a/docs/api-guide/requests.md +++ b/docs/api-guide/requests.md @@ -1,5 +1,11 @@ source: request.py +--- + +**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. + +--- + # Requests > If you're doing REST-based web service stuff ... you should ignore request.POST. diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index cd076b4f..4d6c491f 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -1,5 +1,11 @@ source: serializers.py +--- + +**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. + +--- + # Serializers > Expanding the usefulness of the serializers is something that we would diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index ac2f3248..f087e191 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -1,5 +1,11 @@ +--- + +**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. + +--- + # Validators > Validators can be useful for re-using validation logic between different types of fields. -- cgit v1.2.3 From 9ba29a88d6674d65bf5e8438eba2a072f0d44bf1 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 28 Nov 2014 14:43:33 +0000 Subject: Finalizing 3.0 release notes --- docs/api-guide/serializers.md | 38 +++++++++++++------------------------- 1 file changed, 13 insertions(+), 25 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 4d6c491f..0ee80d53 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -567,21 +567,22 @@ There needs to be a way of determining which views should be used for hyperlinki 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 a field on the model. For example: +You can override a URL field view name and lookup field by using either, or both of, the `view_name` and `lookup_field` options in the `extra_field_kwargs` setting, like so: class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Account - fields = ('url', 'account_name', 'users', 'created') - lookup_field = 'slug' - -Note that the `lookup_field` will be used as the default on *all* hyperlinked fields, including both the URL identity, and any hyperlinked relationships. + fields = ('account_url', 'account_name', 'users', 'created') + extra_field_kwargs = { + 'url': {'view_name': 'accounts', 'lookup_field': 'account_name'} + 'users': {'lookup_field': 'username'} + } -For more specific requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example: +Alternatively you can set the fields on the serializer explicitly. For example: class AccountSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( - view_name='account-detail', + view_name='accounts', lookup_field='slug' ) users = serializers.HyperlinkedRelatedField( @@ -595,28 +596,15 @@ For more specific requirements such as specifying a different lookup for each fi model = Account fields = ('url', 'account_name', 'users', 'created') -## Overriding the URL field behavior - -The name of the URL field defaults to 'url'. You can override this globally, by using the `URL_FIELD_NAME` setting. - -You can also override this on a per-serializer basis by using the `url_field_name` option on the serializer, like so: +--- - class AccountSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = Account - fields = ('account_url', 'account_name', 'users', 'created') - url_field_name = 'account_url' +**Tip**: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the `repr` of a `HyperlinkedModelSerializer` instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too. -**Note**: The generic view implementations normally generate a `Location` header in response to successful `POST` requests. Serializers using `url_field_name` option will not have this header automatically included by the view. If you need to do so you will ned to also override the view's `get_success_headers()` method. +--- -You can also override the URL field's view name and lookup field without overriding the field explicitly, by using the `view_name` and `lookup_field` options, like so: +## Changing the URL field name - class AccountSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = Account - fields = ('account_url', 'account_name', 'users', 'created') - view_name = 'account_detail' - lookup_field='account_name' +The name of the URL field defaults to 'url'. You can override this globally, by using the `URL_FIELD_NAME` setting. --- -- cgit v1.2.3 From 08c727add37790b5a556db3fff762f4a27a5c660 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 28 Nov 2014 15:55:02 +0000 Subject: @api_view defaults to allowing GET --- docs/api-guide/views.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md index 31c62682..291fe737 100644 --- a/docs/api-guide/views.md +++ b/docs/api-guide/views.md @@ -127,19 +127,26 @@ REST framework also allows you to work with regular function based views. It pr ## @api_view() -**Signature:** `@api_view(http_method_names)` +**Signature:** `@api_view(http_method_names=['GET'])` -The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: +The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: from rest_framework.decorators import api_view - @api_view(['GET']) + @api_view() def hello_world(request): return Response({"message": "Hello, world!"}) - This view will use the default renderers, parsers, authentication classes etc specified in the [settings]. +By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so: + + @api_view(['GET', 'POST']) + def hello_world(request): + if request.method == 'POST': + return Response({"message": "Got some data!", "data": request.data}) + return Response({"message": "Hello, world!"}) + ## API policy decorators To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle][throttling] to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes: -- cgit v1.2.3 From 731c8421afe3093a78cdabb9c3cc28fa52cd1c8e Mon Sep 17 00:00:00 2001 From: José Padilla Date: Sat, 29 Nov 2014 14:43:05 -0400 Subject: Remove YAML support from core --- docs/api-guide/parsers.md | 24 ++++++++---------------- docs/api-guide/renderers.md | 42 +++++------------------------------------- docs/api-guide/settings.md | 4 ++-- docs/api-guide/testing.md | 4 ++-- 4 files changed, 17 insertions(+), 57 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 73e3a705..1e134c77 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -26,26 +26,26 @@ As an example, if you are sending `json` encoded data using jQuery with the [.aj ## Setting the parsers -The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow requests with `YAML` content. +The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow requests with `JSON` content. REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( - 'rest_framework.parsers.YAMLParser', + 'rest_framework.parsers.JSONParser', ) } You can also set the parsers used for an individual view, or viewset, using the `APIView` class based views. - from rest_framework.parsers import YAMLParser + from rest_framework.parsers import JSONParser from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): """ - A view that can accept POST requests with YAML content. + A view that can accept POST requests with JSON content. """ - parser_classes = (YAMLParser,) + parser_classes = (JSONParser,) def post(self, request, format=None): return Response({'received data': request.data}) @@ -53,10 +53,10 @@ using the `APIView` class based views. Or, if you're using the `@api_view` decorator with function based views. @api_view(['POST']) - @parser_classes((YAMLParser,)) + @parser_classes((JSONParser,)) def example_view(request, format=None): """ - A view that can accept POST requests with YAML content. + A view that can accept POST requests with JSON content. """ return Response({'received data': request.data}) @@ -70,14 +70,6 @@ Parses `JSON` request content. **.media_type**: `application/json` -## YAMLParser - -Parses `YAML` request content. - -Requires the `pyyaml` package to be installed. - -**.media_type**: `application/yaml` - ## XMLParser Parses REST framework's default style of `XML` request content. @@ -161,7 +153,7 @@ By default this will include the following keys: `view`, `request`, `args`, `kwa ## Example -The following is an example plaintext parser that will populate the `request.data` property with a string representing the body of the request. +The following is an example plaintext parser that will populate the `request.data` property with a string representing the body of the request. class PlainTextParser(BaseParser): """ diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 035ec1d2..aa8da088 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -18,11 +18,11 @@ For more information see the documentation on [content negotiation][conneg]. ## Setting the renderers -The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would use `YAML` as the main media type and also include the self describing API. +The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would use `JSON` as the main media type and also include the self describing API. REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( - 'rest_framework.renderers.YAMLRenderer', + 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ) } @@ -31,15 +31,15 @@ You can also set the renderers used for an individual view, or viewset, using the `APIView` class based views. from django.contrib.auth.models import User - from rest_framework.renderers import JSONRenderer, YAMLRenderer + from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.views import APIView class UserCountView(APIView): """ - A view that returns the count of active users, in JSON or YAML. + A view that returns the count of active users in JSON. """ - renderer_classes = (JSONRenderer, YAMLRenderer) + renderer_classes = (JSONRenderer, ) def get(self, request, format=None): user_count = User.objects.filter(active=True).count() @@ -113,38 +113,6 @@ The `jsonp` approach is essentially a browser hack, and is [only appropriate for **.charset**: `utf-8` -## YAMLRenderer - -Renders the request data into `YAML`. - -Requires the `pyyaml` package to be installed. - -Note that non-ascii characters will be rendered using `\uXXXX` character escape. For example: - - unicode black star: "\u2605" - -**.media_type**: `application/yaml` - -**.format**: `'.yaml'` - -**.charset**: `utf-8` - -## UnicodeYAMLRenderer - -Renders the request data into `YAML`. - -Requires the `pyyaml` package to be installed. - -Note that non-ascii characters will not be character escaped. For example: - - unicode black star: ★ - -**.media_type**: `application/yaml` - -**.format**: `'.yaml'` - -**.charset**: `utf-8` - ## XMLRenderer Renders REST framework's default style of `XML` response content. diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 9005511b..623d89fb 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -12,10 +12,10 @@ For example your project's `settings.py` file might include something like this: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( - 'rest_framework.renderers.YAMLRenderer', + 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( - 'rest_framework.parsers.YAMLParser', + 'rest_framework.parsers.JSONParser', ) } diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index d059fdab..cd8c7820 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -255,14 +255,14 @@ The default format used to make test requests may be set using the `TEST_REQUEST If you need to test requests using something other than multipart or json requests, you can do so by setting the `TEST_REQUEST_RENDERER_CLASSES` setting. -For example, to add support for using `format='yaml'` in test requests, you might have something like this in your `settings.py` file. +For example, to add support for using `format='html'` in test requests, you might have something like this in your `settings.py` file. REST_FRAMEWORK = { ... 'TEST_REQUEST_RENDERER_CLASSES': ( 'rest_framework.renderers.MultiPartRenderer', 'rest_framework.renderers.JSONRenderer', - 'rest_framework.renderers.YAMLRenderer' + 'rest_framework.renderers.TemplateHTMLRenderer' ) } -- cgit v1.2.3 From fe745b96163282e492f17a6b003418b81350333f Mon Sep 17 00:00:00 2001 From: José Padilla Date: Sat, 29 Nov 2014 14:55:33 -0400 Subject: Remove JSONP support from core --- docs/api-guide/renderers.md | 28 ++-------------------------- 1 file changed, 2 insertions(+), 26 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 035ec1d2..a77b9db2 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -49,10 +49,10 @@ using the `APIView` class based views. Or, if you're using the `@api_view` decorator with function based views. @api_view(['GET']) - @renderer_classes((JSONRenderer, JSONPRenderer)) + @renderer_classes((JSONRenderer,)) def user_count_view(request, format=None): """ - A view that returns the count of active users, in JSON or JSONp. + A view that returns the count of active users in JSON. """ user_count = User.objects.filter(active=True).count() content = {'user_count': user_count} @@ -93,26 +93,6 @@ The default JSON encoding style can be altered using the `UNICODE_JSON` and `COM **.charset**: `None` -## JSONPRenderer - -Renders the request data into `JSONP`. The `JSONP` media type provides a mechanism of allowing cross-domain AJAX requests, by wrapping a `JSON` response in a javascript callback. - -The javascript callback function must be set by the client including a `callback` URL query parameter. For example `http://example.com/api/users?callback=jsonpCallback`. If the callback function is not explicitly set by the client it will default to `'callback'`. - ---- - -**Warning**: If you require cross-domain AJAX requests, you should almost certainly be using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details. - -The `jsonp` approach is essentially a browser hack, and is [only appropriate for globally readable API endpoints][jsonp-security], where `GET` requests are unauthenticated and do not require any user permissions. - ---- - -**.media_type**: `application/javascript` - -**.format**: `'.jsonp'` - -**.charset**: `utf-8` - ## YAMLRenderer Renders the request data into `YAML`. @@ -433,10 +413,6 @@ Comma-separated values are a plain-text tabular data format, that can be easily [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process [conneg]: content-negotiation.md [browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers -[rfc4627]: http://www.ietf.org/rfc/rfc4627.txt -[cors]: http://www.w3.org/TR/cors/ -[cors-docs]: ../topics/ajax-csrf-cors.md -[jsonp-security]: http://stackoverflow.com/questions/613962/is-jsonp-safe-to-use [testing]: testing.md [HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas [quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven -- cgit v1.2.3 From 7f9dc736728baf92a3198a7f90bd302fff240373 Mon Sep 17 00:00:00 2001 From: José Padilla Date: Sat, 29 Nov 2014 14:50:51 -0400 Subject: Remove XML support from core --- docs/api-guide/parsers.md | 14 +------------- docs/api-guide/renderers.md | 14 -------------- 2 files changed, 1 insertion(+), 27 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 73e3a705..32819146 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -78,18 +78,6 @@ Requires the `pyyaml` package to be installed. **.media_type**: `application/yaml` -## XMLParser - -Parses REST framework's default style of `XML` request content. - -Note that the `XML` markup language is typically used as the base language for more strictly defined domain-specific languages, such as `RSS`, `Atom`, and `XHTML`. - -If you are considering using `XML` for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type. - -Requires the `defusedxml` package to be installed. - -**.media_type**: `application/xml` - ## FormParser Parses HTML form content. `request.data` will be populated with a `QueryDict` of data. @@ -161,7 +149,7 @@ By default this will include the following keys: `view`, `request`, `args`, `kwa ## Example -The following is an example plaintext parser that will populate the `request.data` property with a string representing the body of the request. +The following is an example plaintext parser that will populate the `request.data` property with a string representing the body of the request. class PlainTextParser(BaseParser): """ diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 035ec1d2..47bf2e60 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -145,20 +145,6 @@ Note that non-ascii characters will not be character escaped. For example: **.charset**: `utf-8` -## XMLRenderer - -Renders REST framework's default style of `XML` response content. - -Note that the `XML` markup language is used typically used as the base language for more strictly defined domain-specific languages, such as `RSS`, `Atom`, and `XHTML`. - -If you are considering using `XML` for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type. - -**.media_type**: `application/xml` - -**.format**: `'.xml'` - -**.charset**: `utf-8` - ## TemplateHTMLRenderer Renders data to HTML, using Django's standard template rendering. -- cgit v1.2.3 From 555c450497e96bf8fed82fc76e70adf907c5c409 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 1 Dec 2014 14:46:47 +0000 Subject: Add missing 'validators.py' link. Closes #2166. --- docs/api-guide/validators.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index f087e191..8f5a8929 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -1,4 +1,4 @@ - +source: validators.py --- -- cgit v1.2.3 From f4fc4670ca491eabd5bcdfcef382d8373dd5e380 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 2 Dec 2014 08:53:36 +0000 Subject: Promote 'many_init' to public API. Closes #2152. --- docs/api-guide/serializers.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 0ee80d53..4c78473e 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -689,6 +689,21 @@ Here's an example of how you might choose to implement multiple updates: It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the `allow_add_remove` behavior that was present in REST framework 2. +#### Customizing ListSerializer initialization + +When a serializer with `many=True` is instantiated, we need to determine which arguments and keyword arguments should be passed to the `.__init__()` method for both the child `Serializer` class, and for the parent `ListSerializer` class. + +The default implementation is to pass all arguments to both classes, except for `validators`, and any custom keyword arguments, both of which are assumed to be intended for the child serializer class. + +Occasionally you might need to explicitly specify how the child and parent classes should be instantiated when `many=True` is passed. You can do so by using the `many_init` class method. + + @classmethod + def many_init(cls, *args, **kwargs): + # Instantiate the child serializer. + kwargs['child'] = cls() + # Instantiate the parent list serializer. + return CustomListSerializer(*args, **kwargs) + --- # BaseSerializer -- cgit v1.2.3 From 6ac79b822325784ad145ff0ad064127750c4f7e0 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 2 Dec 2014 09:19:59 +0000 Subject: Document Field.fail(). Closes #2147. --- docs/api-guide/fields.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 391a52e5..aa5cc84e 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -453,7 +453,7 @@ If you want to create a custom field, you'll need to subclass `Field` and then o The `.to_representation()` method is called to convert the initial datatype into a primitive, serializable datatype. -The `to_internal_value()` method is called to restore a primitive datatype into its internal python representation. +The `to_internal_value()` method is called to restore a primitive datatype into its internal python representation. This method should raise a `serializer.ValidationError` if the data is invalid. Note that the `WritableField` class that was present in version 2.x no longer exists. You should subclass `Field` and override `to_internal_value()` if the field supports data input. @@ -498,6 +498,53 @@ As an example, let's create a field that can be used represent the class name of """ return obj.__class__.__name__ +#### Raising validation errors + +Our `ColorField` class above currently does not perform any data validation. +To indicate invalid data, we should raise a `serializers.ValidationError`, like so: + + def to_internal_value(self, data): + if not isinstance(data, six.text_type): + msg = 'Incorrect type. Expected a string, but got %s' + raise ValidationError(msg % type(data).__name__) + + if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data): + raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.') + + data = data.strip('rgb(').rstrip(')') + red, green, blue = [int(col) for col in data.split(',')] + + if any([col > 255 or col < 0 for col in (red, green, blue)]): + raise ValidationError('Value out of range. Must be between 0 and 255.') + + return Color(red, green, blue) + +The `.fail()` method is a shortcut for raising `ValidationError` that takes a message string from the `error_messages` dictionary. For example: + + default_error_messages = { + 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}', + 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.', + 'out_of_range': 'Value out of range. Must be between 0 and 255.' + } + + def to_internal_value(self, data): + if not isinstance(data, six.text_type): + msg = 'Incorrect type. Expected a string, but got %s' + self.fail('incorrect_type', input_type=type(data).__name__) + + if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data): + self.fail('incorrect_format') + + data = data.strip('rgb(').rstrip(')') + red, green, blue = [int(col) for col in data.split(',')] + + if any([col > 255 or col < 0 for col in (red, green, blue)]): + self.fail('out_of_range') + + return Color(red, green, blue) + +This style keeps you error messages more cleanly separated from your code, and should be preferred. + # Third party packages The following third party packages are also available. -- cgit v1.2.3 From 84cff98fbf72355cb5e8359aa1c9b5568c289cbf Mon Sep 17 00:00:00 2001 From: David Ray Date: Tue, 2 Dec 2014 09:46:43 -0500 Subject: fix typo --- docs/api-guide/serializers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 4c78473e..a011bb52 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -96,7 +96,7 @@ If we want to be able to return complete object instances based on the validated If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if `Comment` was a Django model, the methods might look like this: def create(self, validated_data): - return Comment.objcts.create(**validated_data) + return Comment.objects.create(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) -- cgit v1.2.3 From 5ad22aea605f888e06186d907674669c46a611ef Mon Sep 17 00:00:00 2001 From: Matías Lang Date: Tue, 2 Dec 2014 12:23:25 -0300 Subject: Updated serializers documentation There was an error in the docs: the field extra_field_kwargs of the serializer's Meta doesn't work. The field must be extra_kwargs instead.--- docs/api-guide/serializers.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index a011bb52..1779c863 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -567,13 +567,13 @@ There needs to be a way of determining which views should be used for hyperlinki 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 override a URL field view name and lookup field by using either, or both of, the `view_name` and `lookup_field` options in the `extra_field_kwargs` setting, like so: +You can override a URL field view name and lookup field by using either, or both of, the `view_name` and `lookup_field` options in the `extra_kwargs` setting, like so: class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Account fields = ('account_url', 'account_name', 'users', 'created') - extra_field_kwargs = { + extra_kwargs = { 'url': {'view_name': 'accounts', 'lookup_field': 'account_name'} 'users': {'lookup_field': 'username'} } -- cgit v1.2.3 From 71e1a3942e7945fe4d8da4c44b4ba2100a2c67de Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Thu, 4 Dec 2014 12:15:14 +0100 Subject: Initial link from Serializers to Validators --- docs/api-guide/serializers.md | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 1779c863..69fc1857 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -104,7 +104,7 @@ If your object instances correspond to Django models you'll also want to ensure instance.created = validated_data.get('created', instance.created) instance.save() return instance - + Now when deserializing data, we can call `.save()` to return an object instance, based on the validated data. comment = serializer.save() @@ -113,7 +113,7 @@ Calling `.save()` will either create a new instance, or update an existing insta # .save() will create a new instance. serializer = CommentSerializer(data=data) - + # .save() will update the existing `comment` instance. serializer = CommentSerializer(comment, data=data) @@ -140,7 +140,7 @@ For example: class ContactForm(serializers.Serializer): email = serializers.EmailField() message = serializers.CharField() - + def save(self): email = self.validated_data['email'] message = self.validated_data['message'] @@ -230,7 +230,7 @@ Serializer classes can also include reusable validators that are applied to the name = serializers.CharField() room_number = serializers.IntegerField(choices=[101, 102, 103, 201]) date = serializers.DateField() - + class Meta: # Each room only has one event per day. validators = UniqueTogetherValidator( @@ -448,7 +448,7 @@ To do so, open the Django shell, using `python manage.py shell`, then import the id = IntegerField(label='ID', read_only=True) name = CharField(allow_blank=True, max_length=100, required=False) owner = PrimaryKeyRelatedField(queryset=User.objects.all()) - + ## 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`. @@ -505,6 +505,19 @@ This option should be a list or tuple of field names, and is declared as follows 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. +--- + +**Note**: There is a special-case where a read-only field is part of a `unique_together` constraint at the model level. Here you **must** specify the field explicitly and provide a valid default value. + +A common example of this is a read-only relation to currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so: + + user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) + +Please review the [Validators Documentation](/api-guide/validators/) for details on the [UniqueTogetherValidator](/api-guide/validators/#uniquetogethervalidator) and [CurrentUserDefault](/api-guide/validators/#currentuserdefault) classes. + +--- + + ## Specifying additional keyword arguments for fields. There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the `extra_kwargs` option. Similarly to `read_only_fields` this means you do not need to explicitly declare the field on the serializer. @@ -516,7 +529,7 @@ This option is a dictionary, mapping field names to a dictionary of keyword argu model = User fields = ('email', 'username', 'password') extra_kwargs = {'password': {'write_only': True}} - + def create(self, validated_data): user = User( email=validated_data['email'], @@ -656,7 +669,7 @@ To support multiple updates you'll need to do so explicitly. When writing your m * How do you determine which instance should be updated for each item in the list of data? * How should insertions be handled? Are they invalid, or do they create new objects? * How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid? -* How should ordering be handled? Does changing the position of two items imply any state change or is it ignored? +* How should ordering be handled? Does changing the position of two items imply any state change or is it ignored? Here's an example of how you might choose to implement multiple updates: -- cgit v1.2.3 From 6ee361332b09f148f86149a7d9a6220bd61966e8 Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Thu, 4 Dec 2014 14:15:01 +0100 Subject: Add missing definite article --- docs/api-guide/serializers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 69fc1857..79db275f 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -509,7 +509,7 @@ Model fields which have `editable=False` set, and `AutoField` fields will be set **Note**: There is a special-case where a read-only field is part of a `unique_together` constraint at the model level. Here you **must** specify the field explicitly and provide a valid default value. -A common example of this is a read-only relation to currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so: +A common example of this is a read-only relation to the currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so: user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) -- cgit v1.2.3 From 9fb1b396db751234a531dabacb6758ac2645776c Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 5 Dec 2014 13:07:31 +0000 Subject: user in example should have been instance. Closees #2191. --- docs/api-guide/serializers.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 1779c863..ab44839f 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -326,9 +326,9 @@ Here's an example for an `update()` method on our previous `UserSerializer` clas # would need to be handled. profile = instance.profile - user.username = validated_data.get('username', instance.username) - user.email = validated_data.get('email', instance.email) - user.save() + instance.username = validated_data.get('username', instance.username) + instance.email = validated_data.get('email', instance.email) + instance.save() profile.is_premium_member = profile_data.get( 'is_premium_member', @@ -340,7 +340,7 @@ Here's an example for an `update()` method on our previous `UserSerializer` clas ) profile.save() - return user + return instance Because the behavior of nested creates and updates can be ambiguous, and may require complex dependancies between related models, REST framework 3 requires you to always write these methods explicitly. The default `ModelSerializer` `.create()` and `.update()` methods do not include support for writable nested representations. -- cgit v1.2.3 From 59b2ad542580eb93243c4403ded4c2b4dc8518c2 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 5 Dec 2014 13:23:14 +0000 Subject: Minor docs tweaks --- docs/api-guide/serializers.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 1f97614d..5fe6b4c2 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -507,9 +507,11 @@ Model fields which have `editable=False` set, and `AutoField` fields will be set --- -**Note**: There is a special-case where a read-only field is part of a `unique_together` constraint at the model level. Here you **must** specify the field explicitly and provide a valid default value. +**Note**: There is a special-case where a read-only field is part of a `unique_together` constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user. -A common example of this is a read-only relation to the currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so: +The right way to deal with this is to specify the field explicitly on the serializer, providing both the `read_only=True` and `default=…` keyword arguments. + +One example of this is a read-only relation to the currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so: user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) -- cgit v1.2.3 From 9b468fba60def77144949628211aac95c6316c70 Mon Sep 17 00:00:00 2001 From: Mark Henwood Date: Sun, 7 Dec 2014 11:57:07 +0000 Subject: Amend ViewSet docs to warn of potential problem I went through this exact problem and so thought the docs might benefit from a small hint at the appropriate point. --- docs/api-guide/viewsets.md | 3 +++ 1 file changed, 3 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 28186c64..3e37cef8 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -201,6 +201,8 @@ Note that you can use any of the standard attributes or method overrides provide def get_queryset(self): return self.request.user.accounts.all() +Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the base_name of your Model automatically, and so you you will have to specify the `base_name` kwarg as part of your [router registration][routers]. + 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 @@ -243,3 +245,4 @@ To create a base viewset class that provides `create`, `list` and `retrieve` ope 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 +[routers]: routers.md -- cgit v1.2.3 From f5b783af617f507efbc0d5ede0d27bd6be903d63 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 9 Dec 2014 14:21:31 +0000 Subject: allow_blank in ChoiceField. Refs #2239. --- docs/api-guide/fields.md | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index aa5cc84e..e4ef1d4a 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -310,6 +310,9 @@ Used by `ModelSerializer` to automatically generate fields if the corresponding **Signature:** `ChoiceField(choices)` - `choices` - A list of valid values, or a list of `(key, display_name)` tuples. +- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. + +Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices. ## MultipleChoiceField @@ -318,6 +321,9 @@ A field that can accept a set of zero, one or many values, chosen from a limited **Signature:** `MultipleChoiceField(choices)` - `choices` - A list of valid values, or a list of `(key, display_name)` tuples. +- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. + +As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices. --- -- cgit v1.2.3 From 00da2414827987e9934ebe7bf2f9a3afea1cdb13 Mon Sep 17 00:00:00 2001 From: Jeff Fein-Worton Date: Fri, 12 Dec 2014 22:14:22 -0800 Subject: documentation typo base-name -> base_name--- docs/api-guide/routers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 080230fa..929a1710 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -41,7 +41,7 @@ The example above would generate the following URL patterns: **Note**: The `base_name` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part. -Typically you won't *need* to specify the `base-name` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this: +Typically you won't *need* to specify the `base_name` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this: 'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute. -- cgit v1.2.3 From 2d470eef809b119c8c72009c81d652ddbf895e0b Mon Sep 17 00:00:00 2001 From: Brian Jacobel Date: Sat, 13 Dec 2014 14:47:11 -0500 Subject: Change serializers.Field to serializers.ReadOnlyField for 3.x compatibility Using this code snippet as-is on DRF 3.0.1 results in a NotImplementedError being raised for to_representation due to 3.0's changed behavior with serializers.Field. The code snippet should be updated to use serializers.ReadOnlyField instead. Further discussion here: https://groups.google.com/forum/?fromgroups=#!topic/django-rest-framework/aX8mLT_v3yc --- docs/api-guide/pagination.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 9b7086c5..83429292 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -128,7 +128,7 @@ For example, to nest a pair of links labelled 'prev' and 'next', and set the nam class CustomPaginationSerializer(pagination.BasePaginationSerializer): links = LinksSerializer(source='*') # Takes the page object as the source - total_results = serializers.Field(source='paginator.count') + total_results = serializers.ReadOnlyField(source='paginator.count') results_field = 'objects' -- cgit v1.2.3 From 478c8d724b846b370c897548f8ee89f1128e12c9 Mon Sep 17 00:00:00 2001 From: José Padilla Date: Sun, 14 Dec 2014 10:16:52 -0400 Subject: Update docs --- docs/api-guide/exceptions.md | 4 ++-- docs/api-guide/settings.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 467ad970..31a8431b 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -51,10 +51,10 @@ In order to alter the style of the response, you could write the following custo from rest_framework.views import exception_handler - def custom_exception_handler(exc): + def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. - response = exception_handler(exc) + response = exception_handler(exc, context) # Now add the HTTP status code to the response. if response is not None: diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 9005511b..2c4f8423 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -393,7 +393,7 @@ This setting can be changed to support error responses other than the default `{ This should be a function with the following signature: - exception_handler(exc) + exception_handler(exc, context) * `exc`: The exception. -- cgit v1.2.3 From 56c09cc1f2bdd22d1a5465ad618a86b04a8b1d6a Mon Sep 17 00:00:00 2001 From: Jason Spafford Date: Mon, 15 Dec 2014 02:41:39 -0800 Subject: Doc typo --- docs/api-guide/permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index f068f0f7..ddcefadb 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -104,7 +104,7 @@ This permission is suitable if you want your API to only be accessible to regist The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff` is `True` in which case permission will be allowed. -This permission is suitable is you want your API to only be accessible to a subset of trusted administrators. +This permission is suitable if you want your API to only be accessible to a subset of trusted administrators. ## IsAuthenticatedOrReadOnly -- cgit v1.2.3 From d71ef9c6d810115bfe0de6327139c6886932cdb8 Mon Sep 17 00:00:00 2001 From: José Padilla Date: Mon, 15 Dec 2014 21:48:31 -0400 Subject: Closes #2281 --- docs/api-guide/relations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index a79b6ea5..e56db229 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -397,7 +397,7 @@ We could define a custom field that could be used to serialize tagged instances, return 'Note: ' + value.text raise Exception('Unexpected type of tagged object') -If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_native()` method: +If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_representation()` method: def to_representation(self, value): """ -- cgit v1.2.3 From 6e51e4f5cdec4f4580360a487d7bf5ebdef08709 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 16 Dec 2014 15:34:19 +0000 Subject: Versioning first pass --- docs/api-guide/versioning.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 docs/api-guide/versioning.md (limited to 'docs/api-guide') diff --git a/docs/api-guide/versioning.md b/docs/api-guide/versioning.md new file mode 100644 index 00000000..df814894 --- /dev/null +++ b/docs/api-guide/versioning.md @@ -0,0 +1,9 @@ +source: versioning.py + +# Versioning + +> Versioning an interface is just a "polite" way to kill deployed clients. +> +> — [Roy Fielding][cite]. + +[cite]: http://www.slideshare.net/evolve_conference/201308-fielding-evolve/31 \ No newline at end of file -- cgit v1.2.3 From 05a6eaec8aebdca2248b9e1069a15769fd85a480 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Dec 2014 12:41:46 +0000 Subject: More docs, plus 'ALLOWED_VERSIONS' setting. --- docs/api-guide/exceptions.md | 16 ++++ docs/api-guide/settings.md | 22 +++++ docs/api-guide/versioning.md | 195 ++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 232 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 31a8431b..50bd14dd 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -128,6 +128,14 @@ Raised when an authenticated request fails the permission checks. By default this exception results in a response with the HTTP status code "403 Forbidden". +## NotFound + +**Signature:** `NotFound(detail=None)` + +Raised when a resource does not exists at the given URL. This exception is equivalent to the standard `Http404` Django exception. + +By default this exception results in a response with the HTTP status code "404 Not Found". + ## MethodNotAllowed **Signature:** `MethodNotAllowed(method, detail=None)` @@ -136,6 +144,14 @@ Raised when an incoming request occurs that does not map to a handler method on By default this exception results in a response with the HTTP status code "405 Method Not Allowed". +## NotAcceptable + +**Signature:** `NotAcceptable(detail=None)` + +Raised when an incoming request occurs with an `Accept` header that cannot be satisfied by any of the available renderers. + +By default this exception results in a response with the HTTP status code "406 Not Acceptable". + ## UnsupportedMediaType **Signature:** `UnsupportedMediaType(media_type, detail=None)` diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 9efeda7f..5af429d1 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -166,6 +166,28 @@ Default: `ordering` --- +## Versioning settings + +#### DEFAULT_VERSION + +The value that should be used for `request.version` when no versioning information is present. + +Default: `None` + +#### ALLOWED_VERSIONS + +If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set. + +Default: `None` + +#### VERSION_PARAMETER + +The string that should used for any versioning parameters, such as in the media type or URL query parameters. + +Default: `'version'` + +--- + ## Authentication settings *The following settings control the behavior of unauthenticated requests.* diff --git a/docs/api-guide/versioning.md b/docs/api-guide/versioning.md index df814894..92380cc0 100644 --- a/docs/api-guide/versioning.md +++ b/docs/api-guide/versioning.md @@ -6,4 +6,197 @@ source: versioning.py > > — [Roy Fielding][cite]. -[cite]: http://www.slideshare.net/evolve_conference/201308-fielding-evolve/31 \ No newline at end of file +API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes. + +Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers. + +## Versioning with REST framework + +When API versioning is enabled, the `request.version` attribute will contain a string that corresponds to the version requested in the incoming client request. + +By default, versioning is not enabled, and `request.version` will always return `None`. + +#### Varying behavior based on the version + +How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example: + + def get_serializer_class(self): + if self.request.version == 'v1': + return AccountSerializerVersion1 + return AccountSerializer + +#### Reversing URLs for versioned APIs + +The `reverse` function included by REST framework ties in with the versioning scheme. You need to make sure to include the current `request` as a keyword argument, like so. + + reverse('bookings-list', request=request) + +The above function will apply any URL transformations appropriate to the request version. For example: + +* If `NamespacedVersioning` was being used, and the API version was 'v1', then the URL lookup used would be `'v1:bookings-list'`, which might resolve to a URL like `http://example.org/v1/bookings/`. +* If `QueryParameterVersioning` was being used, and the API version was `1.0`, then the returned URL might be something like `http://example.org/bookings/?version=1.0` + +#### Versioned APIs and hyperlinked serializers + +When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer. + + def get(self, request): + queryset = Booking.objects.all() + serializer = BookingsSerializer(queryset, many=True, context={'request': request}) + return Response({'all_bookings': serializer.data}) + +Doing so will allow any returned URLs to include the appropriate versioning. + +## Configuring the versioning scheme + +The versioning scheme is defined by the `DEFAULT_VERSIONING_CLASS` settings key. + + REST_FRAMEWORK = { + 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning' + } + +Unless it is explicitly set, the value for `DEFAULT_VERSIONING_CLASS` will be `None`. In this case the `request.version` attribute will always return `None`. + +You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the `versioning_class` attribute. + + class ProfileList(APIView): + versioning_class = versioning.QueryParameterVersioning + +#### Other versioning settings + +The following settings keys are also used to control versioning: + +* `DEFAULT_VERSION`. The value that should be used for `request.version` when no versioning information is present. Defaults to `None`. +* `ALLOWED_VERSIONS`. If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set. Defaults to `None`. +* `VERSION_PARAMETER`. The string that should used for any versioning parameters, such as in the media type or URL query parameters. Defaults to `'version'`. + +--- + +# API Reference + +## AcceptHeaderVersioning + +This scheme requires the client to specify the version as part of the media type in the `Accept` header. The version is included as a media type parameter, that supplements the main media type. + +Here's an example HTTP request using the accept header versioning style. + + GET /bookings/ HTTP/1.1 + Host: example.com + Accept: application/json; version=1.0 + +In the example request above `request.version` attribute would return the string `'1.0'`. + +Versioning based on accept headers is [generally considered][klabnik-guidelines] as [best practice][heroku-guidelines], although other styles may be suitable depending on your client requirements. + +#### Using accept headers with vendor media types + +Strictly speaking the `json` media type is not specified as [including additional parameters][json-parameters]. If you are building a well-specified public API you might consider using a [vendor media type][vendor-media-type]. To do so, configure your renderers to use a JSON based renderer with a custom media type: + + class BookingsAPIRenderer(JSONRenderer): + media_type = 'application/vnd.megacorp.bookings+json' + +Your client requests would now look like this: + + GET /bookings/ HTTP/1.1 + Host: example.com + Accept: application/vnd.megacorp.bookings+json; version=1.0 + +## URLParameterVersioning + +This scheme requires the client to specify the version as part of the URL path. + + GET /v1/bookings/ HTTP/1.1 + Host: example.com + Accept: application/json + +Your URL conf must include a pattern that matches the version with a `'version'` keyword argument, so that this information is available to the versioning scheme. + + urlpatterns = [ + url( + r'^(?P{v1,v2})/bookings/$', + bookings_list, + name='bookings-list' + ), + url( + r'^(?P{v1,v2})/bookings/(?P[0-9]+)/$', + bookings_detail, + name='bookings-detail' + ) + ] + +## NamespaceVersioning + +To the client, this scheme is the same as `URLParameterVersioning`. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments. + + GET /v1/something/ HTTP/1.1 + Host: example.com + Accept: application/json + +With this scheme the `request.version` attribute is determined based on the `namespace` that matches the incoming request path. + +In the following example we're giving a set of views two different possible URL prefixes, each under a different namespace: + + # bookings/urls.py + urlpatterns = [ + url(r'^$', bookings_list, name='bookings-list'), + url(r'^(?P[0-9]+)/$', bookings_detail, name='bookings-detail') + ] + + # urls.py + urlpatterns = [ + url(r'^v1/bookings/', include('bookings.urls', namespace='v1')), + url(r'^v2/bookings/', include('bookings.urls', namespace='v2')) + ] + +Both `URLParameterVersioning` and `NamespaceVersioning` are reasonable if you just need a simple versioning scheme. The `URLParameterVersioning` approach might be better suitable for small ad-hoc projects, and the `NaemspaceVersioning` is probably easier to manage for larger projects. + +## HostNameVersioning + +The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL. + +For example the following is an HTTP request to the `http://v1.example.com/bookings/` URL: + + GET /bookings/ HTTP/1.1 + Host: v1.example.com + Accept: application/json + +By default this implementation expects the hostname to match this simple regular expression: + + ^([a-zA-Z0-9]+)\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+$ + +Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname. + +The `HostNameVersioning` scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as `127.0.0.1`. There are various online services which you to [access localhost with a custom subdomain][lvh] which you may find helpful in this case. + +Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions. + +## QueryParameterVersioning + +This scheme is a simple style that includes the version as a query parameter in the URL. For example: + + GET /something/?version=0.1 HTTP/1.1 + Host: example.com + Accept: application/json + +--- + +# Custom versioning schemes + +To implement a custom versioning scheme, subclass `BaseVersioning` and override the `.determine_version` method. + +## Example + +The following example uses a custom `X-API-Version` header to determine the requested version. + + class XAPIVersionScheme(versioning.BaseVersioning): + def determine_version(self, request, *args, **kwargs): + return request.META.get('HTTP_X_API_VERSION', None) + +If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the `.reverse()` method on the class. See the source code for examples. + +[cite]: http://www.slideshare.net/evolve_conference/201308-fielding-evolve/31 +[klabnik-guidelines]: http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http#i_want_my_api_to_be_versioned +[heroku-guidelines]: https://github.com/interagent/http-api-design#version-with-accepts-header +[json-parameters]: http://tools.ietf.org/html/rfc4627#section-6 +[vendor-media-type]: http://en.wikipedia.org/wiki/Internet_media_type#Vendor_tree +[lvh]: https://reinteractive.net/posts/199-developing-and-testing-rails-applications-with-subdomains -- cgit v1.2.3 From c6137bbf5aa7ca800e4afc06657e5196b2e0e481 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Dec 2014 14:14:51 +0000 Subject: Serializer API restrictions. --- docs/api-guide/serializers.md | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 5fe6b4c2..137cc9d5 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -240,6 +240,12 @@ Serializer classes can also include reusable validators that are applied to the For more information see the [validators documentation](validators.md). +## Accessing the initial data and instance + +When passing an initial object or queryset to a serializer instance, the object will be made available as `.instance`. If no initial object is passed then the `.instance` attribute will be `None`. + +When passing data to a serializer instance, the unmodified data will be made available as `.initial_data`. If the data keyword argument is not passed then the `.initial_data` attribute will not exist. + ## Partial updates By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the `partial` argument in order to allow partial updates. -- cgit v1.2.3 From 3fff5cb6e0960b7ff8abd9f13a075f1f057de0a7 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Dec 2014 15:13:48 +0000 Subject: Fix empty HTML values when a default is provided. --- docs/api-guide/fields.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index e4ef1d4a..f06db56c 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -112,6 +112,8 @@ Two options are currently used in HTML form generation, `'input_type'` and `'bas A boolean representation. +When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to `False`, even if it has a `default=True` option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input. + Corresponds to `django.db.models.fields.BooleanField`. **Signature:** `BooleanField()` -- cgit v1.2.3 From c9a2ce07037475359712104a8a68624e99bdfeb1 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Dec 2014 16:19:02 +0000 Subject: Expand permissions docs. Closes #2223. --- docs/api-guide/permissions.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index ddcefadb..743ca435 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -10,12 +10,24 @@ Together with [authentication] and [throttling], permissions determine whether a Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the `request.user` and `request.auth` properties to determine if the incoming request should be permitted. +Permissions are used to grant or deny access different classes of users to different parts of the API. + +The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds the `IsAuthenticated` class in REST framework. + +A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the `IsAuthenticatedOrReadOnly` class in REST framework. + ## How permissions are determined Permissions in REST framework are always defined as a list of permission classes. Before running the main body of the view each permission in the list is checked. -If any permission check fails an `exceptions.PermissionDenied` exception will be raised, and the main body of the view will not run. +If any permission check fails an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run. + +When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules: + +* The request was successfully authenticated, but permission was denied. *— An HTTP 403 Forbidden response will be returned.* +* The request was not successfully authenticated, and the highest priority authentication class *does not* use `WWW-Authenticate` headers. *— An HTTP 403 Forbidden response will be returned.* +* The request was not successfully authenticated, and the highest priority authentication class *does* use `WWW-Authenticate` headers. *— An HTTP 401 Unauthorized response, with an appropriate `WWW-Authenticate` header will be returned.* ## Object level permissions -- cgit v1.2.3 From eeb6e340644eba70b2fd41100db34b159ae6f091 Mon Sep 17 00:00:00 2001 From: Tymur Maryokhin Date: Wed, 17 Dec 2014 17:28:11 +0100 Subject: Docs/tutorial import fixes. Refs #2296 --- docs/api-guide/serializers.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 137cc9d5..b9f0e7bc 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -22,11 +22,13 @@ The serializers in REST framework work very similarly to Django's `Form` and `Mo Let's start by creating a simple object we can use for example purposes: + from datetime import datetime + class Comment(object): def __init__(self, email, content, created=None): self.email = email self.content = content - self.created = created or datetime.datetime.now() + self.created = created or datetime.now() comment = Comment(email='leila@example.com', content='foo bar') @@ -61,10 +63,10 @@ At this point we've translated the model instance into Python native datatypes. Deserialization is similar. First we parse a stream into Python native datatypes... - from StringIO import StringIO + from django.utils.six import BytesIO from rest_framework.parsers import JSONParser - stream = StringIO(json) + stream = BytesIO(json) data = JSONParser().parse(stream) ...then we restore those native datatypes into a dictionary of validated data. -- cgit v1.2.3 From 7105c1308e08a756fcb4131168e3187b0bc1ddee Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 18 Dec 2014 15:42:27 +0000 Subject: Add OPTIONS/metadata to docs index --- docs/api-guide/metadata.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/metadata.md b/docs/api-guide/metadata.md index c3e51148..247ae988 100644 --- a/docs/api-guide/metadata.md +++ b/docs/api-guide/metadata.md @@ -1,4 +1,4 @@ - +source: metadata.py --- -- cgit v1.2.3 From 6aa0e307c99d0c17d7c48f2416472c7dbdcbbf8f Mon Sep 17 00:00:00 2001 From: Rahul Date: Fri, 19 Dec 2014 20:31:21 +0530 Subject: Added documentation about url_path parameter for custom actions. --- docs/api-guide/routers.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 61a476b8..63b8b59a 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -68,6 +68,24 @@ The following URL pattern would additionally be generated: * URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'` +If you did not like the default URL generated for your custom action, you could use `url_path` parameter with `@detail_route` or `@list_route` to customize it. + +For example, if you want to change the URL for our custom action to `^users/{pk}/change-password/$`, you could write: + + from myapp.permissions import IsAdminOrIsSelf + from rest_framework.decorators import detail_route + + class UserViewSet(ModelViewSet): + ... + + @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf], url_path='change-password') + def set_password(self, request, pk=None): + ... + +Above example would instead generate following URL pattern: + +* URL pattern: `^users/{pk}/change-password/$` Name: `'user-change-password'` + For more information see the viewset documentation on [marking extra actions for routing][route-decorators]. # API Guide -- cgit v1.2.3 From b4a3e7f64096ea7106ff0d622bdf1c6e2e4e2895 Mon Sep 17 00:00:00 2001 From: Rahul Date: Fri, 19 Dec 2014 21:20:19 +0530 Subject: Updates url_path info per suggestion --- docs/api-guide/routers.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 63b8b59a..87b6f15a 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -68,7 +68,7 @@ The following URL pattern would additionally be generated: * URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'` -If you did not like the default URL generated for your custom action, you could use `url_path` parameter with `@detail_route` or `@list_route` to customize it. +If you do not want to use the default URL generated for your custom action, you can instead use the url_path parameter to customize it. For example, if you want to change the URL for our custom action to `^users/{pk}/change-password/$`, you could write: @@ -82,7 +82,7 @@ For example, if you want to change the URL for our custom action to `^users/{pk} def set_password(self, request, pk=None): ... -Above example would instead generate following URL pattern: +The above example would now generate the following URL pattern: * URL pattern: `^users/{pk}/change-password/$` Name: `'user-change-password'` -- cgit v1.2.3 From 48d15f6ff8a13aafd5b4977c8d1b4b7fe70b4f6a Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 19 Dec 2014 16:58:35 +0000 Subject: Stub out the documentation --- docs/api-guide/serializers.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index b9f0e7bc..4d3dfa31 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -567,6 +567,32 @@ The inner `Meta` class on serializers is not inherited from parent classes by de Typically we would recommend *not* using inheritance on inner Meta classes, but instead declaring all options explicitly. +## Advanced `ModelSerializer` usage + +The ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer. + +#### `.serializer_field_mapping` + +A mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class. + +#### `.serializer_relational_field` + +This property should be the serializer field class, that is used for relational fields by default. For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`. For `HyperlinkedModelSerializer` this defaults to `HyperlinkedRelatedField`. + +#### The build field methods + +#### `build_standard_field(**kwargs)` + +#### `build_relational_field(**kwargs)` + +#### `build_nested_field(**kwargs)` + +#### `build_property_field(**kwargs)` + +#### `build_url_field(**kwargs)` + +#### `build_unknown_field(**kwargs)` + --- # HyperlinkedModelSerializer -- cgit v1.2.3 From 2a1485e00943b8280245d19e1e1f8514b1ef18ea Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 19 Dec 2014 21:32:43 +0000 Subject: Final bits of docs for ModelSerializer fields API --- docs/api-guide/serializers.md | 57 +++++++++++++++++++++++++++++++++---------- 1 file changed, 44 insertions(+), 13 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 4d3dfa31..dcbbd5f2 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -457,7 +457,7 @@ To do so, open the Django shell, using `python manage.py shell`, then import the name = CharField(allow_blank=True, max_length=100, required=False) owner = PrimaryKeyRelatedField(queryset=User.objects.all()) -## Specifying which fields should be included +## Specifying which fields to include 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`. @@ -499,7 +499,7 @@ You can add extra fields to a `ModelSerializer` or override the default fields b Extra fields can correspond to any property or callable on the model. -## Specifying which fields should be read-only +## Specifying read only fields 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 shortcut Meta option, `read_only_fields`. @@ -528,7 +528,7 @@ Please review the [Validators Documentation](/api-guide/validators/) for details --- -## Specifying additional keyword arguments for fields. +## Additional keyword arguments There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the `extra_kwargs` option. Similarly to `read_only_fields` this means you do not need to explicitly declare the field on the serializer. @@ -567,31 +567,62 @@ The inner `Meta` class on serializers is not inherited from parent classes by de Typically we would recommend *not* using inheritance on inner Meta classes, but instead declaring all options explicitly. -## Advanced `ModelSerializer` usage +## Customizing field mappings The ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer. -#### `.serializer_field_mapping` +Normally if a `ModelSerializer` does not generate the fields you need by default the you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model. + +### `.serializer_field_mapping` A mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class. -#### `.serializer_relational_field` +### `.serializer_relational_field` This property should be the serializer field class, that is used for relational fields by default. For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`. For `HyperlinkedModelSerializer` this defaults to `HyperlinkedRelatedField`. -#### The build field methods +### The field_class and field_kwargs API + +The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`. + +### `.build_standard_field(self, field_name, model_field)` + +Called to generate a serializer field that maps to a standard model field. + +The default implementation returns a serializer class based on the `serializer_field_mapping` attribute. + +### `.build_relational_field(self, field_name, relation_info)` + +Called to generate a serializer field that maps to a relational model field. + +The default implementation returns a serializer class based on the `serializer_relational_field` attribute. + +The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties. + +### `.build_nested_field(self, field_name, relation_info, nested_depth)` + +Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set. + +The default implementation dynamically creates a nested serializer class based on either `ModelSerializer` or `HyperlinkedModelSerializer`. + +The `nested_depth` will be the value of the `depth` option, minus one. + +The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties. + +### `.build_property_field(self, field_name, model_class)` -#### `build_standard_field(**kwargs)` +Called to generate a serializer field that maps to a property or zero-argument method on the model class. -#### `build_relational_field(**kwargs)` +The default implementation returns a `ReadOnlyField` class. -#### `build_nested_field(**kwargs)` +### `.build_url_field(self, field_name, model_class)` -#### `build_property_field(**kwargs)` +Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class. -#### `build_url_field(**kwargs)` +### `.build_unknown_field(self, field_name, model_class)` -#### `build_unknown_field(**kwargs)` +Called when the field name did not map to any model field or model property. +The default implementation raises an error, although subclasses may customize this behavior. --- -- cgit v1.2.3 From 35696748603665526be7947e918d41856644ec52 Mon Sep 17 00:00:00 2001 From: Brian Stearns Date: Sun, 21 Dec 2014 18:53:35 -0500 Subject: use of double quotes broke the code highlighting. --- docs/api-guide/fields.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index f06db56c..946e355d 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -480,7 +480,7 @@ Let's look at an example of serializing a class that represents an RGB color val class ColorField(serializers.Field): """ - Color objects are serialized into "rgb(#, #, #)" notation. + Color objects are serialized into 'rgb(#, #, #)' notation. """ def to_representation(self, obj): return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue) -- cgit v1.2.3 From 18687f075d9fb998b82c6fb8f6cb37eb1ed7e5bf Mon Sep 17 00:00:00 2001 From: Matías Lang Date: Tue, 23 Dec 2014 12:22:10 -0300 Subject: Documented an optional argument of HyperlinkedIdentityField lookup_url_kwarg argument of HyperlinkedIdentityField wasn't documented--- docs/api-guide/relations.md | 1 + 1 file changed, 1 insertion(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index e56db229..50e3b7b5 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -231,6 +231,7 @@ This field is always read-only. * `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `-detail`. **required**. * `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'`. +* `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as `lookup_field`. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. --- -- cgit v1.2.3 From 5b5652594a9c000d8e925d35efa03be27c28c077 Mon Sep 17 00:00:00 2001 From: Rocky Meza Date: Fri, 26 Dec 2014 22:24:31 -0700 Subject: Typo manger => manager --- docs/api-guide/serializers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index b9f0e7bc..f88ec51f 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -384,7 +384,7 @@ This manager class now more nicely encapsulates that user instances and profile has_support_contract=validated_data['profile']['has_support_contract'] ) -For more details on this approach see the Django documentation on [model managers](model-managers), and [this blogpost on using model and manger classes](encapsulation-blogpost). +For more details on this approach see the Django documentation on [model managers](model-managers), and [this blogpost on using model and manager classes](encapsulation-blogpost). ## Dealing with multiple objects -- cgit v1.2.3 From a636320ff3b381a6d7d8685f1b4fba8bdd6c8b94 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 28 Dec 2014 11:02:19 +0000 Subject: Add import notes in docs. Closes #2357 --- docs/api-guide/generic-views.md | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index f5bbdfdd..6374e305 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -214,6 +214,8 @@ You won't typically need to override the following methods, although you might n 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. +The mixin classes can be imported from `rest_framework.mixins`. + ## ListModelMixin Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset. @@ -258,6 +260,8 @@ If an object is deleted this returns a `204 No Content` response, otherwise it w 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. +The view classes can be imported from `rest_framework.generics`. + ## CreateAPIView Used for **create-only** endpoints. -- cgit v1.2.3 From 8dc95ee22181de6e38c7187426bca9fcee9d7927 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 28 Dec 2014 11:24:49 +0000 Subject: Add notes on include and namespacing. Closes #2335. --- docs/api-guide/routers.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 6819adb6..3a8a8f6c 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -49,6 +49,38 @@ This means you'll need to explicitly set the `base_name` argument when registeri --- +### Using `include` with routers + +The `.urls` attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs. + +For example, you can append `router.urls` to a list of existing views… + + router = routers.SimpleRouter() + router.register(r'users', UserViewSet) + router.register(r'accounts', AccountViewSet) + + urlpatterns = [ + url(r'^forgot-password/$, ForgotPasswordFormView.as_view(), + ] + + urlpatterns += router.urls + +Alternatively you can use Django's `include` function, like so… + + urlpatterns = [ + url(r'^forgot-password/$, ForgotPasswordFormView.as_view(), + url(r'^', include(router.urls)) + ] + +Router URL patterns can also be namespaces. + + urlpatterns = [ + url(r'^forgot-password/$, ForgotPasswordFormView.as_view(), + url(r'^api/', include(router.urls, namespace='api')) + ] + +If using namespacing with hyperlinked serializers you'll also need to ensure that any `view_name` parameters on the serializers correctly reflect the namespace. In the example above you'd need to include a parameter such as `view_name='api:user-detail'` for serializer fields hyperlinked to the user detail view. + ### Extra link and actions Any methods on the viewset decorated with `@detail_route` or `@list_route` will also be routed. -- cgit v1.2.3 From d8e66970a11ec2d4b66f0cf56950f2cc83e83224 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 28 Dec 2014 12:14:07 +0000 Subject: Note on using i18n_patterns with format_suffix_patterns. Closes #2278. --- docs/api-guide/format-suffixes.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md index 20c1e995..35dbcd39 100644 --- a/docs/api-guide/format-suffixes.md +++ b/docs/api-guide/format-suffixes.md @@ -55,6 +55,18 @@ The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` se Also note that `format_suffix_patterns` does not support descending into `include` URL patterns. +### Using with `i18n_patterns` + +If using the `i18n_patterns` function provided by Django, as well as `format_suffix_patterns` you should make sure that the `i18n_patterns` function is applied as the final, or outermost function. For example: + + url patterns = [ + … + ] + + urlpatterns = i18n_patterns( + format_suffix_patterns(urlpatterns, allowed=['json', 'html']) + ) + --- ## Accept headers vs. format suffixes -- cgit v1.2.3 From 17665aa52a9cd5599099c19fd8f54540a5d436ce Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 5 Jan 2015 12:26:15 +0000 Subject: Add docs for OAuth, XML, YAML, JSONP packages. Closes #2179. --- docs/api-guide/authentication.md | 47 +++++++++++++++++++++-- docs/api-guide/parsers.md | 51 +++++++++++++++++++++++-- docs/api-guide/renderers.md | 80 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 169 insertions(+), 9 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 2074f1bf..bb731817 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -293,13 +293,48 @@ The following example will authenticate any incoming request as the user given b The following third party packages are also available. -## Digest Authentication +## Django OAuth Toolkit -HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. [Juan Riaza][juanriaza] maintains the [djangorestframework-digestauth][djangorestframework-digestauth] package which provides HTTP digest authentication support for REST framework. +The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by [Evonove][evonove] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**. -## Django OAuth Toolkit +#### Installation & configuration + +Install using `pip`. + + pip install django-oauth-toolkit + +Add the package to your `INSTALLED_APPS` and modify your REST framework settings. -The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by [Evonove][evonove] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and comes as a recommended alternative for OAuth 2.0 support. + INSTALLED_APPS = ( + ... + 'oauth2_provider', + ) + + REST_FRAMEWORK = { + 'DEFAULT_AUTHENTICATION_CLASSES': ( + 'oauth2_provider.ext.rest_framework.OAuth2Authentication', + ) + } + +For more details see the [Django REST framework - Getting started][django-oauth-toolkit-getting-started] documentation. + +## Django REST framework OAuth + +The [Django REST framework OAuth][django-rest-framework-oauth] package provides both OAuth1 and OAuth2 support for REST framework. + +This package was previously included directly in REST framework but is now supported and maintained as a third party package. + +#### Installation & configuration + +Install the package using `pip`. + + pip install djangorestframework-oauth + +For details on configuration and usage see the Django REST framework OAuth documentation for [authentication][django-rest-framework-oauth-authentication] and [permissions][django-rest-framework-oauth-permissions]. + +## Digest Authentication + +HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. [Juan Riaza][juanriaza] maintains the [djangorestframework-digestauth][djangorestframework-digestauth] package which provides HTTP digest authentication support for REST framework. ## Django OAuth2 Consumer @@ -332,6 +367,10 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a [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 +[django-oauth-toolkit-getting-started]: https://django-oauth-toolkit.readthedocs.org/en/latest/rest-framework/getting_started.html +[django-rest-framework-oauth]: http://jpadilla.github.io/django-rest-framework-oauth/ +[django-rest-framework-oauth-authentication]: http://jpadilla.github.io/django-rest-framework-oauth/authentication/ +[django-rest-framework-oauth-permissions]: http://jpadilla.github.io/django-rest-framework-oauth/permissions/ [juanriaza]: https://github.com/juanriaza [djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth [oauth-1.0a]: http://oauth.net/core/1.0a diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 9323d382..b68b33be 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -26,7 +26,7 @@ As an example, if you are sending `json` encoded data using jQuery with the [.aj ## Setting the parsers -The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow requests with `JSON` content. +The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow only requests with `JSON` content, instead of the default of JSON or form data. REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( @@ -37,8 +37,8 @@ The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSE You can also set the parsers used for an individual view, or viewset, using the `APIView` class based views. - from rest_framework.parsers import JSONParser - from rest_framework.response import Response + from rest_framework.parsers import JSONParser + from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): @@ -162,6 +162,48 @@ The following is an example plaintext parser that will populate the `request.dat The following third party packages are also available. +## YAML + +[REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. + +#### Installation & configuration + +Install using pip. + + $ pip install djangorestframework-yaml + +Modify your REST framework settings. + + REST_FRAMEWORK = { + 'DEFAULT_PARSER_CLASSES': ( + 'rest_framework_yaml.parsers.YAMLParser', + ), + 'DEFAULT_RENDERER_CLASSES': ( + 'rest_framework_yaml.renderers.YAMLRenderer', + ), + } + +## XML + +[REST Framework XML][rest-framework-xml] provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. + +#### Installation & configuration + +Install using pip. + + $ pip install djangorestframework-xml + +Modify your REST framework settings. + + REST_FRAMEWORK = { + 'DEFAULT_PARSER_CLASSES': ( + 'rest_framework_xml.parsers.XMLParser', + ), + 'DEFAULT_RENDERER_CLASSES': ( + 'rest_framework_xml.renderers.XMLRenderer', + ), + } + ## MessagePack [MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework. @@ -173,6 +215,9 @@ 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 +[rest-framework-yaml]: http://jpadilla.github.io/django-rest-framework-yaml/ +[rest-framework-xml]: http://jpadilla.github.io/django-rest-framework-xml/ +[yaml]: http://www.yaml.org/ [messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack [juanriaza]: https://github.com/juanriaza [vbabiy]: https://github.com/vbabiy diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 69460dbc..83ded849 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -342,13 +342,81 @@ Templates will render with a `RequestContext` which includes the `status_code` a The following third party packages are also available. +## YAML + +[REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. + +#### Installation & configuration + +Install using pip. + + $ pip install djangorestframework-yaml + +Modify your REST framework settings. + + REST_FRAMEWORK = { + 'DEFAULT_PARSER_CLASSES': ( + 'rest_framework_yaml.parsers.YAMLParser', + ), + 'DEFAULT_RENDERER_CLASSES': ( + 'rest_framework_yaml.renderers.YAMLRenderer', + ), + } + +## XML + +[REST Framework XML][rest-framework-xml] provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. + +#### Installation & configuration + +Install using pip. + + $ pip install djangorestframework-xml + +Modify your REST framework settings. + + REST_FRAMEWORK = { + 'DEFAULT_PARSER_CLASSES': ( + 'rest_framework_xml.parsers.XMLParser', + ), + 'DEFAULT_RENDERER_CLASSES': ( + 'rest_framework_xml.renderers.XMLRenderer', + ), + } + +## JSONP + +[REST framework JSONP][rest-framework-jsonp] provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. + +--- + +**Warning**: If you require cross-domain AJAX requests, you should generally be using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details. + +The `jsonp` approach is essentially a browser hack, and is [only appropriate for globally readable API endpoints][jsonp-security], where `GET` requests are unauthenticated and do not require any user permissions. + +--- + +#### Installation & configuration + +Install using pip. + + $ pip install djangorestframework-jsonp + +Modify your REST framework settings. + + REST_FRAMEWORK = { + 'DEFAULT_RENDERER_CLASSES': ( + 'rest_framework_yaml.renderers.JSONPRenderer', + ), + } + ## MessagePack [MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework. ## CSV -Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework. +Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework. ## UltraJSON @@ -358,7 +426,6 @@ Comma-separated values are a plain-text tabular data format, that can be easily [djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy]. - ## Pandas (CSV, Excel, PNG) [Django REST Pandas] provides a serializer and renderers that support additional data processing and output via the [Pandas] DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both `.xls` and `.xlsx`), and a number of [other formats]. It is maintained by [S. Andrew Sheppard][sheppard] as part of the [wq Project][wq]. @@ -373,10 +440,19 @@ Comma-separated values are a plain-text tabular data format, that can be easily [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 +[rest-framework-jsonp]: http://jpadilla.github.io/django-rest-framework-jsonp/ +[cors]: http://www.w3.org/TR/cors/ +[cors-docs]: http://www.django-rest-framework.org/topics/ajax-csrf-cors/ +[jsonp-security]: http://stackoverflow.com/questions/613962/is-jsonp-safe-to-use +[rest-framework-yaml]: http://jpadilla.github.io/django-rest-framework-yaml/ +[rest-framework-xml]: http://jpadilla.github.io/django-rest-framework-xml/ [messagepack]: http://msgpack.org/ [juanriaza]: https://github.com/juanriaza [mjumbewu]: https://github.com/mjumbewu [vbabiy]: https://github.com/vbabiy +[rest-framework-yaml]: http://jpadilla.github.io/django-rest-framework-yaml/ +[rest-framework-xml]: http://jpadilla.github.io/django-rest-framework-xml/ +[yaml]: http://www.yaml.org/ [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack [djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv [ultrajson]: https://github.com/esnme/ultrajson -- cgit v1.2.3 From b6ca7248ebcf95a95e1911aa0b130f653b8bf690 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 5 Jan 2015 14:32:12 +0000 Subject: required=False allows omission of value for output. Closes #2342 --- docs/api-guide/fields.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 946e355d..b3d274dd 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -41,6 +41,8 @@ Defaults to `False` Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization. +Setting this to `False` also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation. + Defaults to `True`. ### `allow_null` -- cgit v1.2.3 From 271b638df10c0cf498cbc69847f388e978c4da78 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 6 Jan 2015 11:21:58 +0000 Subject: Update exception docs. Closes #2378. --- docs/api-guide/exceptions.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 467ad970..993134f7 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -18,7 +18,7 @@ The handled exceptions are: In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error. -By default all error responses will include a key `detail` in the body of the response, but other keys may also be included. +Most error responses will include a key `detail` in the body of the response. For example, the following request: @@ -33,6 +33,16 @@ Might receive an error response indicating that the `DELETE` method is not allow {"detail": "Method 'DELETE' not allowed."} +Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the `NON_FIELD_ERRORS_KEY` setting. + +Any example validation error might look like this: + + HTTP/1.1 400 Bad Request + Content-Type: application/json + Content-Length: 94 + + {"amount": ["A valid integer is required."], "description": ["This field may not be blank."]} + ## Custom exception handling You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API. -- cgit v1.2.3 From fe92a2cfee9e3a20e913500802d98a15e8b70780 Mon Sep 17 00:00:00 2001 From: JocelynDelalande Date: Wed, 7 Jan 2015 10:42:11 +0100 Subject: fixed doc : DEFAULT_AUTHENTICATION_CLASSES -> DEFAULT_AUTHENTICATION + It is consistent with docs about DEFAULT_PERMISSION_CLASSES--- docs/api-guide/authentication.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index b04858e3..1222dbf0 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -34,7 +34,7 @@ The value of `request.user` and `request.auth` for unauthenticated requests can ## Setting the authentication scheme -The default authentication schemes may be set globally, using the `DEFAULT_AUTHENTICATION` setting. For example. +The default authentication schemes may be set globally, using the `DEFAULT_AUTHENTICATION_CLASSES` setting. For example. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( @@ -282,7 +282,7 @@ This authentication class depends on the optional [django-oauth2-provider][djang 'provider.oauth2', ) -Then add `OAuth2Authentication` to your global `DEFAULT_AUTHENTICATION` setting: +Then add `OAuth2Authentication` to your global `DEFAULT_AUTHENTICATION_CLASSES` setting: 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.OAuth2Authentication', -- cgit v1.2.3 From e61ef3d39f301bc62323b47af5080877e273c395 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 8 Jan 2015 11:07:47 +0000 Subject: Minor docs updates --- docs/api-guide/filtering.md | 1 + 1 file changed, 1 insertion(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 83977048..3eb1538f 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -316,6 +316,7 @@ Typically you'd instead control this by setting `order_by` on the initial querys queryset = User.objects.all() serializer_class = UserSerializer filter_backends = (filters.OrderingFilter,) + ordering_fields = ('username', 'email') ordering = ('username',) The `ordering` attribute may be either a string or a list/tuple of strings. -- cgit v1.2.3 From f0ad0a88c49f1fef473ef1fbf965bcaa974ee062 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 8 Jan 2015 12:31:51 +0000 Subject: Link to Roy Fielding versioning interview. --- docs/api-guide/versioning.md | 3 +++ 1 file changed, 3 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/versioning.md b/docs/api-guide/versioning.md index 92380cc0..7463f190 100644 --- a/docs/api-guide/versioning.md +++ b/docs/api-guide/versioning.md @@ -10,6 +10,8 @@ API versioning allows you to alter behavior between different clients. REST fram Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers. +There are a number of valid approaches to approaching versioning. [Non-versioned systems can also be appropriate][roy-fielding-on-versioning], particularly if you're engineering for very long-term systems with multiple clients outside of your control. + ## Versioning with REST framework When API versioning is enabled, the `request.version` attribute will contain a string that corresponds to the version requested in the incoming client request. @@ -195,6 +197,7 @@ The following example uses a custom `X-API-Version` header to determine the requ If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the `.reverse()` method on the class. See the source code for examples. [cite]: http://www.slideshare.net/evolve_conference/201308-fielding-evolve/31 +[roy-fielding-on-versioning]: http://www.infoq.com/articles/roy-fielding-on-versioning [klabnik-guidelines]: http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http#i_want_my_api_to_be_versioned [heroku-guidelines]: https://github.com/interagent/http-api-design#version-with-accepts-header [json-parameters]: http://tools.ietf.org/html/rfc4627#section-6 -- cgit v1.2.3 From 7f9a62a5bf6a86c4d0a96e5f00d7e96b22d3337f Mon Sep 17 00:00:00 2001 From: Philip Neustrom Date: Tue, 13 Jan 2015 15:19:52 +0800 Subject: Fix link to `django-rest-framework-filters` (formerly `django-rest-framework-chain`) --- docs/api-guide/filtering.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 07420d84..2b6d5449 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -388,9 +388,9 @@ We could achieve the same behavior by overriding `get_queryset()` on the views, The following third party packages provide additional filter implementations. -## Django REST framework chain +## Django REST framework filters package -The [django-rest-framework-chain package][django-rest-framework-chain] works together with the `DjangoFilterBackend` class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field. +The [django-rest-framework-filters package][django-rest-framework-filters] works together with the `DjangoFilterBackend` class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field. [cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters [django-filter]: https://github.com/alex/django-filter @@ -400,4 +400,4 @@ The [django-rest-framework-chain package][django-rest-framework-chain] works tog [view-permissions-blogpost]: http://blog.nyaruka.com/adding-a-view-permission-to-django-models [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 -[django-rest-framework-chain]: https://github.com/philipn/django-rest-framework-chain +[django-rest-framework-filters]: https://github.com/philipn/django-rest-framework-filters -- cgit v1.2.3 From 1bcec3a0ac4346b31b655a08505d3e3dc2156604 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 13 Jan 2015 17:14:13 +0000 Subject: API tweaks and pagination documentation --- docs/api-guide/pagination.md | 162 ++++++++++++++++--------------------------- 1 file changed, 58 insertions(+), 104 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 83429292..9fbeb22a 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -6,148 +6,101 @@ source: pagination.py > > — [Django documentation][cite] -REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types. +REST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data. -## Paginating basic data +The pagination API can support either: -Let's start by taking a look at an example from the Django documentation. +* Pagination links that are provided as part of the content of the response. +* Pagination links that are included in response headers, such as `Content-Range` or `Link`. - from django.core.paginator import Paginator +The built-in styles currently all use links included as part of the content of the response. This style is more accessible when using the browsable API. - objects = ['john', 'paul', 'george', 'ringo'] - paginator = Paginator(objects, 2) - page = paginator.page(1) - page.object_list - # ['john', 'paul'] +Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular `APIView`, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the `mixins.ListMixin` and `generics.GenericAPIView` classes for an example. -At this point we've got a page object. If we wanted to return this page object as a JSON response, we'd need to provide the client with context such as next and previous links, so that it would be able to page through the remaining results. +## Setting the pagination style - from rest_framework.pagination import PaginationSerializer +The default pagination style may be set globally, using the `DEFAULT_PAGINATION_CLASS` settings key. For example, to use the built-in limit/offset pagination, you would do: - serializer = PaginationSerializer(instance=page) - serializer.data - # {'count': 4, 'next': '?page=2', 'previous': None, 'results': [u'john', u'paul']} - -The `context` argument of the `PaginationSerializer` class may optionally include the request. If the request is included in the context then the next and previous links returned by the serializer will use absolute URLs instead of relative URLs. - - request = RequestFactory().get('/foobar') - serializer = PaginationSerializer(instance=page, context={'request': request}) - serializer.data - # {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']} - -We could now return that data in a `Response` object, and it would be rendered into the correct media type. - -## Paginating QuerySets - -Our first example worked because we were using primitive objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself. - -We can do this using the `object_serializer_class` attribute on the inner `Meta` class of the pagination serializer. For example. - - class UserSerializer(serializers.ModelSerializer): - """ - Serializes user querysets. - """ - class Meta: - model = User - fields = ('username', 'email') + REST_FRAMEWORK = { + 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination' + } - class PaginatedUserSerializer(pagination.PaginationSerializer): - """ - Serializes page objects of user querysets. - """ - class Meta: - object_serializer_class = UserSerializer +You can also set the pagination class on an individual view by using the `pagination_class` attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis. -We could now use our pagination serializer in a view like this. +## Modifying the pagination style - @api_view('GET') - def user_list(request): - queryset = User.objects.all() - paginator = Paginator(queryset, 20) +If you want to modify particular aspects of the pagination style, you'll want to override one of the pagination classes, and set the attributes that you want to change. - page = request.QUERY_PARAMS.get('page') - try: - users = paginator.page(page) - except PageNotAnInteger: - # 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. - users = paginator.page(paginator.num_pages) + class LargeResultsSetPagination(PageNumberPagination): + paginate_by = 1000 + paginate_by_param = 'page_size' + max_paginate_by = 10000 - serializer_context = {'request': request} - serializer = PaginatedUserSerializer(users, - context=serializer_context) - return Response(serializer.data) + class StandardResultsSetPagination(PageNumberPagination): + paginate_by = 100 + paginate_by_param = 'page_size' + max_paginate_by = 1000 -## Pagination in the generic views +You can then apply your new style to a view using the `.pagination_class` attribute: -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. + class BillingRecordsView(generics.ListAPIView): + queryset = Billing.objects.all() + serializer = BillingRecordsSerializer + pagination_class = LargeResultsSetPagination -The default pagination style may be set globally, using the `DEFAULT_PAGINATION_SERIALIZER_CLASS`, `PAGINATE_BY`, `PAGINATE_BY_PARAM`, and `MAX_PAGINATE_BY` settings. For example. +Or apply the style globally, using the `DEFAULT_PAGINATION_CLASS` settings key. For example: REST_FRAMEWORK = { - 'PAGINATE_BY': 10, # Default to 10 - 'PAGINATE_BY_PARAM': 'page_size', # Allow client to override, using `?page_size=xxx`. - 'MAX_PAGINATE_BY': 100 # Maximum limit allowed when using `?page_size=xxx`. - } - -You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view. + 'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination' } - class PaginatedListView(ListAPIView): - queryset = ExampleModel.objects.all() - serializer_class = ExampleModelSerializer - paginate_by = 10 - paginate_by_param = 'page_size' - max_paginate_by = 100 +# API Reference -Note that using a `paginate_by` value of `None` will turn off pagination for the view. -Note if you use the `PAGINATE_BY_PARAM` settings, you also have to set the `paginate_by_param` attribute in your view to `None` in order to turn off pagination for those requests that contain the `paginate_by_param` parameter. +## PageNumberPagination -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. +## LimitOffsetPagination --- -# Custom pagination serializers +# Custom pagination styles + +To create a custom pagination serializer class you should subclass `pagination.BasePagination` and override the `paginate_queryset(self, queryset, request, view)` and `get_paginated_response(self, data)` methods: -To create a custom pagination serializer class you should override `pagination.BasePaginationSerializer` and set the fields that you want the serializer to return. +* The `paginate_queryset` method is passed the initial queryset and should return an iterable object that contains only the data in the requested page. +* The `get_paginated_response` method is passed the serialized page data and should return a `Response` instance. -You can also override the name used for the object list field, by setting the `results_field` attribute, which defaults to `'results'`. +Note that the `paginate_queryset` method may set state on the pagination instance, that may later be used by the `get_paginated_response` method. ## Example -For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this. +Let's modify the built-in `PageNumberPagination` style, so that instead of include the pagination links in the body of the response, we'll instead include a `Link` header, in a [similar style to the GitHub API][github-link-pagination]. - from rest_framework import pagination - from rest_framework import serializers + class LinkHeaderPagination(PageNumberPagination) + def get_paginated_response(self, data): + next_url = self.get_next_link() previous_url = self.get_previous_link() - class LinksSerializer(serializers.Serializer): - next = pagination.NextPageField(source='*') - prev = pagination.PreviousPageField(source='*') + if next_url is not None and previous_url is not None: + link = '<{next_url}; rel="next">, <{previous_url}; rel="prev">' + elif next_url is not None: + link = '<{next_url}; rel="next">' + elif prev_url is not None: + link = '<{previous_url}; rel="prev">' + else: + link = '' - class CustomPaginationSerializer(pagination.BasePaginationSerializer): - links = LinksSerializer(source='*') # Takes the page object as the source - total_results = serializers.ReadOnlyField(source='paginator.count') + link = link.format(next_url=next_url, previous_url=previous_url) + headers = {'Link': link} if link else {} - results_field = 'objects' + return Response(data, headers=headers) -## Using your custom pagination serializer +## Using your custom pagination class -To have your custom pagination serializer be used by default, use the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting: +To have your custom pagination class be used by default, use the `DEFAULT_PAGINATION_CLASS` setting: REST_FRAMEWORK = { - 'DEFAULT_PAGINATION_SERIALIZER_CLASS': - 'example_app.pagination.CustomPaginationSerializer', + 'DEFAULT_PAGINATION_CLASS': + 'my_project.apps.core.pagination.LinkHeaderPagination', } -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(generics.ListAPIView): - model = ExampleModel - pagination_serializer_class = CustomPaginationSerializer - paginate_by = 10 - # Third party packages The following third party packages are also available. @@ -157,5 +110,6 @@ The following third party packages are also available. The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` mixin class][paginate-by-max-mixin] that allows your API clients to specify `?page_size=max` to obtain the maximum allowed page size. [cite]: https://docs.djangoproject.com/en/dev/topics/pagination/ +[github-link-pagination]: https://developer.github.com/guides/traversing-with-pagination/ [drf-extensions]: http://chibisov.github.io/drf-extensions/docs/ [paginate-by-max-mixin]: http://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin -- cgit v1.2.3 From 313aa727e3c44016e531a7af75051fc6e6d7cb96 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 14 Jan 2015 17:46:41 +0000 Subject: Tweaks --- docs/api-guide/pagination.md | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 9fbeb22a..ba71a303 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -74,7 +74,7 @@ Note that the `paginate_queryset` method may set state on the pagination instanc Let's modify the built-in `PageNumberPagination` style, so that instead of include the pagination links in the body of the response, we'll instead include a `Link` header, in a [similar style to the GitHub API][github-link-pagination]. - class LinkHeaderPagination(PageNumberPagination) + class LinkHeaderPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): next_url = self.get_next_link() previous_url = self.get_previous_link() @@ -82,7 +82,7 @@ Let's modify the built-in `PageNumberPagination` style, so that instead of inclu link = '<{next_url}; rel="next">, <{previous_url}; rel="prev">' elif next_url is not None: link = '<{next_url}; rel="next">' - elif prev_url is not None: + elif previous_url is not None: link = '<{previous_url}; rel="prev">' else: link = '' @@ -97,10 +97,20 @@ Let's modify the built-in `PageNumberPagination` style, so that instead of inclu To have your custom pagination class be used by default, use the `DEFAULT_PAGINATION_CLASS` setting: REST_FRAMEWORK = { - 'DEFAULT_PAGINATION_CLASS': - 'my_project.apps.core.pagination.LinkHeaderPagination', + 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination', + 'PAGINATE_BY': 10 } +API responses for list endpoints will now include a `Link` header, instead of including the pagination links as part of the body of the response, for example: + +--- + +![Link Header][link-header] + +*A custom pagination style, using the 'Link' header'* + +--- + # Third party packages The following third party packages are also available. @@ -111,5 +121,6 @@ The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` [cite]: https://docs.djangoproject.com/en/dev/topics/pagination/ [github-link-pagination]: https://developer.github.com/guides/traversing-with-pagination/ +[link-header]: ../img/link-header-pagination.png [drf-extensions]: http://chibisov.github.io/drf-extensions/docs/ [paginate-by-max-mixin]: http://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin -- cgit v1.2.3 From 53edd37df5aa0ac29dbe7824db2e33da1d901f98 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 15 Jan 2015 21:07:05 +0000 Subject: Tests for LimitOffsetPagination --- docs/api-guide/pagination.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index ba71a303..8ab2edd5 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -63,7 +63,7 @@ Or apply the style globally, using the `DEFAULT_PAGINATION_CLASS` settings key. # Custom pagination styles -To create a custom pagination serializer class you should subclass `pagination.BasePagination` and override the `paginate_queryset(self, queryset, request, view)` and `get_paginated_response(self, data)` methods: +To create a custom pagination serializer class you should subclass `pagination.BasePagination` and override the `paginate_queryset(self, queryset, request, view=None)` and `get_paginated_response(self, data)` methods: * The `paginate_queryset` method is passed the initial queryset and should return an iterable object that contains only the data in the requested page. * The `get_paginated_response` method is passed the serialized page data and should return a `Response` instance. -- cgit v1.2.3 From 3ca8f85a5b54e6f78fac273732b6c5be2ad25ae4 Mon Sep 17 00:00:00 2001 From: soooooot Date: Tue, 20 Jan 2015 22:24:58 +0800 Subject: correcting unclosed quote in routers.md correcting unclosed quote in routers.md--- docs/api-guide/routers.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 3a8a8f6c..9c9bfb50 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -60,7 +60,7 @@ For example, you can append `router.urls` to a list of existing views… router.register(r'accounts', AccountViewSet) urlpatterns = [ - url(r'^forgot-password/$, ForgotPasswordFormView.as_view(), + url(r'^forgot-password/$', ForgotPasswordFormView.as_view(), ] urlpatterns += router.urls @@ -68,14 +68,14 @@ For example, you can append `router.urls` to a list of existing views… Alternatively you can use Django's `include` function, like so… urlpatterns = [ - url(r'^forgot-password/$, ForgotPasswordFormView.as_view(), + url(r'^forgot-password/$', ForgotPasswordFormView.as_view(), url(r'^', include(router.urls)) ] Router URL patterns can also be namespaces. urlpatterns = [ - url(r'^forgot-password/$, ForgotPasswordFormView.as_view(), + url(r'^forgot-password/$', ForgotPasswordFormView.as_view(), url(r'^api/', include(router.urls, namespace='api')) ] -- cgit v1.2.3 From 6e471ad8f41dda11365080ca583a0ccbf37de55e Mon Sep 17 00:00:00 2001 From: Duncan Maitland Date: Thu, 22 Jan 2015 18:29:20 +1100 Subject: fix link to Django CSRF docs --- docs/api-guide/authentication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 1222dbf0..0d53de70 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -427,7 +427,7 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a [oauth]: http://oauth.net/2/ [permission]: permissions.md [throttling]: throttling.md -[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax +[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/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 -- cgit v1.2.3 From 5bb348605e5dad3b58495b1fc56ea393194b89fb Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 23 Jan 2015 15:31:08 +0000 Subject: UUIDField docs --- docs/api-guide/fields.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index b3d274dd..64ec902b 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -182,6 +182,12 @@ Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.v **Signature:** `URLField(max_length=200, min_length=None, allow_blank=False)` +## UUIDField + +A field that ensures the input is a valid UUID string. The `to_internal_value` method will return a `uuid.UUID` instance. On output the field will return a string in the canonical hyphenated format, for example: + + "de305d54-75b4-431b-adb2-eb6b9e546013" + --- # Numeric fields @@ -320,7 +326,7 @@ Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, alth ## MultipleChoiceField -A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. `to_internal_representation` returns a `set` containing the selected values. +A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. `to_internal_value` returns a `set` containing the selected values. **Signature:** `MultipleChoiceField(choices)` -- cgit v1.2.3 From 35f6a8246299d31ecce4f791f9527bf34cebe6e2 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 23 Jan 2015 16:27:23 +0000 Subject: Added DictField and support for HStoreField. --- docs/api-guide/fields.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 64ec902b..1c78a42b 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -380,7 +380,7 @@ A field class that validates a list of objects. **Signature**: `ListField(child)` -- `child` - A field instance that should be used for validating the objects in the list. +- `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated. For example, to validate a list of integers you might use something like the following: @@ -395,6 +395,23 @@ The `ListField` class also supports a declarative style that allows you to write We can now reuse our custom `StringListField` class throughout our application, without having to provide a `child` argument to it. +## DictField + +A field class that validates a dictionary of objects. The keys in `DictField` are always assumed to be string values. + +**Signature**: `DictField(child)` + +- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated. + +For example, to create a field that validates a mapping of strings to strings, you would write something like this: + + document = DictField(child=CharField()) + +You can also use the declarative style, as with `ListField`. For example: + + class DocumentField(DictField): + child = CharField() + --- # Miscellaneous fields -- cgit v1.2.3 From 39da9c7c865533d580ea410458aeb366835b18cc Mon Sep 17 00:00:00 2001 From: Jeff Fein-Worton Date: Sat, 24 Jan 2015 12:53:21 -0800 Subject: minor typo in viewsets docs --- docs/api-guide/viewsets.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 3e37cef8..b09dfc9e 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -146,7 +146,7 @@ The decorators can additionally take extra arguments that will be set for the ro def set_password(self, request, pk=None): ... -Theses decorators will route `GET` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example: +These decorators will route `GET` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example: @detail_route(methods=['post', 'delete']) def unset_password(self, request, pk=None): -- cgit v1.2.3 From 0a65913fea471e7545896bd88760be8b26a3225e Mon Sep 17 00:00:00 2001 From: Jeff Fein-Worton Date: Sat, 24 Jan 2015 18:34:16 -0800 Subject: typo in fields.md --- docs/api-guide/fields.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 1c78a42b..10291c12 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -461,7 +461,7 @@ This is a read-only field. It gets its value by calling a method on the serializ **Signature**: `SerializerMethodField(method_name=None)` -- `method-name` - The name of the method on the serializer to be called. If not included this defaults to `get_`. +- `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_`. The serializer method referred to by the `method_name` argument 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: -- cgit v1.2.3 From 0daf160946db4f2fed6a237136d738d954b841c0 Mon Sep 17 00:00:00 2001 From: Xavier Ordoquy Date: Wed, 28 Jan 2015 00:06:34 +0100 Subject: Fix #2476 --- docs/api-guide/routers.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 9c9bfb50..a9f911a9 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -60,7 +60,7 @@ For example, you can append `router.urls` to a list of existing views… router.register(r'accounts', AccountViewSet) urlpatterns = [ - url(r'^forgot-password/$', ForgotPasswordFormView.as_view(), + url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), ] urlpatterns += router.urls @@ -68,15 +68,15 @@ For example, you can append `router.urls` to a list of existing views… Alternatively you can use Django's `include` function, like so… urlpatterns = [ - url(r'^forgot-password/$', ForgotPasswordFormView.as_view(), - url(r'^', include(router.urls)) + url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), + url(r'^', include(router.urls)), ] Router URL patterns can also be namespaces. urlpatterns = [ - url(r'^forgot-password/$', ForgotPasswordFormView.as_view(), - url(r'^api/', include(router.urls, namespace='api')) + url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), + url(r'^api/', include(router.urls, namespace='api')), ] If using namespacing with hyperlinked serializers you'll also need to ensure that any `view_name` parameters on the serializers correctly reflect the namespace. In the example above you'd need to include a parameter such as `view_name='api:user-detail'` for serializer fields hyperlinked to the user detail view. -- cgit v1.2.3 From 4a2a36ef828ce0e687c48fdb597d343df65f0e2b Mon Sep 17 00:00:00 2001 From: mareknaskret Date: Wed, 28 Jan 2015 15:17:56 +0100 Subject: Update filtering.md Updated links for django-guardian package.--- docs/api-guide/filtering.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index e00560c7..b16b6be5 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -398,8 +398,8 @@ The [django-rest-framework-filters package][django-rest-framework-filters] works [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 -[guardian]: http://pythonhosted.org/django-guardian/ -[view-permissions]: http://pythonhosted.org/django-guardian/userguide/assign.html +[guardian]: https://django-guardian.readthedocs.org/ +[view-permissions]: https://django-guardian.readthedocs.org/en/latest/userguide/assign.html [view-permissions-blogpost]: http://blog.nyaruka.com/adding-a-view-permission-to-django-models [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 -- cgit v1.2.3 From e720927b78a31999f03bfa248329d623ce2c045c Mon Sep 17 00:00:00 2001 From: Tymur Maryokhin Date: Thu, 29 Jan 2015 17:28:18 +0100 Subject: Removed deprecated '.model' docs --- docs/api-guide/generic-views.md | 8 ++------ docs/api-guide/routers.md | 2 +- 2 files changed, 3 insertions(+), 7 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 6374e305..61c8e8d8 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -93,17 +93,13 @@ The following attributes are used to control pagination when used with list view * `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. -**Deprecated attributes**: - -* `model` - This shortcut may be used instead of setting either (or both) of the `queryset`/`serializer_class` attributes. The explicit style is preferred over the `.model` shortcut, and usage of this attribute is now deprecated. - ### 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. +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. This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests. @@ -153,7 +149,7 @@ For example: #### `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. +Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute. May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users. diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index a9f911a9..592f7d66 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -28,7 +28,7 @@ There are two mandatory arguments to the `register()` method: 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. Note that if the viewset does not include a `model` or `queryset` attribute then you must set `base_name` when registering the viewset. +* `base_name` - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the `queryset` attribute of the viewset, if it has one. Note that if the viewset does not include a `queryset` attribute then you must set `base_name` when registering the viewset. The example above would generate the following URL patterns: -- cgit v1.2.3 From 7cf9dea7f905ea6869148a68b4fa96cad0a347e8 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 30 Jan 2015 11:00:29 +0000 Subject: Docs typo. Closes #2491. --- docs/api-guide/parsers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 73e3a705..3d44fe56 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -128,7 +128,7 @@ If the view used with `FileUploadParser` is called with a `filename` URL keyword def put(self, request, filename, format=None): file_obj = request.data['file'] # ... - # do some staff with uploaded file + # do some stuff with uploaded file # ... return Response(status=204) -- cgit v1.2.3 From f6765696610a0de3cf7d9986a2dfab40ca37e88b Mon Sep 17 00:00:00 2001 From: James Cooke Date: Tue, 3 Feb 2015 13:43:03 +0000 Subject: Small documentation fixes * Remove "you you" from viewsets API-guide * Fix link from routers API-guide to viewsets API-guide --- docs/api-guide/routers.md | 2 +- docs/api-guide/viewsets.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 592f7d66..222b6cd2 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -304,7 +304,7 @@ The [wq.db package][wq.db] provides an advanced [Router][wq.db-router] class (an The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions-routers] for creating [nested viewsets][drf-extensions-nested-viewsets], [collection level controllers][drf-extensions-collection-level-controllers] with [customizable endpoint names][drf-extensions-customizable-endpoint-names]. [cite]: http://guides.rubyonrails.org/routing.html -[route-decorators]: viewsets.html#marking-extra-actions-for-routing +[route-decorators]: viewsets.md#marking-extra-actions-for-routing [drf-nested-routers]: https://github.com/alanjds/drf-nested-routers [wq.db]: http://wq.io/wq.db [wq.db-router]: http://wq.io/docs/app.py diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index b09dfc9e..bbf92c6c 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -201,7 +201,7 @@ Note that you can use any of the standard attributes or method overrides provide def get_queryset(self): return self.request.user.accounts.all() -Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the base_name of your Model automatically, and so you you will have to specify the `base_name` kwarg as part of your [router registration][routers]. +Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the base_name of your Model automatically, and so you will have to specify the `base_name` kwarg as part of your [router registration][routers]. 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. -- cgit v1.2.3 From 76efbdddb69d0e7279c1b9de066e829f34019609 Mon Sep 17 00:00:00 2001 From: Warren Jin Date: Tue, 3 Feb 2015 17:18:54 -0500 Subject: docs --- docs/api-guide/fields.md | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index b3d274dd..f379ac72 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -567,6 +567,10 @@ The [drf-compound-fields][drf-compound-fields] package provides "compound" seria The [drf-extra-fields][drf-extra-fields] package provides extra serializer fields for REST framework, including `Base64ImageField` and `PointField` classes. +## djangrestframework-recursive + +the [djangorestframework-recursive][djangorestframework-recursive] package provides a `RecursiveField` for serializing and deserializing recursive structures + ## django-rest-framework-gis The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer. @@ -583,6 +587,7 @@ The [django-rest-framework-hstore][django-rest-framework-hstore] package provide [iso8601]: http://www.w3.org/TR/NOTE-datetime [drf-compound-fields]: http://drf-compound-fields.readthedocs.org [drf-extra-fields]: https://github.com/Hipo/drf-extra-fields +[djangorestframework-recursive]: https://github.com/heywbj/django-rest-framework-recursive [django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis [django-rest-framework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore [django-hstore]: https://github.com/djangonauts/django-hstore -- cgit v1.2.3 From 7f801b9a01fa7df3b081ddec803bd0d34cc3b35b Mon Sep 17 00:00:00 2001 From: José Padilla Date: Fri, 6 Feb 2015 01:09:19 -0400 Subject: Add trim_whitespace to CharField #2517 If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.--- docs/api-guide/fields.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 10291c12..9c33974f 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -138,11 +138,12 @@ A text representation. Optionally validates the text to be shorter than `max_len Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.TextField`. -**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False)` +**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)` - `max_length` - Validates that the input contains no more than this number of characters. - `min_length` - Validates that the input contains no fewer than this number of characters. - `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. +- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`. The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs. @@ -524,7 +525,7 @@ As an example, let's create a field that can be used represent the class name of # We pass the object instance onto `to_representation`, # not just the field attribute. return obj - + def to_representation(self, obj): """ Serialize the object's class name. -- cgit v1.2.3 From 5d8c3abe726768d30619f7596fb863b4f83719ee Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 6 Feb 2015 15:27:35 +0000 Subject: Fix typo --- docs/api-guide/versioning.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/versioning.md b/docs/api-guide/versioning.md index 7463f190..30dfeb2c 100644 --- a/docs/api-guide/versioning.md +++ b/docs/api-guide/versioning.md @@ -150,7 +150,7 @@ In the following example we're giving a set of views two different possible URL url(r'^v2/bookings/', include('bookings.urls', namespace='v2')) ] -Both `URLParameterVersioning` and `NamespaceVersioning` are reasonable if you just need a simple versioning scheme. The `URLParameterVersioning` approach might be better suitable for small ad-hoc projects, and the `NaemspaceVersioning` is probably easier to manage for larger projects. +Both `URLParameterVersioning` and `NamespaceVersioning` are reasonable if you just need a simple versioning scheme. The `URLParameterVersioning` approach might be better suitable for small ad-hoc projects, and the `NamespaceVersioning` is probably easier to manage for larger projects. ## HostNameVersioning -- cgit v1.2.3 From 670723f0216e5aea3aa133c99703949900be3d20 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 6 Feb 2015 15:45:02 +0000 Subject: Minor cleanups/improvements to ModelSerializer API --- docs/api-guide/serializers.md | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 9a9d5032..940eb424 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -577,9 +577,25 @@ Normally if a `ModelSerializer` does not generate the fields you need by default A mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class. -### `.serializer_relational_field` +### `.serializer_related_field` -This property should be the serializer field class, that is used for relational fields by default. For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`. For `HyperlinkedModelSerializer` this defaults to `HyperlinkedRelatedField`. +This property should be the serializer field class, that is used for relational fields by default. + +For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`. + +For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`. + +### `serializer_url_field` + +The serializer field class that should be used for any `url` field on the serializer. + +Defaults to `serializers.HyperlinkedIdentityField` + +### `serializer_choice_field` + +The serializer field class that should be used for any choice fields on the serializer. + +Defaults to `serializers.ChoiceField` ### The field_class and field_kwargs API -- cgit v1.2.3 From 407480b4840990ff17f9a33b293cfcf15bb6f7c5 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 9 Feb 2015 17:01:41 +0000 Subject: Minor docs work --- docs/api-guide/pagination.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 8ab2edd5..bae579a6 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -53,12 +53,22 @@ Or apply the style globally, using the `DEFAULT_PAGINATION_CLASS` settings key. REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination' } +--- + # API Reference ## PageNumberPagination +**TODO** + ## LimitOffsetPagination +**TODO** + +## CursorPagination + +**TODO** + --- # Custom pagination styles @@ -111,6 +121,12 @@ API responses for list endpoints will now include a `Link` header, instead of in --- +# HTML pagination controls + +## Customizing the controls + +--- + # Third party packages The following third party packages are also available. -- cgit v1.2.3 From 9d80335ac86076f75c81de02abc0cda8f98916d7 Mon Sep 17 00:00:00 2001 From: Tymur Maryokhin Date: Thu, 12 Feb 2015 01:10:03 +0100 Subject: Remove '.model' shortcut from viewset docs. Refs #2486. Closes #2549. --- docs/api-guide/viewsets.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index bbf92c6c..4fd7aa84 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -178,7 +178,7 @@ The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, #### Example -Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes, or the `model` attribute shortcut. For 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): """ -- cgit v1.2.3 From 30e6f32f6fbe20eafe949017cd62aed5d15529d5 Mon Sep 17 00:00:00 2001 From: Yannick PÉROUX Date: Tue, 17 Feb 2015 17:08:30 +0100 Subject: Fix typo in requests.md --- docs/api-guide/requests.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md index 77000ffa..c993dfae 100644 --- a/docs/api-guide/requests.md +++ b/docs/api-guide/requests.md @@ -38,7 +38,7 @@ For clarity inside your code, we recommend using `request.query_params` instead ## .DATA and .FILES -The old-style version 2.x `request.data` and `request.FILES` attributes are still available, but are now pending deprecation in favor of the unified `request.data` attribute. +The old-style version 2.x `request.DATA` and `request.FILES` attributes are still available, but are now pending deprecation in favor of the unified `request.data` attribute. ## .QUERY_PARAMS -- cgit v1.2.3 From d9c652813d3ab0ddebbb5503ce8ed57c49e1d0d2 Mon Sep 17 00:00:00 2001 From: Paul Hallett Date: Mon, 16 Feb 2015 16:07:08 +0000 Subject: add missing import in tests --- docs/api-guide/testing.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index cd8c7820..d9a1696d 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -65,6 +65,8 @@ When testing views directly using a request factory, it's often convenient to be To forcibly authenticate a request, use the `force_authenticate()` method. + from rest_framework.tests import force_authenticate + factory = APIRequestFactory() user = User.objects.get(username='olivia') view = AccountDetail.as_view() -- cgit v1.2.3 From c0916c2859468f4888d688217baca73747fd3bf7 Mon Sep 17 00:00:00 2001 From: aRkadeFR Date: Fri, 20 Feb 2015 15:59:10 +0100 Subject: Documentation test fix double word --- docs/api-guide/testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index d9a1696d..1b96b325 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -14,7 +14,7 @@ Extends [Django's existing `RequestFactory` class][requestfactory]. ## Creating test requests -The `APIRequestFactory` class supports an almost identical API to Django's standard `RequestFactory` class. This means the that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. +The `APIRequestFactory` class supports an almost identical API to Django's standard `RequestFactory` class. This means that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. from rest_framework.test import APIRequestFactory -- cgit v1.2.3 From f29b657798d3f2223275fb33ca95fab2209fc229 Mon Sep 17 00:00:00 2001 From: ludbek Date: Sat, 21 Feb 2015 07:52:56 +0545 Subject: updated outdated link at testing.md#APIClient --- docs/api-guide/testing.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index d9a1696d..9dc3f2bf 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -115,7 +115,7 @@ Extends [Django's existing `Client` class][client]. ## Making requests -The `APIClient` class supports the same request interface as `APIRequestFactory`. This means the that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. For example: +The `APIClient` class supports the same request interface as Django's standard `Client` class. This means the that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. For example: from rest_framework.test import APIClient @@ -269,6 +269,6 @@ For example, to add support for using `format='html'` in test requests, you migh } [cite]: http://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper -[client]: https://docs.djangoproject.com/en/dev/topics/testing/overview/#module-django.test.client +[client]: https://docs.djangoproject.com/en/dev/topics/testing/tools/#the-test-client [requestfactory]: https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.client.RequestFactory [configuration]: #configuration -- cgit v1.2.3 From e51dc1855c2e0b2c079d5e248e58afea5bc016f7 Mon Sep 17 00:00:00 2001 From: Mateusz Sikora Date: Wed, 25 Feb 2015 18:51:20 +0100 Subject: Update authentication.md --- docs/api-guide/authentication.md | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 4b8110bd..fe1be7bf 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -353,6 +353,10 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a [Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system. +## django-rest-auth + +[Django-rest-auth][django-rest-auth] library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management. + [cite]: http://jacobian.org/writing/rest-worst-practices/ [http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2 [http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4 @@ -392,3 +396,4 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a [mohawk]: http://mohawk.readthedocs.org/en/latest/ [mac]: http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05 [djoser]: https://github.com/sunscrapers/djoser +[django-rest-auth]: https://github.com/Tivix/django-rest-auth -- cgit v1.2.3 From 03818ed004cbe77459663f92a21691cfb7d9f010 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 26 Feb 2015 12:48:34 +0000 Subject: Pagination tweaks and docs --- docs/api-guide/pagination.md | 164 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 154 insertions(+), 10 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index bae579a6..697ba38d 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -32,14 +32,14 @@ You can also set the pagination class on an individual view by using the `pagina If you want to modify particular aspects of the pagination style, you'll want to override one of the pagination classes, and set the attributes that you want to change. class LargeResultsSetPagination(PageNumberPagination): - paginate_by = 1000 - paginate_by_param = 'page_size' - max_paginate_by = 10000 + page_size = 1000 + page_size_query_param = 'page_size' + max_page_size = 10000 class StandardResultsSetPagination(PageNumberPagination): - paginate_by = 100 - paginate_by_param = 'page_size' - max_paginate_by = 1000 + page_size = 100 + page_size_query_param = 'page_size' + max_page_size = 1000 You can then apply your new style to a view using the `.pagination_class` attribute: @@ -59,15 +59,141 @@ Or apply the style globally, using the `DEFAULT_PAGINATION_CLASS` settings key. ## PageNumberPagination -**TODO** +This pagination style accepts a single number page number in the request query parameters. + +**Request**: + + GET https://api.example.org/accounts/?page=4 + +**Response**: + + HTTP 200 OK + { + "count": 1023 + "next": "https://api.example.org/accounts/?page=5", + "previous": "https://api.example.org/accounts/?page=3", + "results": [ + … + ] + } + +#### Setup + +To enable the `PageNumberPagination` style globally, use the following configuration, modifying the `DEFAULT_PAGE_SIZE` as desired: + + REST_FRAMEWORK = { + 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', + 'DEFAULT_PAGE_SIZE': 100 + } + +On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `PageNumberPagination` on a per-view basis. + +#### Configuration + +The `PageNumberPagination` class includes a number of attributes that may be overridden to modify the pagination style. + +To set these attributes you should override the `PageNumberPagination` class, and then enable your custom pagination class as above. + +* `page_size` - A numeric value indicating the page size. If set, this overrides the `DEFAULT_PAGE_SIZE` setting. Defaults to the same value as the `DEFAULT_PAGE_SIZE` settings key. +* `page_query_param` - A string value indicating the name of the query parameter to use for the pagination control. +* `page_size_query_param` - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to `None`, indicating that the client may not control the requested page size. +* `max_page_size` - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if `page_size_query_param` is also set. +* `last_page_strings` - A list or tuple of string values indicating values that may be used with the `page_query_param` to request the final page in the set. Defaults to `('last',)` +* `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`. + +--- ## LimitOffsetPagination -**TODO** +This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an +"offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the `page_size` in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items. + +**Request**: + + GET https://api.example.org/accounts/?limit=100&offset=400 + +**Response**: + + HTTP 200 OK + { + "count": 1023 + "next": "https://api.example.org/accounts/?limit=100&offset=500", + "previous": "https://api.example.org/accounts/?limit=100&offset=300", + "results": [ + … + ] + } + +#### Setup + +To enable the `PageNumberPagination` style globally, use the following configuration: + + REST_FRAMEWORK = { + 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination' + } + +Optionally, you may also set a `DEFAULT_PAGE_SIZE` key. If the `DEFAULT_PAGE_SIZE` parameter is also used then the `limit` query parameter will be optional, and may be omitted by the client. + +On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `LimitOffsetPagination` on a per-view basis. + +#### Configuration + +The `LimitOffsetPagination` class includes a number of attributes that may be overridden to modify the pagination style. + +To set these attributes you should override the `LimitOffsetPagination` class, and then enable your custom pagination class as above. + +* `default_limit` - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the `DEFAULT_PAGE_SIZE` settings key. +* `limit_query_param` - A string value indicating the name of the "limit" query parameter. Defaults to `'limit'`. +* `offset_query_param` - A string value indicating the name of the "offset" query parameter. Defaults to `'offset'`. +* `max_limit` - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to `None`. +* `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`. + +--- ## CursorPagination -**TODO** +The cursor-based pagination presents an opaque "cursor" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions. + +Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against. + +Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits: + +* Provides a consistent pagination view. When used properly `CursorPagination` ensures that the client will never see the same item twice when paging through records. +* Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases. + +#### Details and limitations + +This implementation of cursor pagination uses a smart "position plus offset" style that allows it to properly support not-strictly-unique values as the ordering. + +It should be noted that using non-unique values the ordering does introduce the possibility of paging artifacts, where pagination consistency is no longer 100% guaranteed. + +**TODO**: Notes on `None`. + +The implementation also supports both forward and reverse pagination, which is often not supported in other implementations. + +For more technical details on the implementation we use for cursor pagination, the ["Building cursors for the Disqus API"][disqus-cursor-api] blog post gives a good overview of the basic approach. + +#### Setup + +To enable the `CursorPagination` style globally, use the following configuration, modifying the `DEFAULT_PAGE_SIZE` as desired: + + REST_FRAMEWORK = { + 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination', + 'DEFAULT_PAGE_SIZE': 100 + } + +On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `CursorPagination` on a per-view basis. + +#### Configuration + +The `CursorPagination` class includes a number of attributes that may be overridden to modify the pagination style. + +To set these attributes you should override the `CursorPagination` class, and then enable your custom pagination class as above. + +* `page_size` = A numeric value indicating the page size. If set, this overrides the `DEFAULT_PAGE_SIZE` setting. Defaults to the same value as the `DEFAULT_PAGE_SIZE` settings key. +* `cursor_query_param` = A string value indicating the name of the "cursor" query parameter. Defaults to `'cursor'`. +* `ordering` = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: `ordering = 'created'`. Any filters on the view which define a `get_ordering` will override this attribute. Defaults to `None`. +* `template` = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/previous_and_next.html"`. --- @@ -108,7 +234,7 @@ To have your custom pagination class be used by default, use the `DEFAULT_PAGINA REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination', - 'PAGINATE_BY': 10 + 'DEFAULT_PAGE_SIZE': 10 } API responses for list endpoints will now include a `Link` header, instead of including the pagination links as part of the body of the response, for example: @@ -123,8 +249,25 @@ API responses for list endpoints will now include a `Link` header, instead of in # HTML pagination controls +By default using the pagination classes will cause HTML pagination controls to be displayed in the browsable API. There are two built-in display styles. The `PageNumberPagination` and `LimitOffsetPagination` classes display a list of page numbers with previous and next controls. The `CursorPagination` class displays a simpler style that only displays a previous and next control. + ## Customizing the controls +You can override the templates that render the HTML pagination controls. The two built-in styles are: + +* `rest_framework/pagination/numbers.html` +* `rest_framework/pagination/previous_and_next.html` + +Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes. + +Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting `template = None` as an attribute on the class. You'll then need to configure your `DEFAULT_PAGINATION_CLASS` settings key to use your custom class as the default pagination style. + +#### Low-level API + +The low-level API for determining if a pagination class should display the controls or not is exposed as a `display_page_controls` attribute on the pagination instance. Custom pagination classes should be set to `True` in the `paginate_queryset` method if they require the HTML pagination controls to be displayed. + +The `.to_html()` and `.get_html_context()` methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered. + --- # Third party packages @@ -140,3 +283,4 @@ The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` [link-header]: ../img/link-header-pagination.png [drf-extensions]: http://chibisov.github.io/drf-extensions/docs/ [paginate-by-max-mixin]: http://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin +[disqus-cursor-api]: http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api/ \ No newline at end of file -- cgit v1.2.3 From 8f988466a594f9c0b6a7e6a2ed76c0b27a7f1895 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 26 Feb 2015 13:20:26 +0000 Subject: Docs on exception handler context. Closes #2604. --- docs/api-guide/exceptions.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 56811ec3..3e4b3e8b 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -47,7 +47,7 @@ Any example validation error might look like this: You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API. -The function must take a single argument, which is the exception to be handled, and should either return a `Response` object, or return `None` if the exception cannot be handled. If the handler returns `None` then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response. +The function must take a pair of arguments, this first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a `Response` object, or return `None` if the exception cannot be handled. If the handler returns `None` then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response. For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so: @@ -72,6 +72,8 @@ In order to alter the style of the response, you could write the following custo return response +The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as `context['view']`. + The exception handler must also be configured in your settings, using the `EXCEPTION_HANDLER` setting key. For example: REST_FRAMEWORK = { -- cgit v1.2.3 From 9c359181d7e897e796bd38f0b16e6ddd5ae70d86 Mon Sep 17 00:00:00 2001 From: aRkadeFR Date: Fri, 27 Feb 2015 17:38:28 +0100 Subject: update for `that the` instead of `that` --- docs/api-guide/testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index 1b96b325..ed8bbd1d 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -14,7 +14,7 @@ Extends [Django's existing `RequestFactory` class][requestfactory]. ## Creating test requests -The `APIRequestFactory` class supports an almost identical API to Django's standard `RequestFactory` class. This means that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. +The `APIRequestFactory` class supports an almost identical API to Django's standard `RequestFactory` class. This means that the standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. from rest_framework.test import APIRequestFactory -- cgit v1.2.3 From 18cc0230bff436da2f26b2b25034cece32c9f5d0 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 4 Mar 2015 15:51:00 +0000 Subject: Clean up pagination attributes --- docs/api-guide/generic-views.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 61c8e8d8..39e09aaa 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -84,10 +84,9 @@ The following attributes control the basic view behavior. The following attributes 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 override 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'`. +* `pagination_class` - The pagination class that should be used when paginating list results. Defaults to the same value as the `DEFAULT_PAGINATION_CLASS` setting, which is `'rest_framework.pagination.PageNumberPagination'`. + +Note that usage of the `paginate_by`, `paginate_by_param` and `page_kwarg` attributes are now pending deprecation. The `pagination_serializer_class` attribute and `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting have been removed completely. Pagination settings should instead be controlled by overriding a pagination class and setting any configuration attributes there. See the pagination documentation for more details. **Filtering**: -- cgit v1.2.3 From efb42ff7d048d165b151e3b75553ef720dc49cd3 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 4 Mar 2015 16:17:30 +0000 Subject: Update docs --- docs/api-guide/pagination.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 697ba38d..13bd57ae 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -208,6 +208,30 @@ Note that the `paginate_queryset` method may set state on the pagination instanc ## Example +Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so: + + class CustomPagination(pagination.PageNumberPagination): + def get_paginated_response(self, data): + return Response({ + 'links': { + 'next': self.get_next_link(), + 'previous': self.get_previous_link() + }, + 'count': self.page.paginator.count, + 'results': data + }) + +We'd then need to setup the custom class in our configuration: + + REST_FRAMEWORK = { + 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination', + 'PAGE_SIZE': 100 + } + +Note that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an `OrderedDict` when constructing the body of paginated responses, but this is optional. + +## Header based pagination + Let's modify the built-in `PageNumberPagination` style, so that instead of include the pagination links in the body of the response, we'll instead include a `Link` header, in a [similar style to the GitHub API][github-link-pagination]. class LinkHeaderPagination(pagination.PageNumberPagination): @@ -234,7 +258,7 @@ To have your custom pagination class be used by default, use the `DEFAULT_PAGINA REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination', - 'DEFAULT_PAGE_SIZE': 10 + 'PAGE_SIZE': 100 } API responses for list endpoints will now include a `Link` header, instead of including the pagination links as part of the body of the response, for example: -- cgit v1.2.3 From 58dfde7fcd9c29530d0613161dda0cf30c56a0a4 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 6 Mar 2015 10:22:32 +0000 Subject: Tweaks for cursor pagination and docs --- docs/api-guide/pagination.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 13bd57ae..14c0b7f2 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -51,7 +51,8 @@ You can then apply your new style to a view using the `.pagination_class` attrib Or apply the style globally, using the `DEFAULT_PAGINATION_CLASS` settings key. For example: REST_FRAMEWORK = { - 'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination' } + 'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination' + } --- @@ -163,6 +164,10 @@ Cursor based pagination is more complex than other schemes. It also requires tha #### Details and limitations +Cursor based pagination requires a specified ordering to be applied to the queryset. This will default to `'-created'`, which requires the model being paged against to have a `'created'` field. + + + This implementation of cursor pagination uses a smart "position plus offset" style that allows it to properly support not-strictly-unique values as the ordering. It should be noted that using non-unique values the ordering does introduce the possibility of paging artifacts, where pagination consistency is no longer 100% guaranteed. @@ -192,7 +197,7 @@ To set these attributes you should override the `CursorPagination` class, and th * `page_size` = A numeric value indicating the page size. If set, this overrides the `DEFAULT_PAGE_SIZE` setting. Defaults to the same value as the `DEFAULT_PAGE_SIZE` settings key. * `cursor_query_param` = A string value indicating the name of the "cursor" query parameter. Defaults to `'cursor'`. -* `ordering` = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: `ordering = 'created'`. Any filters on the view which define a `get_ordering` will override this attribute. Defaults to `None`. +* `ordering` = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: `ordering = '-created'`. Any filters on the view which define a `get_ordering` will override this attribute. Defaults to `None`. * `template` = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/previous_and_next.html"`. --- @@ -236,7 +241,8 @@ Let's modify the built-in `PageNumberPagination` style, so that instead of inclu class LinkHeaderPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): - next_url = self.get_next_link() previous_url = self.get_previous_link() + next_url = self.get_next_link() + previous_url = self.get_previous_link() if next_url is not None and previous_url is not None: link = '<{next_url}; rel="next">, <{previous_url}; rel="prev">' -- cgit v1.2.3 From c511342047f9eea01335fec0ac9ff7f4c823b696 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 6 Mar 2015 11:32:03 +0000 Subject: More docs on cursor pagination --- docs/api-guide/pagination.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 14c0b7f2..bc65267f 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -159,22 +159,23 @@ Cursor based pagination requires that there is a unique, unchanging ordering of Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits: -* Provides a consistent pagination view. When used properly `CursorPagination` ensures that the client will never see the same item twice when paging through records. +* Provides a consistent pagination view. When used properly `CursorPagination` ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process. * Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases. #### Details and limitations -Cursor based pagination requires a specified ordering to be applied to the queryset. This will default to `'-created'`, which requires the model being paged against to have a `'created'` field. +Proper use of cursor based pagination a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by `"-created"`. This assumes that **there must be a 'created' timestamp field** on the model instances, and will present a "timeline" style paginated view, with the most recently added items first. +You can modify the ordering by overriding the `'ordering'` attribute on the pagination class, or by using the `OrderingFilter` filter class together with `CursorPagination`. When used with `OrderingFilter` you should strongly consider restricting the fields that the user may order by. +Proper usage of cursor pagination should have an ordering field that satisfies the following: -This implementation of cursor pagination uses a smart "position plus offset" style that allows it to properly support not-strictly-unique values as the ordering. +* Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation. +* Should be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart "position plus offset" style that allows it to properly support not-strictly-unique values as the ordering. +* Should be a non-nullable value that can be coerced to a string. +* The field should have a database index. -It should be noted that using non-unique values the ordering does introduce the possibility of paging artifacts, where pagination consistency is no longer 100% guaranteed. - -**TODO**: Notes on `None`. - -The implementation also supports both forward and reverse pagination, which is often not supported in other implementations. +Using an ordering field that does not satisfy these constraints will generally still work, but you'll be loosing some of the benefits of cursor pagination. For more technical details on the implementation we use for cursor pagination, the ["Building cursors for the Disqus API"][disqus-cursor-api] blog post gives a good overview of the basic approach. @@ -197,7 +198,7 @@ To set these attributes you should override the `CursorPagination` class, and th * `page_size` = A numeric value indicating the page size. If set, this overrides the `DEFAULT_PAGE_SIZE` setting. Defaults to the same value as the `DEFAULT_PAGE_SIZE` settings key. * `cursor_query_param` = A string value indicating the name of the "cursor" query parameter. Defaults to `'cursor'`. -* `ordering` = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: `ordering = '-created'`. Any filters on the view which define a `get_ordering` will override this attribute. Defaults to `None`. +* `ordering` = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: `ordering = 'slug'`. Defaults to `-created`. This value may also be overridden by using `OrderingFilter` on the view. * `template` = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/previous_and_next.html"`. --- -- cgit v1.2.3 From 2ddb6bfa70036bc1182a768807362b4e46a1b67b Mon Sep 17 00:00:00 2001 From: José Padilla Date: Sat, 7 Mar 2015 10:19:25 -0400 Subject: Fix permissions on markdown files --- docs/api-guide/authentication.md | 0 docs/api-guide/generic-views.md | 0 2 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 docs/api-guide/authentication.md mode change 100755 => 100644 docs/api-guide/generic-views.md (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md old mode 100755 new mode 100644 diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md old mode 100755 new mode 100644 -- cgit v1.2.3 From d12de927adaac6018f3e8c232307b76372fe3527 Mon Sep 17 00:00:00 2001 From: José Padilla Date: Sat, 7 Mar 2015 10:49:56 -0400 Subject: Remove docs for 3.0 banners --- docs/api-guide/fields.md | 6 ------ docs/api-guide/generic-views.md | 6 ------ docs/api-guide/metadata.md | 8 +------- docs/api-guide/relations.md | 6 ------ docs/api-guide/requests.md | 6 ------ docs/api-guide/serializers.md | 8 +------- docs/api-guide/validators.md | 14 ++++---------- 7 files changed, 6 insertions(+), 48 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index f113bb23..5edc997a 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -1,11 +1,5 @@ source: fields.py ---- - -**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. - ---- - # 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. diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 39e09aaa..7df3d6ff 100644 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -1,12 +1,6 @@ source: mixins.py generics.py ---- - -**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. - ---- - # Generic views > Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself. diff --git a/docs/api-guide/metadata.md b/docs/api-guide/metadata.md index 247ae988..01727440 100644 --- a/docs/api-guide/metadata.md +++ b/docs/api-guide/metadata.md @@ -1,11 +1,5 @@ source: metadata.py ---- - -**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. - ---- - # Metadata > [The `OPTIONS`] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. @@ -59,7 +53,7 @@ Or you can set the metadata class individually for a view: class APIRoot(APIView): metadata_class = APIRootMetadata - + def get(self, request, format=None): return Response({ ... diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 50e3b7b5..093bbdd0 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -1,11 +1,5 @@ source: relations.py ---- - -**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. - ---- - # Serializer relations > Bad programmers worry about the code. diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md index c993dfae..658a5ffd 100644 --- a/docs/api-guide/requests.md +++ b/docs/api-guide/requests.md @@ -1,11 +1,5 @@ source: request.py ---- - -**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. - ---- - # Requests > If you're doing REST-based web service stuff ... you should ignore request.POST. diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 940eb424..aad2236f 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -1,11 +1,5 @@ source: serializers.py ---- - -**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. - ---- - # Serializers > Expanding the usefulness of the serializers is something that we would @@ -23,7 +17,7 @@ The serializers in REST framework work very similarly to Django's `Form` and `Mo Let's start by creating a simple object we can use for example purposes: from datetime import datetime - + class Comment(object): def __init__(self, email, content, created=None): self.email = email diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index 8f5a8929..40ad4857 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -1,11 +1,5 @@ source: validators.py ---- - -**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available. - ---- - # Validators > Validators can be useful for re-using validation logic between different types of fields. @@ -33,7 +27,7 @@ When you're using `ModelSerializer` all of this is handled automatically for you As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint. class CustomerReportRecord(models.Model): - time_raised = models.DateTimeField(default=timezone.now, editable=False) + time_raised = models.DateTimeField(default=timezone.now, editable=False) reference = models.CharField(unique=True, max_length=20) description = models.TextField() @@ -43,7 +37,7 @@ Here's a basic `ModelSerializer` that we can use for creating or updating instan class Meta: model = CustomerReportRecord -If we open up the Django shell using `manage.py shell` we can now +If we open up the Django shell using `manage.py shell` we can now >>> from project.example.serializers import CustomerReportSerializer >>> serializer = CustomerReportSerializer() @@ -204,7 +198,7 @@ A validator may be any callable that raises a `serializers.ValidationError` on f def even_number(value): if value % 2 != 0: - raise serializers.ValidationError('This field must be an even number.') + raise serializers.ValidationError('This field must be an even number.') ## Class based @@ -213,7 +207,7 @@ To write a class based validator, use the `__call__` method. Class based validat class MultipleOf: def __init__(self, base): self.base = base - + def __call__(self, value): if value % self.base != 0 message = 'This field must be a multiple of %d.' % self.base -- cgit v1.2.3 From c2cbda43b90159d4a98ad6afdb1e6594247bfcd5 Mon Sep 17 00:00:00 2001 From: jwbixby Date: Sun, 8 Mar 2015 00:22:28 -0500 Subject: Update documenation over PAGE_SIZE This replaces all locations of the old setting `DEFAULT_PAGE_SIZE` for the current setting `PAGE_SIZE`--- docs/api-guide/pagination.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index bc65267f..c264ea8c 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -80,11 +80,11 @@ This pagination style accepts a single number page number in the request query p #### Setup -To enable the `PageNumberPagination` style globally, use the following configuration, modifying the `DEFAULT_PAGE_SIZE` as desired: +To enable the `PageNumberPagination` style globally, use the following configuration, modifying the `PAGE_SIZE` as desired: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', - 'DEFAULT_PAGE_SIZE': 100 + 'PAGE_SIZE': 100 } On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `PageNumberPagination` on a per-view basis. @@ -95,7 +95,7 @@ The `PageNumberPagination` class includes a number of attributes that may be ove To set these attributes you should override the `PageNumberPagination` class, and then enable your custom pagination class as above. -* `page_size` - A numeric value indicating the page size. If set, this overrides the `DEFAULT_PAGE_SIZE` setting. Defaults to the same value as the `DEFAULT_PAGE_SIZE` settings key. +* `page_size` - A numeric value indicating the page size. If set, this overrides the `PAGE_SIZE` setting. Defaults to the same value as the `PAGE_SIZE` settings key. * `page_query_param` - A string value indicating the name of the query parameter to use for the pagination control. * `page_size_query_param` - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to `None`, indicating that the client may not control the requested page size. * `max_page_size` - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if `page_size_query_param` is also set. @@ -133,7 +133,7 @@ To enable the `PageNumberPagination` style globally, use the following configura 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination' } -Optionally, you may also set a `DEFAULT_PAGE_SIZE` key. If the `DEFAULT_PAGE_SIZE` parameter is also used then the `limit` query parameter will be optional, and may be omitted by the client. +Optionally, you may also set a `PAGE_SIZE` key. If the `PAGE_SIZE` parameter is also used then the `limit` query parameter will be optional, and may be omitted by the client. On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `LimitOffsetPagination` on a per-view basis. @@ -143,7 +143,7 @@ The `LimitOffsetPagination` class includes a number of attributes that may be ov To set these attributes you should override the `LimitOffsetPagination` class, and then enable your custom pagination class as above. -* `default_limit` - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the `DEFAULT_PAGE_SIZE` settings key. +* `default_limit` - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the `PAGE_SIZE` settings key. * `limit_query_param` - A string value indicating the name of the "limit" query parameter. Defaults to `'limit'`. * `offset_query_param` - A string value indicating the name of the "offset" query parameter. Defaults to `'offset'`. * `max_limit` - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to `None`. @@ -181,11 +181,11 @@ For more technical details on the implementation we use for cursor pagination, t #### Setup -To enable the `CursorPagination` style globally, use the following configuration, modifying the `DEFAULT_PAGE_SIZE` as desired: +To enable the `CursorPagination` style globally, use the following configuration, modifying the `PAGE_SIZE` as desired: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination', - 'DEFAULT_PAGE_SIZE': 100 + 'PAGE_SIZE': 100 } On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `CursorPagination` on a per-view basis. @@ -314,4 +314,4 @@ The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` [link-header]: ../img/link-header-pagination.png [drf-extensions]: http://chibisov.github.io/drf-extensions/docs/ [paginate-by-max-mixin]: http://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin -[disqus-cursor-api]: http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api/ \ No newline at end of file +[disqus-cursor-api]: http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api/ -- cgit v1.2.3 From 20ba47e3430a1ae18d47aee7c9e55b43db43c61b Mon Sep 17 00:00:00 2001 From: Deven Xie Date: Mon, 9 Mar 2015 00:10:26 -0400 Subject: Fixed missing word in CursorPagination docs --- docs/api-guide/pagination.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index bc65267f..4f97e7ea 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -164,7 +164,7 @@ Cursor based pagination is more complex than other schemes. It also requires tha #### Details and limitations -Proper use of cursor based pagination a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by `"-created"`. This assumes that **there must be a 'created' timestamp field** on the model instances, and will present a "timeline" style paginated view, with the most recently added items first. +Proper use of cursor based pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by `"-created"`. This assumes that **there must be a 'created' timestamp field** on the model instances, and will present a "timeline" style paginated view, with the most recently added items first. You can modify the ordering by overriding the `'ordering'` attribute on the pagination class, or by using the `OrderingFilter` filter class together with `CursorPagination`. When used with `OrderingFilter` you should strongly consider restricting the fields that the user may order by. @@ -314,4 +314,4 @@ The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` [link-header]: ../img/link-header-pagination.png [drf-extensions]: http://chibisov.github.io/drf-extensions/docs/ [paginate-by-max-mixin]: http://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin -[disqus-cursor-api]: http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api/ \ No newline at end of file +[disqus-cursor-api]: http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api/ -- cgit v1.2.3 From 69b6e26f06c787761bb8d6006ed6fc607fbc9d23 Mon Sep 17 00:00:00 2001 From: Bryan Alsdorf Date: Tue, 10 Mar 2015 17:30:41 -0500 Subject: Changed incorrect class name --- docs/api-guide/pagination.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 3518fb34..eca468b8 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -127,7 +127,7 @@ This pagination style mirrors the syntax used when looking up multiple database #### Setup -To enable the `PageNumberPagination` style globally, use the following configuration: +To enable the `LimitOffsetPagination` style globally, use the following configuration: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination' -- cgit v1.2.3