From 99ca078ebbb7995eb8d8bcbc5d1336a9a5543d0d Mon Sep 17 00:00:00 2001 From: Ryan P Kilby Date: Fri, 6 Jul 2018 05:28:18 -0400 Subject: [PATCH] Add "Community" section to docs, minor cleanup (#5993) * Add 'Community' tab to navigation, move articles * Drop DRF 2.x announcements and the docs note * Drop embedded tutorial/guide/topics links * Conver mixture of tabs/spaces => spaces * Fix topics/community links --- .../{topics => community}/3.0-announcement.md | 12 +- .../{topics => community}/3.1-announcement.md | 4 +- .../{topics => community}/3.2-announcement.md | 4 +- .../{topics => community}/3.3-announcement.md | 12 +- .../{topics => community}/3.4-announcement.md | 8 +- .../{topics => community}/3.5-announcement.md | 0 .../{topics => community}/3.6-announcement.md | 6 +- .../{topics => community}/3.7-announcement.md | 0 .../{topics => community}/3.8-announcement.md | 0 docs/{topics => community}/contributing.md | 0 docs/{topics => community}/funding.md | 182 ++++++------ docs/{topics => community}/jobs.md | 0 .../kickstarter-announcement.md | 0 docs/{topics => community}/mozilla-grant.md | 20 +- .../project-management.md | 0 docs/{topics => community}/release-notes.md | 0 .../third-party-packages.md | 0 .../tutorials-and-resources.md | 0 docs/index.md | 148 +--------- docs/topics/2.2-announcement.md | 158 ----------- docs/topics/2.3-announcement.md | 264 ------------------ docs/topics/2.4-announcement.md | 172 ------------ docs/topics/rest-framework-2-announcement.md | 97 ------- docs/topics/writable-nested-serializers.md | 18 +- docs/tutorial/1-serialization.md | 14 +- .../4-authentication-and-permissions.md | 2 +- mkdocs.yml | 37 +-- 27 files changed, 168 insertions(+), 990 deletions(-) rename docs/{topics => community}/3.0-announcement.md (99%) rename docs/{topics => community}/3.1-announcement.md (98%) rename docs/{topics => community}/3.2-announcement.md (99%) rename docs/{topics => community}/3.3-announcement.md (90%) rename docs/{topics => community}/3.4-announcement.md (97%) rename docs/{topics => community}/3.5-announcement.md (100%) rename docs/{topics => community}/3.6-announcement.md (97%) rename docs/{topics => community}/3.7-announcement.md (100%) rename docs/{topics => community}/3.8-announcement.md (100%) rename docs/{topics => community}/contributing.md (100%) rename docs/{topics => community}/funding.md (69%) rename docs/{topics => community}/jobs.md (100%) rename docs/{topics => community}/kickstarter-announcement.md (100%) rename docs/{topics => community}/mozilla-grant.md (83%) rename docs/{topics => community}/project-management.md (100%) rename docs/{topics => community}/release-notes.md (100%) rename docs/{topics => community}/third-party-packages.md (100%) rename docs/{topics => community}/tutorials-and-resources.md (100%) delete mode 100644 docs/topics/2.2-announcement.md delete mode 100644 docs/topics/2.3-announcement.md delete mode 100644 docs/topics/2.4-announcement.md delete mode 100644 docs/topics/rest-framework-2-announcement.md diff --git a/docs/topics/3.0-announcement.md b/docs/community/3.0-announcement.md similarity index 99% rename from docs/topics/3.0-announcement.md rename to docs/community/3.0-announcement.md index 03a2c281c..66a035380 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/community/3.0-announcement.md @@ -119,7 +119,7 @@ This would now be split out into two separate methods. instance.save() return instance - def create(self, validated_data): + def create(self, validated_data): return Snippet.objects.create(**validated_data) Note that these methods should return the newly created object instance. @@ -329,7 +329,7 @@ The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDe model = MyModel fields = ('id', 'email', 'notes', 'is_admin') extra_kwargs = { - 'is_admin': {'write_only': True} + 'is_admin': {'write_only': True} } Alternatively, specify the field explicitly on the serializer class: @@ -454,7 +454,7 @@ We can now use this class to serialize single `HighScore` instances: def high_score(request, pk): instance = HighScore.objects.get(pk=pk) serializer = HighScoreSerializer(instance) - return Response(serializer.data) + return Response(serializer.data) Or use it to serialize multiple instances: @@ -462,7 +462,7 @@ Or use it to serialize multiple instances: def all_high_scores(request): queryset = HighScore.objects.order_by('-score') serializer = HighScoreSerializer(queryset, many=True) - return Response(serializer.data) + return Response(serializer.data) ##### Read-write `BaseSerializer` classes. @@ -493,8 +493,8 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd 'player_name': 'May not be more than 10 characters.' }) - # Return the validated values. This will be available as - # the `.validated_data` property. + # Return the validated values. This will be available as + # the `.validated_data` property. return { 'score': int(score), 'player_name': player_name diff --git a/docs/topics/3.1-announcement.md b/docs/community/3.1-announcement.md similarity index 98% rename from docs/topics/3.1-announcement.md rename to docs/community/3.1-announcement.md index a86fa943a..0a2c40c9e 100644 --- a/docs/topics/3.1-announcement.md +++ b/docs/community/3.1-announcement.md @@ -123,7 +123,7 @@ If you only wish to support a subset of the supported languages, use Django's st ('en', _('English')), ] -For more details, see the [internationalization documentation](internationalization.md). +For more details, see the [internationalization documentation][internationalization]. Many thanks to [Craig Blaszczyk](https://github.com/jakul) for helping push this through. @@ -205,5 +205,5 @@ This will either be made as a single 3.2 release, or split across two separate r [custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling [pagination]: ../api-guide/pagination.md [versioning]: ../api-guide/versioning.md -[internationalization]: internationalization.md +[internationalization]: ../topics/internationalization.md [customizing-field-mappings]: ../api-guide/serializers.md#customizing-field-mappings diff --git a/docs/topics/3.2-announcement.md b/docs/community/3.2-announcement.md similarity index 99% rename from docs/topics/3.2-announcement.md rename to docs/community/3.2-announcement.md index 8500a9892..c022231a0 100644 --- a/docs/topics/3.2-announcement.md +++ b/docs/community/3.2-announcement.md @@ -83,7 +83,7 @@ When using `allow_null` with `ListField` or a nested `many=True` serializer the For example, take the following field: - NestedSerializer(many=True, allow_null=True) + NestedSerializer(many=True, allow_null=True) Previously the validation behavior would be: @@ -110,4 +110,4 @@ This release is planned to include: * Improvements and public API for our templated HTML forms and fields. * Nested object and list support in HTML forms. -Thanks once again to all our sponsors and supporters. \ No newline at end of file +Thanks once again to all our sponsors and supporters. diff --git a/docs/topics/3.3-announcement.md b/docs/community/3.3-announcement.md similarity index 90% rename from docs/topics/3.3-announcement.md rename to docs/community/3.3-announcement.md index 44e8dd511..5dcbe3b3b 100644 --- a/docs/topics/3.3-announcement.md +++ b/docs/community/3.3-announcement.md @@ -37,8 +37,8 @@ This brings our supported versions into line with Django's [currently supported The AJAX based support for the browsable API means that there are a number of internal cleanups in the `request` class. For the vast majority of developers this should largely remain transparent: * To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class. -* The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class](browser-enhancements.md#url-based-accept-headers). -* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware](browser-enhancements.md#http-header-based-method-overriding). +* The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class][accept-headers]. +* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override]. The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy. @@ -52,7 +52,9 @@ The following pagination view attributes and settings have been moved into attri The `ModelSerializer` and `HyperlinkedModelSerializer` classes should now include either a `fields` or `exclude` option, although the `fields = '__all__'` shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings `ModelSerializer` more closely in line with Django's `ModelForm` behavior. -[forms-api]: html-and-forms.md +[forms-api]: ../topics/html-and-forms.md [ajax-form]: https://github.com/encode/ajax-form -[jsonfield]: ../../api-guide/fields#jsonfield -[django-supported-versions]: https://www.djangoproject.com/download/#supported-versions \ No newline at end of file +[jsonfield]: ../api-guide/fields#jsonfield +[accept-headers]: ../topics/browser-enhancements.md#url-based-accept-headers +[method-override]: ../topics/browser-enhancements.md#http-header-based-method-overriding +[django-supported-versions]: https://www.djangoproject.com/download/#supported-versions diff --git a/docs/topics/3.4-announcement.md b/docs/community/3.4-announcement.md similarity index 97% rename from docs/topics/3.4-announcement.md rename to docs/community/3.4-announcement.md index 7db145600..73ec3f2a2 100644 --- a/docs/topics/3.4-announcement.md +++ b/docs/community/3.4-announcement.md @@ -185,10 +185,10 @@ The full set of itemized release notes [are available here][release-notes]. [swagger]: https://openapis.org/specification [hyperschema]: http://json-schema.org/latest/json-schema-hypermedia.html [api-blueprint]: https://apiblueprint.org/ -[tut-7]: ../../tutorial/7-schemas-and-client-libraries/ -[schema-generation]: ../../api-guide/schemas/ -[api-clients]: api-clients.md +[tut-7]: ../tutorial/7-schemas-and-client-libraries/ +[schema-generation]: ../api-guide/schemas/ +[api-clients]: ../topics/api-clients.md [milestone]: https://github.com/encode/django-rest-framework/milestone/35 [release-notes]: release-notes#34 -[metadata]: ../../api-guide/metadata/#custom-metadata-classes +[metadata]: ../api-guide/metadata/#custom-metadata-classes [gh3751]: https://github.com/encode/django-rest-framework/issues/3751 diff --git a/docs/topics/3.5-announcement.md b/docs/community/3.5-announcement.md similarity index 100% rename from docs/topics/3.5-announcement.md rename to docs/community/3.5-announcement.md diff --git a/docs/topics/3.6-announcement.md b/docs/community/3.6-announcement.md similarity index 97% rename from docs/topics/3.6-announcement.md rename to docs/community/3.6-announcement.md index fc3526d00..04e6a6669 100644 --- a/docs/topics/3.6-announcement.md +++ b/docs/community/3.6-announcement.md @@ -194,6 +194,6 @@ on realtime support, for the 3.7 release. [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors [funding]: funding.md -[api-docs]: documenting-your-api.md -[js-docs]: api-clients.md#javascript-client-library -[py-docs]: api-clients.md#python-client-library +[api-docs]: ../topics/documenting-your-api.md +[js-docs]: ../topics/api-clients.md#javascript-client-library +[py-docs]: ../topics/api-clients.md#python-client-library diff --git a/docs/topics/3.7-announcement.md b/docs/community/3.7-announcement.md similarity index 100% rename from docs/topics/3.7-announcement.md rename to docs/community/3.7-announcement.md diff --git a/docs/topics/3.8-announcement.md b/docs/community/3.8-announcement.md similarity index 100% rename from docs/topics/3.8-announcement.md rename to docs/community/3.8-announcement.md diff --git a/docs/topics/contributing.md b/docs/community/contributing.md similarity index 100% rename from docs/topics/contributing.md rename to docs/community/contributing.md diff --git a/docs/topics/funding.md b/docs/community/funding.md similarity index 69% rename from docs/topics/funding.md rename to docs/community/funding.md index d79b61b17..0faf2164b 100644 --- a/docs/topics/funding.md +++ b/docs/community/funding.md @@ -174,23 +174,23 @@ This subscription is recommended for individuals with an interest in seeing REST If you are using REST framework as a full-time employee, consider recommending that your company takes out a [corporate plan](#corporate-plans).
-
-
-
- {{ symbol }} - {{ rates.personal1 }} - /month{% if vat %} +VAT{% endif %} -
-
Individual
-
-
- Support ongoing development -
-
- Credited on the site -
-
- -
+
+
+
*Billing is monthly and you can cancel at any time.* @@ -222,23 +222,23 @@ In exchange for funding you'll also receive advertising space on our site, allow Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.
-
-
-
- {{ symbol }} - {{ rates.corporate1 }} - /month{% if vat %} +VAT{% endif %} -
-
Basic
-
-
- Support ongoing development -
-
- Funding page ad placement -
-
- -
-
-
- {{ symbol }} - {{ rates.corporate2 }} - /month{% if vat %} +VAT{% endif %} -
-
Professional
-
+
+
+
+
+
+ {{ symbol }} + {{ rates.corporate2 }} + /month{% if vat %} +VAT{% endif %} +
+
Professional
+
Support ongoing development
-
- Sidebar ad placement -
-
- Priority support for your engineers -
-
-
+ -
-
-
-
-
- {{ symbol }} - {{ rates.corporate3 }} - /month{% if vat %} +VAT{% endif %} -
-
Premium
-
+
+
+
+
+
+ {{ symbol }} + {{ rates.corporate3 }} + /month{% if vat %} +VAT{% endif %} +
+
Premium
+
Support ongoing development
-
- Homepage ad placement -
-
- Sidebar ad placement -
-
- Priority support for your engineers -
-
-
+ -
-
-
+
+
+
@@ -346,22 +346,22 @@ In an effort to keep the project as transparent as possible, we are releasing [m
-

Stay up to date, with our monthly progress reports...

+

Stay up to date, with our monthly progress reports...

- - + +
-
- - -
+
+ + +
diff --git a/docs/topics/jobs.md b/docs/community/jobs.md similarity index 100% rename from docs/topics/jobs.md rename to docs/community/jobs.md diff --git a/docs/topics/kickstarter-announcement.md b/docs/community/kickstarter-announcement.md similarity index 100% rename from docs/topics/kickstarter-announcement.md rename to docs/community/kickstarter-announcement.md diff --git a/docs/topics/mozilla-grant.md b/docs/community/mozilla-grant.md similarity index 83% rename from docs/topics/mozilla-grant.md rename to docs/community/mozilla-grant.md index f20b65f4f..4d9b1d438 100644 --- a/docs/topics/mozilla-grant.md +++ b/docs/community/mozilla-grant.md @@ -42,22 +42,22 @@ funded via the [REST framework paid plans](funding.md).
-

Stay up to date, with our monthly progress reports...

+

Stay up to date, with our monthly progress reports...

- - + +
-
- - -
+
+ + +
diff --git a/docs/topics/project-management.md b/docs/community/project-management.md similarity index 100% rename from docs/topics/project-management.md rename to docs/community/project-management.md diff --git a/docs/topics/release-notes.md b/docs/community/release-notes.md similarity index 100% rename from docs/topics/release-notes.md rename to docs/community/release-notes.md diff --git a/docs/topics/third-party-packages.md b/docs/community/third-party-packages.md similarity index 100% rename from docs/topics/third-party-packages.md rename to docs/community/third-party-packages.md diff --git a/docs/topics/tutorials-and-resources.md b/docs/community/tutorials-and-resources.md similarity index 100% rename from docs/topics/tutorials-and-resources.md rename to docs/community/tutorials-and-resources.md diff --git a/docs/index.md b/docs/index.md index c4acd19c8..43332715d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -31,10 +31,6 @@ --- -**Note**: This is the documentation for the **version 3** of REST framework. Documentation for [version 2](https://tomchristie.github.io/rest-framework-2-docs/) is also available. - ---- -

` flag. For example: - - extra_details = CharField(required=False) - -The `blank` keyword argument will continue to function, but will raise a `PendingDeprecationWarning`. - -### Simpler object-level permissions - -Custom permissions classes previously used the signature `.has_permission(self, request, view, obj=None)`. This method would be called twice, firstly for the global permissions check, with the `obj` parameter set to `None`, and again for the object-level permissions check when appropriate, with the `obj` parameter set to the relevant model instance. - -The global permissions check and object-level permissions check are now separated into two separate methods, which gives a cleaner, more obvious API. - -* Global permission checks now use the `.has_permission(self, request, view)` signature. -* Object-level permission checks use a new method `.has_object_permission(self, request, view, obj)`. - -For example, the following custom permission class: - - class IsOwner(permissions.BasePermission): - """ - Custom permission to only allow owners of an object to view or edit it. - Model instances are expected to include an `owner` attribute. - """ - - def has_permission(self, request, view, obj=None): - if obj is None: - # Ignore global permissions check - return True - - return obj.owner == request.user - -Now becomes: - - class IsOwner(permissions.BasePermission): - """ - Custom permission to only allow owners of an object to view or edit it. - Model instances are expected to include an `owner` attribute. - """ - - def has_object_permission(self, request, view, obj): - return obj.owner == request.user - -If you're overriding the `BasePermission` class, the old-style signature will continue to function, and will correctly handle both global and object-level permissions checks, but its use will raise a `PendingDeprecationWarning`. - -Note also that the usage of the internal APIs for permission checking on the `View` class has been cleaned up slightly, and is now documented and subject to the deprecation policy in all future versions. - -### More explicit hyperlink relations behavior - -When using a serializer with a `HyperlinkedRelatedField` or `HyperlinkedIdentityField`, the hyperlinks would previously use absolute URLs if the serializer context included a `'request'` key, and fall back to using relative URLs otherwise. This could lead to non-obvious behavior, as it might not be clear why some serializers generated absolute URLs, and others do not. - -From version 2.2 onwards, serializers with hyperlinked relationships *always* require a `'request'` key to be supplied in the context dictionary. The implicit behavior will continue to function, but its use will raise a `PendingDeprecationWarning`. - -[xordoquy]: https://github.com/xordoquy -[django-python-3]: https://docs.djangoproject.com/en/stable/faq/install/#can-i-use-django-with-python-3 -[porting-python-3]: https://docs.djangoproject.com/en/stable/topics/python3/ -[python-compat]: https://docs.djangoproject.com/en/stable/releases/1.5/#python-compatibility -[django-deprecation-policy]: https://docs.djangoproject.com/en/stable/internals/release-process/#internal-release-deprecation-policy -[credits]: http://www.django-rest-framework.org/topics/credits -[mailing-list]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework -[django-rest-framework-docs]: https://github.com/marcgibbons/django-rest-framework-docs -[marcgibbons]: https://github.com/marcgibbons/ -[564]: https://github.com/encode/django-rest-framework/issues/564 diff --git a/docs/topics/2.3-announcement.md b/docs/topics/2.3-announcement.md deleted file mode 100644 index d9bab39dc..000000000 --- a/docs/topics/2.3-announcement.md +++ /dev/null @@ -1,264 +0,0 @@ -# Django REST framework 2.3 - -REST framework 2.3 makes it even quicker and easier to build your Web APIs. - -## ViewSets and Routers - -The 2.3 release introduces the [ViewSet][viewset] and [Router][router] classes. - -A viewset is simply a type of class-based view that allows you to group multiple views into a single common class. - -Routers allow you to automatically determine the URLconf for your viewset classes. - -As an example of just how simple REST framework APIs can now be, here's an API written in a single `urls.py` module: - - """ - A REST framework API for viewing and editing users and groups. - """ - from django.conf.urls.defaults import url, include - from django.contrib.auth.models import User, Group - from rest_framework import viewsets, routers - - - # ViewSets define the view behavior. - class UserViewSet(viewsets.ModelViewSet): - model = User - - class GroupViewSet(viewsets.ModelViewSet): - model = Group - - - # Routers provide an easy way of automatically determining the URL conf - router = routers.DefaultRouter() - router.register(r'users', UserViewSet) - router.register(r'groups', GroupViewSet) - - - # Wire up our API using automatic URL routing. - # Additionally, we include login URLs for the browsable API. - urlpatterns = [ - url(r'^', include(router.urls)), - url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) - ] - -The best place to get started with ViewSets and Routers is to take a look at the [newest section in the tutorial][part-6], which demonstrates their usage. - -## Simpler views - -This release rationalises the API and implementation of the generic views, dropping the dependency on Django's `SingleObjectMixin` and `MultipleObjectMixin` classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with. - -This improvement is reflected in improved documentation for the `GenericAPIView` base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses. - -## Easier Serializers - -REST framework lets you be totally explicit regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships. - -The ability to specify exactly how you want to represent relationships is powerful, but it also introduces complexity. In order to keep things more simple, REST framework now allows you to include reverse relationships simply by including the field name in the `fields` metadata of the serializer class. - -For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class. - - class BlogSerializer(serializers.ModelSerializer): - comments = serializers.PrimaryKeyRelatedField(many=True) - - class Meta: - model = Blog - fields = ('id', 'title', 'created', 'comments') - -As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship. - - class BlogSerializer(serializers.ModelSerializer): - """ - Don't need to specify the 'comments' field explicitly anymore. - """ - class Meta: - model = Blog - fields = ('id', 'title', 'created', 'comments') - -Similarly, you can now easily include the primary key in hyperlinked relationships, simply by adding the field name to the metadata. - - class BlogSerializer(serializers.HyperlinkedModelSerializer): - """ - This is a hyperlinked serializer, which default to using - a field named 'url' as the primary identifier. - Note that we can now easily also add in the 'id' field. - """ - class Meta: - model = Blog - fields = ('url', 'id', 'title', 'created', 'comments') - -## More flexible filtering - -The `FILTER_BACKEND` setting has moved to pending deprecation, in favor of a `DEFAULT_FILTER_BACKENDS` setting that takes a *list* of filter backend classes, instead of a single filter backend class. - -The generic view `filter_backend` attribute has also been moved to pending deprecation in favor of a `filter_backends` setting. - -Being able to specify multiple filters will allow for more flexible, powerful behavior. New filter classes to handle searching and ordering of results are planned to be released shortly. - ---- - -# API Changes - -## Simplified generic view classes - -The functionality provided by `SingleObjectAPIView` and `MultipleObjectAPIView` base classes has now been moved into the base class `GenericAPIView`. The implementation of this base class is simple enough that providing subclasses for the base classes of detail and list views is somewhat unnecessary. - -Additionally the base generic view no longer inherits from Django's `SingleObjectMixin` or `MultipleObjectMixin` classes, simplifying the implementation, and meaning you don't need to cross-reference across to Django's codebase. - -Using the `SingleObjectAPIView` and `MultipleObjectAPIView` base classes continues to be supported, but will raise a `PendingDeprecationWarning`. You should instead simply use `GenericAPIView` as the base for any generic view subclasses. - -### Removed attributes - -The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unused and have now been entirely removed. - -* context_object_name -* get_context_data() -* get_context_object_name() - -The following attributes and methods, which were previously present as part of Django's generic view implementations have also been entirely removed. - -* paginator_class -* get_paginator() -* get_allow_empty() -* get_slug_field() - -There may be cases when removing these bits of API might mean you need to write a little more code if your view has highly customized behavior, but generally we believe that providing a coarser-grained API will make the views easier to work with, and is the right trade-off to make for the vast majority of cases. - -Note that the listed attributes and methods have never been a documented part of the REST framework API, and as such are not covered by the deprecation policy. - -### Simplified methods - -The `get_object` and `get_paginate_by` methods no longer take an optional queryset argument. This makes overridden these methods more obvious, and a little more simple. - -Using an optional queryset with these methods continues to be supported, but will raise a `PendingDeprecationWarning`. - -The `paginate_queryset` method no longer takes a `page_size` argument, or returns a four-tuple of pagination information. Instead it simply takes a queryset argument, and either returns a `page` object with an appropriate page size, or returns `None`, if pagination is not configured for the view. - -Using the `page_size` argument is still supported and will trigger the old-style return type, but will raise a `PendingDeprecationWarning`. - -### Deprecated attributes - -The following attributes are used to control queryset lookup, and have all been moved into a pending deprecation state. - -* pk_url_kwarg = 'pk' -* slug_url_kwarg = 'slug' -* slug_field = 'slug' - -Their usage is replaced with a single attribute: - -* lookup_field = 'pk' - -This attribute is used both as the regex keyword argument in the URL conf, and as the model field to filter against when looking up a model instance. To use non-pk based lookup, simply set the `lookup_field` argument to an alternative field, and ensure that the keyword argument in the url conf matches the field name. - -For example, a view with 'username' based lookup might look like this: - - class UserDetail(generics.RetrieveAPIView): - lookup_field = 'username' - queryset = User.objects.all() - serializer_class = UserSerializer - -And would have the following entry in the urlconf: - - url(r'^users/(?P\w+)/$', UserDetail.as_view()), - -Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`. - -The `allow_empty` attribute is also deprecated. To use `allow_empty=False` style behavior you should explicitly override `get_queryset` and raise an `Http404` on empty querysets. - -For example: - - class DisallowEmptyQuerysetMixin(object): - def get_queryset(self): - queryset = super(DisallowEmptyQuerysetMixin, self).get_queryset() - if not queryset.exists(): - raise Http404 - return queryset - -In our opinion removing lesser-used attributes like `allow_empty` helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-enforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views. - -## Simpler URL lookups - -The `HyperlinkedRelatedField` class now takes a single optional `lookup_field` argument, that replaces the `pk_url_kwarg`, `slug_url_kwarg`, and `slug_field` arguments. - -For example, you might have a field that references it's relationship by a hyperlink based on a slug field: - - account = HyperlinkedRelatedField(read_only=True, - lookup_field='slug', - view_name='account-detail') - -Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`. - -## FileUploadParser - -2.3 adds a `FileUploadParser` parser class, that supports raw file uploads, in addition to the existing multipart upload support. - -## DecimalField - -2.3 introduces a `DecimalField` serializer field, which returns `Decimal` instances. - -For most cases APIs using model fields will behave as previously, however if you are using a custom renderer, not provided by REST framework, then you may now need to add support for rendering `Decimal` instances to your renderer implementation. - -## ModelSerializers and reverse relationships - -The support for adding reverse relationships to the `fields` option on a `ModelSerializer` class means that the `get_related_field` and `get_nested_field` method signatures have now changed. - -In the unlikely event that you're providing a custom serializer class, and implementing these methods you should note the new call signature for both methods is now `(self, model_field, related_model, to_many)`. For reverse relationships `model_field` will be `None`. - -The old-style signature will continue to function but will raise a `PendingDeprecationWarning`. - -## View names and descriptions - -The mechanics of how the names and descriptions used in the browsable API are generated has been modified and cleaned up somewhat. - -If you've been customizing this behavior, for example perhaps to use `rst` markup for the browsable API, then you'll need to take a look at the implementation to see what updates you need to make. - -Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated. - ---- - -# Other notes - -## More explicit style - -The usage of `model` attribute in generic Views is still supported, but it's usage is generally being discouraged throughout the documentation, in favour of the setting the more explicit `queryset` and `serializer_class` attributes. - -For example, the following is now the recommended style for using generic views: - - class AccountListView(generics.RetrieveAPIView): - queryset = MyModel.objects.all() - serializer_class = MyModelSerializer - -Using an explicit `queryset` and `serializer_class` attributes makes the functioning of the view more clear than using the shortcut `model` attribute. - -It also makes the usage of the `get_queryset()` or `get_serializer_class()` methods more obvious. - - class AccountListView(generics.RetrieveAPIView): - serializer_class = MyModelSerializer - - def get_queryset(self): - """ - Determine the queryset dynamically, depending on the - user making the request. - - Note that overriding this method follows on more obviously now - that an explicit `queryset` attribute is the usual view style. - """ - return self.user.accounts - -## Django 1.3 support - -The 2.3.x release series will be the last series to provide compatibility with Django 1.3. - -## Version 2.2 API changes - -All API changes in 2.2 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default. - -## What comes next? - -* Support for read-write nested serializers is almost complete, and due to be released in the next few weeks. -* Extra filter backends for searching and ordering of results are planned to be added shortly. - -The next few months should see a renewed focus on addressing outstanding tickets. The 2.4 release is currently planned for around August-September. - -[viewset]: ../api-guide/viewsets.md -[router]: ../api-guide/routers.md -[part-6]: ../tutorial/6-viewsets-and-routers.md diff --git a/docs/topics/2.4-announcement.md b/docs/topics/2.4-announcement.md deleted file mode 100644 index eb1037f17..000000000 --- a/docs/topics/2.4-announcement.md +++ /dev/null @@ -1,172 +0,0 @@ -# Django REST framework 2.4 - -The 2.4 release is largely an intermediate step, tying up some outstanding issues prior to the 3.x series. - -## Version requirements - -Support for Django 1.3 has been dropped. -The lowest supported version of Django is now 1.4.2. - -The current plan is for REST framework to remain in lockstep with [Django's long-term support policy][lts-releases]. - -## Django 1.7 support - -The optional authtoken application now includes support for *both* Django 1.7 schema migrations, *and* for old-style `south` migrations. - -**If you are using authtoken, and you want to continue using `south`, you must upgrade your `south` package to version 1.0.** - -## Deprecation of `.model` view attribute - -The `.model` attribute on view classes is an optional shortcut for either or both of `.serializer_class` and `.queryset`. Its usage results in more implicit, less obvious behavior. - -The documentation has previously stated that usage of the more explicit style is prefered, and we're now taking that one step further and deprecating the usage of the `.model` shortcut. - -Doing so will mean that there are cases of API code where you'll now need to include a serializer class where you previously were just using the `.model` shortcut. However we firmly believe that it is the right trade-off to make. - -Removing the shortcut takes away an unnecessary layer of abstraction, and makes your codebase more explicit without any significant extra complexity. It also results in better consistency, as there's now only one way to set the serializer class and queryset attributes for the view, instead of two. - -The `DEFAULT_MODEL_SERIALIZER_CLASS` API setting is now also deprecated. - -## Updated test runner - -We now have a new test runner for developing against the project,, that uses the excellent [py.test](https://docs.pytest.org/) library. - -To use it make sure you have first installed the test requirements. - - pip install -r requirements-test.txt - -Then run the `runtests.py` script. - - ./runtests.py - -The new test runner also includes [flake8](https://flake8.readthedocs.io) code linting, which should help keep our coding style consistent. - -#### Test runner flags - -Run using a more concise output style. - - ./runtests -q - -Run the tests using a more concise output style, no coverage, no flake8. - - ./runtests --fast - -Don't run the flake8 code linting. - - ./runtests --nolint - -Only run the flake8 code linting, don't run the tests. - - ./runtests --lintonly - -Run the tests for a given test case. - - ./runtests MyTestCase - -Run the tests for a given test method. - - ./runtests MyTestCase.test_this_method - -Shorter form to run the tests for a given test method. - - ./runtests test_this_method - -Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input. - -## Improved viewset routing - -The `@action` and `@link` decorators were inflexible in that they only allowed additional routes to be added against instance style URLs, not against list style URLs. - -The `@action` and `@link` decorators have now been moved to pending deprecation, and the `@list_route` and `@detail_route` decorators have been introduced. - -Here's an example of using the new decorators. Firstly we have a detail-type route named "set_password" that acts on a single instance, and takes a `pk` argument in the URL. Secondly we have a list-type route named "recent_users" that acts on a queryset, and does not take any arguments in the URL. - - class UserViewSet(viewsets.ModelViewSet): - """ - A viewset that provides the standard actions - """ - queryset = User.objects.all() - serializer_class = UserSerializer - - @detail_route(methods=['post']) - def set_password(self, request, pk=None): - user = self.get_object() - serializer = PasswordSerializer(data=request.DATA) - if serializer.is_valid(): - user.set_password(serializer.data['password']) - user.save() - return Response({'status': 'password set'}) - else: - return Response(serializer.errors, - status=status.HTTP_400_BAD_REQUEST) - - @list_route() - 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) - -For more details, see the [viewsets documentation](../api-guide/viewsets.md). - -## Throttle behavior - -There's one bugfix in 2.4 that's worth calling out, as it will *invalidate existing throttle caches* when you upgrade. - -We've now fixed a typo on the `cache_format` attribute. Previously this was named `"throtte_%(scope)s_%(ident)s"`, it is now `"throttle_%(scope)s_%(ident)s"`. - -If you're concerned about the invalidation you have two options. - -* Manually pre-populate your cache with the fixed version. -* Set the `cache_format` attribute on your throttle class in order to retain the previous incorrect spelling. - -## Other features - -There are also a number of other features and bugfixes as [listed in the release notes][2-4-release-notes]. In particular these include: - -[Customizable view name and description functions][view-name-and-description-settings] for use with the browsable API, by using the `VIEW_NAME_FUNCTION` and `VIEW_DESCRIPTION_FUNCTION` settings. - -Smarter [client IP identification for throttling][client-ip-identification], with the addition of the `NUM_PROXIES` setting. - -Added the standardized `Retry-After` header to throttled responses, as per [RFC 6585](https://tools.ietf.org/html/rfc6585). This should now be used in preference to the custom `X-Throttle-Wait-Seconds` header which will be fully deprecated in 3.0. - -## Deprecations - -All API changes in 2.3 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default. - -All API changes in 2.3 that previously raised `DeprecationWarning` have now been removed entirely. - -Furter details on these deprecations is available in the [2.3 announcement][2-3-announcement]. - -## Labels and milestones - -Although not strictly part of the 2.4 release it's also worth noting here that we've been working hard towards improving our triage process. - -The [labels that we use in GitHub][github-labels] have been cleaned up, and all existing tickets triaged. Any given ticket should have one and only one label, indicating its current state. - -We've also [started using milestones][github-milestones] in order to track tickets against particular releases. - ---- - -![Labels and milestones](../img/labels-and-milestones.png) - -**Above**: *Overview of our current use of labels and milestones in GitHub.* - ---- - -We hope both of these changes will help make the management process more clear and obvious and help keep tickets well-organised and relevant. - -## Next steps - -The next planned release will be 3.0, featuring an improved and simplified serializer implementation. - -Once again, many thanks to all the generous [backers and sponsors][kickstarter-sponsors] who've helped make this possible! - -[lts-releases]: https://docs.djangoproject.com/en/stable/internals/release-process/#long-term-support-lts-releases -[2-4-release-notes]: release-notes#240 -[view-name-and-description-settings]: ../api-guide/settings#view-names-and-descriptions -[client-ip-identification]: ../api-guide/throttling#how-clients-are-identified -[2-3-announcement]: 2.3-announcement -[github-labels]: https://github.com/encode/django-rest-framework/issues -[github-milestones]: https://github.com/encode/django-rest-framework/milestones -[kickstarter-sponsors]: kickstarter-announcement#sponsors diff --git a/docs/topics/rest-framework-2-announcement.md b/docs/topics/rest-framework-2-announcement.md deleted file mode 100644 index 0ffb81a94..000000000 --- a/docs/topics/rest-framework-2-announcement.md +++ /dev/null @@ -1,97 +0,0 @@ -# Django REST framework 2.0 - -> Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result. -> -> — [Roy Fielding][cite] - ---- - -**Announcement:** REST framework 2 released - Tue 30th Oct 2012 - ---- - -REST framework 2 is an almost complete reworking of the original framework, which comprehensively addresses some of the original design issues. - -Because the latest version should be considered a re-release, rather than an incremental improvement, we've skipped a version, and called this release Django REST framework 2.0. - -This article is intended to give you a flavor of what REST framework 2 is, and why you might want to give it a try. - -## User feedback - -Before we get cracking, let's start with the hard sell, with a few bits of feedback from some early adopters… - -"Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - [Kit La Touche][quote1] - -"Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - [Ian Strachan][quote2] - -"I switched to the 2.0 branch and I don't regret it - fully refactored my code in another ½ day and it's *much* more to my tastes" - [Bruno Desthuilliers][quote3] - -Sounds good, right? Let's get into some details... - -## Serialization - -REST framework 2 includes a totally re-worked serialization engine, that was initially intended as a replacement for Django's existing inflexible fixture serialization, and which meets the following design goals: - -* A declarative serialization API, that mirrors Django's `Forms`/`ModelForms` API. -* Structural concerns are decoupled from encoding concerns. -* Able to support rendering and parsing to many formats, including both machine-readable representations and HTML forms. -* Validation that can be mapped to obvious and comprehensive error responses. -* Serializers that support both nested, flat, and partially-nested representations. -* Relationships that can be expressed as primary keys, hyperlinks, slug fields, and other custom representations. - -Mapping between the internal state of the system and external representations of that state is the core concern of building Web APIs. Designing serializers that allow the developer to do so in a flexible and obvious way is a deceptively difficult design task, and with the new serialization API we think we've pretty much nailed it. - -## Generic views - -When REST framework was initially released at the start of 2011, the current Django release was version 1.2. REST framework included a backport of Django 1.3's upcoming `View` class, but it didn't take full advantage of the generic view implementations. - -With the new release the generic views in REST framework now tie in with Django's generic views. The end result is that framework is clean, lightweight and easy to use. - -## Requests, Responses & Views - -REST framework 2 includes `Request` and `Response` classes, than are used in place of Django's existing `HttpRequest` and `HttpResponse` classes. Doing so allows logic such as parsing the incoming request or rendering the outgoing response to be supported transparently by the framework. - -The `Request`/`Response` approach leads to a much cleaner API, less logic in the view itself, and a simple, obvious request-response cycle. - -REST framework 2 also allows you to work with both function-based and class-based views. For simple API views all you need is a single `@api_view` decorator, and you're good to go. - - -## API Design - -Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independently of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions. - -## The Browsable API - -Django REST framework's most unique feature is the way it is able to serve up both machine-readable representations, and a fully browsable HTML representation to the same endpoints. - -Browsable Web APIs are easier to work with, visualize and debug, and generally makes it easier and more frictionless to inspect and work with. - -With REST framework 2, the browsable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with. - -There are also some functionality improvements - actions such as as `POST` and `DELETE` will only display if the user has the appropriate permissions. - -![Browsable API][image] - -**Image above**: An example of the browsable API in REST framework 2 - -## Documentation - -As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling. - -We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great. - -## Summary - -In short, we've engineered the hell outta this thing, and we're incredibly proud of the result. - -If you're interested please take a browse around the documentation. [The tutorial][tut] is a great place to get started. - -There's also a [live sandbox version of the tutorial API][sandbox] available for testing. - -[cite]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-724 -[quote1]: https://twitter.com/kobutsu/status/261689665952833536 -[quote2]: https://groups.google.com/d/msg/django-rest-framework/heRGHzG6BWQ/ooVURgpwVC0J -[quote3]: https://groups.google.com/d/msg/django-rest-framework/flsXbvYqRoY/9lSyntOf5cUJ -[image]: ../img/quickstart.png -[tut]: ../tutorial/1-serialization.md -[sandbox]: https://restframework.herokuapp.com/ diff --git a/docs/topics/writable-nested-serializers.md b/docs/topics/writable-nested-serializers.md index cab700e5b..a39feb18c 100644 --- a/docs/topics/writable-nested-serializers.md +++ b/docs/topics/writable-nested-serializers.md @@ -12,17 +12,17 @@ Nested data structures are easy enough to work with if they're read-only - simpl *Example of a **read-only** nested serializer. Nothing complex to worry about here.* - class ToDoItemSerializer(serializers.ModelSerializer): - class Meta: - model = ToDoItem - fields = ('text', 'is_completed') + class ToDoItemSerializer(serializers.ModelSerializer): + class Meta: + model = ToDoItem + fields = ('text', 'is_completed') - class ToDoListSerializer(serializers.ModelSerializer): - items = ToDoItemSerializer(many=True, read_only=True) + class ToDoListSerializer(serializers.ModelSerializer): + items = ToDoItemSerializer(many=True, read_only=True) - class Meta: - model = ToDoList - fields = ('title', 'items') + class Meta: + model = ToDoList + fields = ('title', 'items') Some example output from our serializer. diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 7a9b7cbd8..aa94eeb0e 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -299,18 +299,18 @@ Now we can start up a sample server that serves our snippets. Quit out of the shell... - quit() + quit() ...and start up Django's development server. - python manage.py runserver + python manage.py runserver - Validating models... + Validating models... - 0 errors found - Django version 1.11, using settings 'tutorial.settings' - Development server is running at http://127.0.0.1:8000/ - Quit the server with CONTROL-C. + 0 errors found + Django version 1.11, using settings 'tutorial.settings' + Development server is running at http://127.0.0.1:8000/ + Quit the server with CONTROL-C. In another terminal window, we can test the server. diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 9af9c0940..ef5b45c90 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -83,7 +83,7 @@ We'll also add a couple of views to `views.py`. We'd like to just use read-only Make sure to also import the `UserSerializer` class - from snippets.serializers import UserSerializer + from snippets.serializers import UserSerializer Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `snippets/urls.py`. diff --git a/mkdocs.yml b/mkdocs.yml index e5e99091a..70b8c02ad 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -59,21 +59,22 @@ pages: - 'Browser Enhancements': 'topics/browser-enhancements.md' - 'The Browsable API': 'topics/browsable-api.md' - 'REST, Hypermedia & HATEOAS': 'topics/rest-hypermedia-hateoas.md' - - 'Third Party Packages': 'topics/third-party-packages.md' - - 'Tutorials and Resources': 'topics/tutorials-and-resources.md' - - 'Contributing to REST framework': 'topics/contributing.md' - - 'Project management': 'topics/project-management.md' - - 'Jobs': 'topics/jobs.md' - - '3.0 Announcement': 'topics/3.0-announcement.md' - - '3.1 Announcement': 'topics/3.1-announcement.md' - - '3.2 Announcement': 'topics/3.2-announcement.md' - - '3.3 Announcement': 'topics/3.3-announcement.md' - - '3.4 Announcement': 'topics/3.4-announcement.md' - - '3.5 Announcement': 'topics/3.5-announcement.md' - - '3.6 Announcement': 'topics/3.6-announcement.md' - - '3.7 Announcement': 'topics/3.7-announcement.md' - - '3.8 Announcement': 'topics/3.8-announcement.md' - - 'Kickstarter Announcement': 'topics/kickstarter-announcement.md' - - 'Mozilla Grant': 'topics/mozilla-grant.md' - - 'Funding': 'topics/funding.md' - - 'Release Notes': 'topics/release-notes.md' + - Community: + - 'Tutorials and Resources': 'community/tutorials-and-resources.md' + - 'Third Party Packages': 'community/third-party-packages.md' + - 'Contributing to REST framework': 'community/contributing.md' + - 'Project management': 'community/project-management.md' + - 'Release Notes': 'community/release-notes.md' + - '3.8 Announcement': 'community/3.8-announcement.md' + - '3.7 Announcement': 'community/3.7-announcement.md' + - '3.6 Announcement': 'community/3.6-announcement.md' + - '3.5 Announcement': 'community/3.5-announcement.md' + - '3.4 Announcement': 'community/3.4-announcement.md' + - '3.3 Announcement': 'community/3.3-announcement.md' + - '3.2 Announcement': 'community/3.2-announcement.md' + - '3.1 Announcement': 'community/3.1-announcement.md' + - '3.0 Announcement': 'community/3.0-announcement.md' + - 'Kickstarter Announcement': 'community/kickstarter-announcement.md' + - 'Mozilla Grant': 'community/mozilla-grant.md' + - 'Funding': 'community/funding.md' + - 'Jobs': 'community/jobs.md'