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