From ec076a00786c6b89a55b6ffe2556bb3b777100f5 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 31 Mar 2013 11:36:58 +0100 Subject: Add viewsets/routers to indexs etc --- docs/api-guide/viewsets-routers.md | 109 +++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 docs/api-guide/viewsets-routers.md (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets-routers.md b/docs/api-guide/viewsets-routers.md new file mode 100644 index 00000000..817e1b8f --- /dev/null +++ b/docs/api-guide/viewsets-routers.md @@ -0,0 +1,109 @@ + + +# ViewSets & Routers + +> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code. +> +> — [Ruby on Rails Documentation][cite] + +Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests. + +Conversely, Django stops short of automatically generating URLs, and requires you to explicitly manage your URL configuration. + +REST framework adds support for automatic URL routing, which provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs. + +# ViewSets + +Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'. + +A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`. + +The method handlers for a `ViewSet` are only bound to the corresponding actions at the point of finalizing the view, using the `.as_view()` method. + +Typically, rather than exlicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you. + +## Example + +Let's define a simple viewset that can be used to listing or retrieving all the users in the system. + + class UserViewSet(ViewSet): + """ + A simple ViewSet that for listing or retrieving users. + """ + queryset = User.objects.all() + + def list(self, request): + serializer = UserSerializer(self.queryset, many=True) + return Response(serializer.data) + + def retrieve(self, request, pk=None): + user = get_object_or_404(self.queryset, pk=pk) + serializer = UserSerializer(user) + return Response(serializer.data) + +If we need to, we can bind this viewset into two seperate views, like so: + + user_list = UserViewSet.as_view({'get': 'list'}) + user_detail = UserViewSet.as_view({'get': 'retrieve'}) + +Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. + +# API Reference + +## ViewSet + +The `ViewSet` class inherits from `APIView`. You can use any of the standard attributes such as `permission_classes`, `authentication_classes` in order to control the API policy on the viewset. + +The `ViewSet` class does not provide any implementations of actions. In order to use a `ViewSet` class you'll override the class and define the action implementations explicitly. + +## ModelViewSet + +The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the + +The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, and `.destroy()`. + +## ReadOnlyModelViewSet + +The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`. + +# Custom ViewSet base classes + +Any standard `View` class can be turned into a `ViewSet` class by mixing in `ViewSetMixin`. You can use this to define your own base classes. + +For example, the definition of `ModelViewSet` looks like this: + + class ModelViewSet(mixins.CreateModelMixin, + mixins.RetrieveModelMixin, + mixins.UpdateModelMixin, + mixins.DestroyModelMixin, + mixins.ListModelMixin, + viewsets.ViewSetMixin, + generics.GenericAPIView): + """ + A viewset that provides actions for `create`, `retrieve`, + `update`, `destroy` and `list` actions. + + To use it, override the class and set the `.queryset` + and `.serializer_class` attributes. + """ + pass + +By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple views across your API. + +Note the that `ViewSetMixin` class can also be applied to the standard Django `View` class if you want to use REST framework's automatic routing, but don't want to use it's permissions, authentication and other API policies. + +--- + +# Routers + +Routers provide a convenient and simple shortcut for wiring up your application's URLs. + + router = routers.DefaultRouter() + router.register('^/', APIRoot, 'api-root') + router.register('^users/', UserViewSet, 'user') + router.register('^groups/', GroupViewSet, 'group') + router.register('^accounts/', AccountViewSet, 'account') + + urlpatterns = router.urlpatterns + +[cite]: http://guides.rubyonrails.org/routing.html \ No newline at end of file -- cgit v1.2.3 From c785628300d2b7cce63862a18915c537f8a3ab24 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 4 Apr 2013 20:00:44 +0100 Subject: Fleshing out viewsets/routers --- docs/api-guide/viewsets-routers.md | 50 +++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets-routers.md b/docs/api-guide/viewsets-routers.md index 817e1b8f..7813c00d 100644 --- a/docs/api-guide/viewsets-routers.md +++ b/docs/api-guide/viewsets-routers.md @@ -48,6 +48,14 @@ If we need to, we can bind this viewset into two seperate views, like so: Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. +There are two main advantages of using a `ViewSet` class over using a `View` class. + +* Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views. +* By using routers, we no longer need to deal with wiring up the URL conf ourselves. + +Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout. + + # API Reference ## ViewSet @@ -62,10 +70,50 @@ The `ModelViewSet` class inherits from `GenericAPIView` and includes implementat The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, and `.destroy()`. +#### Example + +Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: + + class AccountViewSet(viewsets.ModelViewSet): + """ + A simple ViewSet for viewing and editing accounts. + """ + queryset = Account.objects.all() + serializer_class = AccountSerializer + permission_classes = [IsAccountAdminOrReadOnly] + +Note that you can use any of the standard attributes or method overrides provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically determines the queryset it should operate on, you might do something like this: + + class AccountViewSet(viewsets.ModelViewSet): + """ + A simple ViewSet for viewing and editing the accounts + associated with the user. + """ + serializer_class = AccountSerializer + permission_classes = [IsAccountAdminOrReadOnly] + + def get_queryset(self): + return request.user.accounts.all() + +Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes. + ## ReadOnlyModelViewSet The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`. +#### Example + +As with `ModelViewSet`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: + + class AccountViewSet(viewsets.ReadOnlyModelViewSet): + """ + A simple ViewSet for viewing accounts. + """ + queryset = Account.objects.all() + serializer_class = AccountSerializer + +Again, as with `ModelViewSet`, you can use any of the standard attributes and method overrides available to `GenericAPIView`. + # Custom ViewSet base classes Any standard `View` class can be turned into a `ViewSet` class by mixing in `ViewSetMixin`. You can use this to define your own base classes. @@ -90,7 +138,7 @@ For example, the definition of `ModelViewSet` looks like this: By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple views across your API. -Note the that `ViewSetMixin` class can also be applied to the standard Django `View` class if you want to use REST framework's automatic routing, but don't want to use it's permissions, authentication and other API policies. +For advanced usage, it's worth noting the that `ViewSetMixin` class can also be applied to the standard Django `View` class. Doing so allows you to use REST framework's automatic routing, but don't want to use it's permissions, authentication and other API policies. --- -- cgit v1.2.3 From 371698331c979305b5684f864ee6bf5b6d11a44e Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 4 Apr 2013 22:24:30 +0100 Subject: Tweaks --- docs/api-guide/generic-views.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 20f1be63..caf6f53c 100644 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -208,14 +208,14 @@ Should be mixed in with [SingleObjectAPIView]. Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance. +Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests. + If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response. If an object is created, for example when making a `DELETE` request followed by a `PUT` request to the same URL, this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response. -A boolean `partial` keyword argument may be supplied to the `.update()` method. If `partial` is set to `True`, all fields for the update will be optional. This allows support for HTTP `PATCH` requests. - Should be mixed in with [SingleObjectAPIView]. ## DestroyModelMixin -- cgit v1.2.3 From 027792c981b1442a018e382a6fa2e58496b0b750 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 9 Apr 2013 11:54:51 +0100 Subject: Viewsets and routers in seperate docs --- docs/api-guide/routers.md | 27 +++++++ docs/api-guide/viewsets-routers.md | 157 ------------------------------------- docs/api-guide/viewsets.md | 145 ++++++++++++++++++++++++++++++++++ 3 files changed, 172 insertions(+), 157 deletions(-) create mode 100644 docs/api-guide/routers.md delete mode 100644 docs/api-guide/viewsets-routers.md create mode 100644 docs/api-guide/viewsets.md (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md new file mode 100644 index 00000000..dbb352fe --- /dev/null +++ b/docs/api-guide/routers.md @@ -0,0 +1,27 @@ + + +# Routers + +> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code. +> +> — [Ruby on Rails Documentation][cite] + +Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests. + +Conversely, Django stops short of automatically generating URLs, and requires you to explicitly manage your URL configuration. + +REST framework adds support for automatic URL routing, which provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs. + +# API Guide + +Routers provide a convenient and simple shortcut for wiring up your application's URLs. + + router = routers.DefaultRouter() + router.register('^/', APIRoot, 'api-root') + router.register('^users/', UserViewSet, 'user') + router.register('^groups/', GroupViewSet, 'group') + router.register('^accounts/', AccountViewSet, 'account') + + urlpatterns = router.urlpatterns + +[cite]: http://guides.rubyonrails.org/routing.html \ No newline at end of file diff --git a/docs/api-guide/viewsets-routers.md b/docs/api-guide/viewsets-routers.md deleted file mode 100644 index 7813c00d..00000000 --- a/docs/api-guide/viewsets-routers.md +++ /dev/null @@ -1,157 +0,0 @@ - - -# ViewSets & Routers - -> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code. -> -> — [Ruby on Rails Documentation][cite] - -Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests. - -Conversely, Django stops short of automatically generating URLs, and requires you to explicitly manage your URL configuration. - -REST framework adds support for automatic URL routing, which provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs. - -# ViewSets - -Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'. - -A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`. - -The method handlers for a `ViewSet` are only bound to the corresponding actions at the point of finalizing the view, using the `.as_view()` method. - -Typically, rather than exlicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you. - -## Example - -Let's define a simple viewset that can be used to listing or retrieving all the users in the system. - - class UserViewSet(ViewSet): - """ - A simple ViewSet that for listing or retrieving users. - """ - queryset = User.objects.all() - - def list(self, request): - serializer = UserSerializer(self.queryset, many=True) - return Response(serializer.data) - - def retrieve(self, request, pk=None): - user = get_object_or_404(self.queryset, pk=pk) - serializer = UserSerializer(user) - return Response(serializer.data) - -If we need to, we can bind this viewset into two seperate views, like so: - - user_list = UserViewSet.as_view({'get': 'list'}) - user_detail = UserViewSet.as_view({'get': 'retrieve'}) - -Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. - -There are two main advantages of using a `ViewSet` class over using a `View` class. - -* Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views. -* By using routers, we no longer need to deal with wiring up the URL conf ourselves. - -Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout. - - -# API Reference - -## ViewSet - -The `ViewSet` class inherits from `APIView`. You can use any of the standard attributes such as `permission_classes`, `authentication_classes` in order to control the API policy on the viewset. - -The `ViewSet` class does not provide any implementations of actions. In order to use a `ViewSet` class you'll override the class and define the action implementations explicitly. - -## ModelViewSet - -The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the - -The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, and `.destroy()`. - -#### Example - -Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: - - class AccountViewSet(viewsets.ModelViewSet): - """ - A simple ViewSet for viewing and editing accounts. - """ - queryset = Account.objects.all() - serializer_class = AccountSerializer - permission_classes = [IsAccountAdminOrReadOnly] - -Note that you can use any of the standard attributes or method overrides provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically determines the queryset it should operate on, you might do something like this: - - class AccountViewSet(viewsets.ModelViewSet): - """ - A simple ViewSet for viewing and editing the accounts - associated with the user. - """ - serializer_class = AccountSerializer - permission_classes = [IsAccountAdminOrReadOnly] - - def get_queryset(self): - return request.user.accounts.all() - -Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes. - -## ReadOnlyModelViewSet - -The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`. - -#### Example - -As with `ModelViewSet`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: - - class AccountViewSet(viewsets.ReadOnlyModelViewSet): - """ - A simple ViewSet for viewing accounts. - """ - queryset = Account.objects.all() - serializer_class = AccountSerializer - -Again, as with `ModelViewSet`, you can use any of the standard attributes and method overrides available to `GenericAPIView`. - -# Custom ViewSet base classes - -Any standard `View` class can be turned into a `ViewSet` class by mixing in `ViewSetMixin`. You can use this to define your own base classes. - -For example, the definition of `ModelViewSet` looks like this: - - class ModelViewSet(mixins.CreateModelMixin, - mixins.RetrieveModelMixin, - mixins.UpdateModelMixin, - mixins.DestroyModelMixin, - mixins.ListModelMixin, - viewsets.ViewSetMixin, - generics.GenericAPIView): - """ - A viewset that provides actions for `create`, `retrieve`, - `update`, `destroy` and `list` actions. - - To use it, override the class and set the `.queryset` - and `.serializer_class` attributes. - """ - pass - -By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple views across your API. - -For advanced usage, it's worth noting the that `ViewSetMixin` class can also be applied to the standard Django `View` class. Doing so allows you to use REST framework's automatic routing, but don't want to use it's permissions, authentication and other API policies. - ---- - -# Routers - -Routers provide a convenient and simple shortcut for wiring up your application's URLs. - - router = routers.DefaultRouter() - router.register('^/', APIRoot, 'api-root') - router.register('^users/', UserViewSet, 'user') - router.register('^groups/', GroupViewSet, 'group') - router.register('^accounts/', AccountViewSet, 'account') - - urlpatterns = router.urlpatterns - -[cite]: http://guides.rubyonrails.org/routing.html \ No newline at end of file diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md new file mode 100644 index 00000000..83b486dd --- /dev/null +++ b/docs/api-guide/viewsets.md @@ -0,0 +1,145 @@ + + +# ViewSets + +Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'. + +A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`. + +The method handlers for a `ViewSet` are only bound to the corresponding actions at the point of finalizing the view, using the `.as_view()` method. + +Typically, rather than exlicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you. + +## Example + +Let's define a simple viewset that can be used to listing or retrieving all the users in the system. + + class UserViewSet(ViewSet): + """ + A simple ViewSet that for listing or retrieving users. + """ + queryset = User.objects.all() + + def list(self, request): + serializer = UserSerializer(self.queryset, many=True) + return Response(serializer.data) + + def retrieve(self, request, pk=None): + user = get_object_or_404(self.queryset, pk=pk) + serializer = UserSerializer(user) + return Response(serializer.data) + +If we need to, we can bind this viewset into two seperate views, like so: + + user_list = UserViewSet.as_view({'get': 'list'}) + user_detail = UserViewSet.as_view({'get': 'retrieve'}) + +Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. + +There are two main advantages of using a `ViewSet` class over using a `View` class. + +* Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views. +* By using routers, we no longer need to deal with wiring up the URL conf ourselves. + +Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout. + + +# API Reference + +## ViewSet + +The `ViewSet` class inherits from `APIView`. You can use any of the standard attributes such as `permission_classes`, `authentication_classes` in order to control the API policy on the viewset. + +The `ViewSet` class does not provide any implementations of actions. In order to use a `ViewSet` class you'll override the class and define the action implementations explicitly. + +## ModelViewSet + +The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the + +The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, and `.destroy()`. + +#### Example + +Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: + + class AccountViewSet(viewsets.ModelViewSet): + """ + A simple ViewSet for viewing and editing accounts. + """ + queryset = Account.objects.all() + serializer_class = AccountSerializer + permission_classes = [IsAccountAdminOrReadOnly] + +Note that you can use any of the standard attributes or method overrides provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically determines the queryset it should operate on, you might do something like this: + + class AccountViewSet(viewsets.ModelViewSet): + """ + A simple ViewSet for viewing and editing the accounts + associated with the user. + """ + serializer_class = AccountSerializer + permission_classes = [IsAccountAdminOrReadOnly] + + def get_queryset(self): + return request.user.accounts.all() + +Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes. + +## ReadOnlyModelViewSet + +The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`. + +#### Example + +As with `ModelViewSet`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: + + class AccountViewSet(viewsets.ReadOnlyModelViewSet): + """ + A simple ViewSet for viewing accounts. + """ + queryset = Account.objects.all() + serializer_class = AccountSerializer + +Again, as with `ModelViewSet`, you can use any of the standard attributes and method overrides available to `GenericAPIView`. + +# Custom ViewSet base classes + +Any standard `View` class can be turned into a `ViewSet` class by mixing in `ViewSetMixin`. You can use this to define your own base classes. + +For example, the definition of `ModelViewSet` looks like this: + + class ModelViewSet(mixins.CreateModelMixin, + mixins.RetrieveModelMixin, + mixins.UpdateModelMixin, + mixins.DestroyModelMixin, + mixins.ListModelMixin, + viewsets.ViewSetMixin, + generics.GenericAPIView): + """ + A viewset that provides actions for `create`, `retrieve`, + `update`, `destroy` and `list` actions. + + To use it, override the class and set the `.queryset` + and `.serializer_class` attributes. + """ + pass + +By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple views across your API. + +For advanced usage, it's worth noting the that `ViewSetMixin` class can also be applied to the standard Django `View` class. Doing so allows you to use REST framework's automatic routing, but don't want to use it's permissions, authentication and other API policies. + +--- + +# Routers + +Routers provide a convenient and simple shortcut for wiring up your application's URLs. + + router = routers.DefaultRouter() + router.register('^/', APIRoot, 'api-root') + router.register('^users/', UserViewSet, 'user') + router.register('^groups/', GroupViewSet, 'group') + router.register('^accounts/', AccountViewSet, 'account') + + urlpatterns = router.urlpatterns + +[cite]: http://guides.rubyonrails.org/routing.html \ No newline at end of file -- cgit v1.2.3 From d75cebf75696602170a9d282d4b114d01d6e5d8e Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 11 Apr 2013 15:48:41 +0100 Subject: Remove router bit from viewset docs --- docs/api-guide/viewsets.md | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 83b486dd..cf6ae33b 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -2,6 +2,11 @@ # ViewSets +> After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. +> +> — [Ruby on Rails Documentation][cite] + + Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'. A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`. @@ -128,18 +133,4 @@ By creating your own base `ViewSet` classes, you can provide common behavior tha For advanced usage, it's worth noting the that `ViewSetMixin` class can also be applied to the standard Django `View` class. Doing so allows you to use REST framework's automatic routing, but don't want to use it's permissions, authentication and other API policies. ---- - -# Routers - -Routers provide a convenient and simple shortcut for wiring up your application's URLs. - - router = routers.DefaultRouter() - router.register('^/', APIRoot, 'api-root') - router.register('^users/', UserViewSet, 'user') - router.register('^groups/', GroupViewSet, 'group') - router.register('^accounts/', AccountViewSet, 'account') - - urlpatterns = router.urlpatterns - [cite]: http://guides.rubyonrails.org/routing.html \ No newline at end of file -- cgit v1.2.3 From ad436d966fa9ee2f5817aa5c26612c82558c4262 Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Mon, 15 Apr 2013 12:40:18 +0200 Subject: Add DecimalField support --- docs/api-guide/fields.md | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 42f89f46..e117c370 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -248,6 +248,12 @@ A floating point representation. Corresponds to `django.db.models.fields.FloatField`. +## DecimalField + +A decimal representation. + +Corresponds to `django.db.models.fields.DecimalField`. + ## FileField A file representation. Performs Django's standard FileField validation. -- cgit v1.2.3 From b94da2468cdda6b0ad491574d35097d0e336ea7f Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 24 Apr 2013 22:40:24 +0100 Subject: Various clean up and lots of docs --- docs/api-guide/filtering.md | 11 +-- docs/api-guide/generic-views.md | 194 +++++++++++++++++++++++++--------------- docs/api-guide/pagination.md | 3 +- docs/api-guide/renderers.md | 2 +- docs/api-guide/routers.md | 49 +++++++--- docs/api-guide/viewsets.md | 27 +++--- 6 files changed, 182 insertions(+), 104 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index ed946368..805d82f8 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -8,7 +8,7 @@ The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset. -The simplest way to filter the queryset of any view that subclasses `MultipleObjectAPIView` is to override the `.get_queryset()` method. +The simplest way to filter the queryset of any view that subclasses `GenericAPIView` is to override the `.get_queryset()` method. Overriding this method allows you to customize the queryset returned by the view in a number of different ways. @@ -21,7 +21,6 @@ You can do so by filtering based on the value of `request.user`. For example: class PurchaseList(generics.ListAPIView) - model = Purchase serializer_class = PurchaseSerializer def get_queryset(self): @@ -44,7 +43,6 @@ For example if your URL config contained an entry like this: You could then write a view that returned a purchase queryset filtered by the username portion of the URL: class PurchaseList(generics.ListAPIView) - model = Purchase serializer_class = PurchaseSerializer def get_queryset(self): @@ -62,7 +60,6 @@ A final example of filtering the initial queryset would be to determine the init We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL: class PurchaseList(generics.ListAPIView) - model = Purchase serializer_class = PurchaseSerializer def get_queryset(self): @@ -100,7 +97,7 @@ You must also set the filter backend to `DjangoFilterBackend` in your settings: If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, listing the set of fields you wish to filter against. class ProductList(generics.ListAPIView): - model = Product + queryset = Product.objects.all() serializer_class = ProductSerializer filter_fields = ('category', 'in_stock') @@ -120,7 +117,7 @@ For more advanced filtering requirements you can specify a `FilterSet` class tha fields = ['category', 'in_stock', 'min_price', 'max_price'] class ProductList(generics.ListAPIView): - model = Product + queryset = Product.objects.all() serializer_class = ProductSerializer filter_class = ProductFilter @@ -183,4 +180,4 @@ For example: [cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters [django-filter]: https://github.com/alex/django-filter [django-filter-docs]: https://django-filter.readthedocs.org/en/latest/index.html -[nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py \ No newline at end of file +[nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index c73bc700..9d09af7f 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -18,7 +18,7 @@ If the generic views don't suit the needs of your API, you can drop down to usin Typically when using the generic views, you'll override the view, and set several class attributes. class UserList(generics.ListCreateAPIView): - model = User + queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAdminUser,) paginate_by = 100 @@ -26,17 +26,16 @@ Typically when using the generic views, you'll override the view, and set severa For more complex cases you might also want to override various methods on the view class. For example. class UserList(generics.ListCreateAPIView): - model = User + queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAdminUser,) - def get_paginate_by(self, queryset): + def get_paginate_by(self): """ Use smaller pagination for HTML representations. """ - page_size_param = self.request.QUERY_PARAMS.get('page_size') - if page_size_param: - return int(page_size_param) + self.request.accepted_renderer.format == 'html': + return 20 return 100 For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something the following entry. @@ -47,6 +46,114 @@ For very simple cases you might want to pass through any class attributes using # API Reference +## GenericAPIView + +This class extends REST framework's `APIView` class, adding commonly required behavior for standard list and detail views. + +Each of the concrete generic views provided is built by combining `GenericAPIView`, with one or more mixin classes. + +### Attributes + +**Basic settings**: + +The following attributes control the basic view behavior. + +* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. +* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method. +* `lookup_field` - The field that should be used to lookup individual model instances. Defaults to `'pk'`. The URL conf should include a keyword argument corresponding to this value. More complex lookup styles can be supported by overriding the `get_object()` method. + +**Pagination**: + +The following attibutes are used to control pagination when used with list views. + +* `paginate_by` - The size of pages to use with paginated data. If set to `None` then pagination is turned off. If unset this uses the same value as the `PAGINATE_BY` setting, which defaults to `None`. +* `paginate_by_param` - The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`. +* `pagination_serializer_class` - The pagination serializer class to use when determining the style of paginated responses. Defaults to the same value as the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting. +* `page_kwarg` - The name of a URL kwarg or URL query parameter which can be used by the client to control which page is requested. Defaults to `'page'`. + +**Other**: + +* `filter_backend` - The filter backend class that should be used for filtering the queryset. Defaults to the same value as the `FILTER_BACKEND` setting. +* `allow_empty` - Determines if an empty list should successfully display zero results, or return a 404 response. Defaults to `True`, meaning empty lists will return sucessful `200 OK` responses, with zero results. +* `model` - This shortcut may be used instead of setting either (or both) of the `queryset`/`serializer_class` attributes, although using the explicit style is generally preferred. If used instead of `serializer_class`, then then `DEFAULT_MODEL_SERIALIZER_CLASS` setting will determine the base serializer class. + +### Methods + +**Base methods**: + +#### `get_queryset(self)` + +Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the `queryset` attribute, or the default queryset for the model if the `model` shortcut is being used. + +May be overridden to provide dynamic behavior such as returning a queryset that is specific to the user making the request. + +For example: + + def get_queryset(self): + return self.user.accounts.all() + +#### `get_object(self)` + +Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset. + +May be overridden to provide more complex behavior such as object lookups based on more than one URL kwarg. + +For example: + + def get_object(self): + queryset = self.get_queryset() + filter = {} + for field in self.multiple_lookup_fields: + filter[field] = self.kwargs[field] + return get_object_or_404(queryset, **filter) + +#### `get_serializer_class(self)` + +Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute, or dynamically generating a serializer class if the `model` shortcut is being used. + +May be override to provide dynamic behavior such as using different serializers for read and write operations, or providing different serializers to different types of uesr. + +For example: + + def get_serializer_class(self): + if self.request.user.is_staff: + return FullAccountSerializer + return BasicAccountSerializer + +#### `get_paginate_by(self)` + +Returna the page size to use with pagination. By default this uses the `paginate_by` attribute, and may be overridden by the cient if the `paginate_by_param` attribute is set. + +You may want to override this method to provide more complex behavior such as modifying page sizes based on the media type of the response. + +For example: + + def get_paginate_by(self): + self.request.accepted_renderer.format == 'html': + return 20 + return 100 + +**Save hooks**: + +The following methods are provided as placeholder interfaces. They contain empty implementations and are not called directly by `GenericAPIView`, but they are overridden and used by some of the mixin classes. + +* `pre_save(self, obj)` - A hook that is called before saving an object. +* `post_save(self, obj, created=False)` - A hook that is called after saving an object. + +**Other methods**: + +You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`. + +* `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys. +* `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False)` - Returns a serializer instance. +* `get_pagination_serializer(self, page)` - Returns a serializer instance to use with paginated data. +* `paginate_queryset(self, queryset, page_size)` - Paginate a queryset. +* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backend is in use. + +--- + +# Concrete View Classes + The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior. ## CreateAPIView @@ -63,7 +170,7 @@ Used for **read-only** endpoints to represent a **collection of model instances* Provides a `get` method handler. -Extends: [MultipleObjectAPIView], [ListModelMixin] +Extends: [GenericAPIView], [ListModelMixin] ## RetrieveAPIView @@ -71,7 +178,7 @@ Used for **read-only** endpoints to represent a **single model instance**. Provides a `get` method handler. -Extends: [SingleObjectAPIView], [RetrieveModelMixin] +Extends: [GenericAPIView], [RetrieveModelMixin] ## DestroyAPIView @@ -79,7 +186,7 @@ Used for **delete-only** endpoints for a **single model instance**. Provides a `delete` method handler. -Extends: [SingleObjectAPIView], [DestroyModelMixin] +Extends: [GenericAPIView], [DestroyModelMixin] ## UpdateAPIView @@ -87,7 +194,7 @@ Used for **update-only** endpoints for a **single model instance**. Provides `put` and `patch` method handlers. -Extends: [SingleObjectAPIView], [UpdateModelMixin] +Extends: [GenericAPIView], [UpdateModelMixin] ## ListCreateAPIView @@ -95,7 +202,7 @@ Used for **read-write** endpoints to represent a **collection of model instances Provides `get` and `post` method handlers. -Extends: [MultipleObjectAPIView], [ListModelMixin], [CreateModelMixin] +Extends: [GenericAPIView], [ListModelMixin], [CreateModelMixin] ## RetrieveUpdateAPIView @@ -103,7 +210,7 @@ Used for **read or update** endpoints to represent a **single model instance**. Provides `get`, `put` and `patch` method handlers. -Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin] +Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin] ## RetrieveDestroyAPIView @@ -111,7 +218,7 @@ Used for **read or delete** endpoints to represent a **single model instance**. Provides `get` and `delete` method handlers. -Extends: [SingleObjectAPIView], [RetrieveModelMixin], [DestroyModelMixin] +Extends: [GenericAPIView], [RetrieveModelMixin], [DestroyModelMixin] ## RetrieveUpdateDestroyAPIView @@ -119,62 +226,13 @@ Used for **read-write-delete** endpoints to represent a **single model instance* Provides `get`, `put`, `patch` and `delete` method handlers. -Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin] - ---- - -# Base views - -Each of the generic views provided is built by combining one of the base views below, with one or more mixin classes. - -## GenericAPIView - -Extends REST framework's `APIView` class, adding support for serialization of model instances and model querysets. - -**Methods**: - -* `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys. -* `get_serializer_class(self)` - Returns the class that should be used for the serializer. -* `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False)` - Returns a serializer instance. -* `pre_save(self, obj)` - A hook that is called before saving an object. -* `post_save(self, obj, created=False)` - A hook that is called after saving an object. - - -**Attributes**: - -* `model` - The model that should be used for this view. Used as a fallback for determining the serializer if `serializer_class` is not set, and as a fallback for determining the queryset if `queryset` is not set. Otherwise not required. -* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. If unset, this defaults to creating a serializer class using `self.model`, with the `DEFAULT_MODEL_SERIALIZER_CLASS` setting as the base serializer class. - -## MultipleObjectAPIView - -Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [MultipleObjectMixin]. - -**See also:** ccbv.co.uk documentation for [MultipleObjectMixin][multiple-object-mixin-classy]. - -**Attributes**: - -* `queryset` - The queryset that should be used for returning objects from this view. If unset, defaults to the default queryset manager for `self.model`. -* `paginate_by` - The size of pages to use with paginated data. If set to `None` then pagination is turned off. If unset this uses the same value as the `PAGINATE_BY` setting, which defaults to `None`. -* `paginate_by_param` - The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`. - -## SingleObjectAPIView - -Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [SingleObjectMixin]. - -**See also:** ccbv.co.uk documentation for [SingleObjectMixin][single-object-mixin-classy]. - -**Attributes**: - -* `queryset` - The queryset that should be used when retrieving an object from this view. If unset, defaults to the default queryset manager for `self.model`. -* `pk_kwarg` - The URL kwarg that should be used to look up objects by primary key. Defaults to `'pk'`. [Can only be set to non-default on Django 1.4+] -* `slug_url_kwarg` - The URL kwarg that should be used to look up objects by a slug. Defaults to `'slug'`. [Can only be set to non-default on Django 1.4+] -* `slug_field` - The field on the model that should be used to look up objects by a slug. If used, this should typically be set to a field with `unique=True`. Defaults to `'slug'`. +Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin] --- # Mixins -The mixin classes provide the actions that are used to provide the basic view behaviour. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behaviour. +The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behavior. ## ListModelMixin @@ -182,7 +240,7 @@ Provides a `.list(request, *args, **kwargs)` method, that implements listing a q If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated. -If the queryset is empty this returns a `200 OK` reponse, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`. +If the queryset is empty this returns a `200 OK` response, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`. Should be mixed in with [MultipleObjectAPIView]. @@ -227,14 +285,8 @@ If an object is deleted this returns a `204 No Content` response, otherwise it w Should be mixed in with [SingleObjectAPIView]. [cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views -[MultipleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-multiple-object/ -[SingleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-single-object/ -[multiple-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.list/MultipleObjectMixin/ -[single-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.detail/SingleObjectMixin/ [GenericAPIView]: #genericapiview -[SingleObjectAPIView]: #singleobjectapiview -[MultipleObjectAPIView]: #multipleobjectapiview [ListModelMixin]: #listmodelmixin [CreateModelMixin]: #createmodelmixin [RetrieveModelMixin]: #retrievemodelmixin diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 13d4760a..912ce41b 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -93,7 +93,8 @@ The default pagination style may be set globally, using the `DEFAULT_PAGINATION_ You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view. class PaginatedListView(ListAPIView): - model = ExampleModel + queryset = ExampleModel.objects.all() + serializer_class = ExampleModelSerializer paginate_by = 10 paginate_by_param = 'page_size' diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 3c8396aa..e2fc36ca 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -127,7 +127,7 @@ An example of a view that uses `TemplateHTMLRenderer`: """ A view that returns a templated HTML representations of a given user. """ - model = Users + queryset = User.objects.all() renderer_classes = (TemplateHTMLRenderer,) def get(self, request, *args, **kwargs) diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index dbb352fe..7411bd7b 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -8,20 +8,49 @@ Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests. -Conversely, Django stops short of automatically generating URLs, and requires you to explicitly manage your URL configuration. +REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs. -REST framework adds support for automatic URL routing, which provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs. +## Usage -# API Guide - -Routers provide a convenient and simple shortcut for wiring up your application's URLs. +Here's an example of a simple URL conf, that uses `DefaultRouter`. router = routers.DefaultRouter() - router.register('^/', APIRoot, 'api-root') - router.register('^users/', UserViewSet, 'user') - router.register('^groups/', GroupViewSet, 'group') - router.register('^accounts/', AccountViewSet, 'account') + router.register(r'users', UserViewSet, 'user') + router.register(r'accounts', AccountViewSet, 'account') + urlpatterns = router.urls + +# API Guide + +## SimpleRouter + + + + + + + + + + + +
URL StyleHTTP MethodActionURL Name
{prefix}/GETlist{basename}-list
POSTcreate
{prefix}/{lookup}/GETretrieve{basename}-detail
PUTupdate
PATCHpartial_update
DELETEdestroy
{prefix}/{lookup}/{methodname}/GET@link decorated method{basename}-{methodname}
POST@action decorated method
+ +## DefaultRouter + + + + + + + + + + + + +
URL StyleHTTP MethodActionURL Name
[.format]GETautomatically generated root viewapi-root
{prefix}/[.format]GETlist{basename}-list
POSTcreate
{prefix}/{lookup}/[.format]GETretrieve{basename}-detail
PUTupdate
PATCHpartial_update
DELETEdestroy
{prefix}/{lookup}/{methodname}/[.format]GET@link decorated method{basename}-{methodname}
POST@action decorated method
+ +# Custom Routers - urlpatterns = router.urlpatterns [cite]: http://guides.rubyonrails.org/routing.html \ No newline at end of file diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index cf6ae33b..5aa66196 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -111,26 +111,25 @@ Again, as with `ModelViewSet`, you can use any of the standard attributes and me Any standard `View` class can be turned into a `ViewSet` class by mixing in `ViewSetMixin`. You can use this to define your own base classes. -For example, the definition of `ModelViewSet` looks like this: - - class ModelViewSet(mixins.CreateModelMixin, - mixins.RetrieveModelMixin, - mixins.UpdateModelMixin, - mixins.DestroyModelMixin, - mixins.ListModelMixin, - viewsets.ViewSetMixin, - generics.GenericAPIView): +## Example + +For example, we can create a base viewset class that provides `retrieve`, `update` and `list` operations: + + class RetrieveUpdateListViewSet(mixins.RetrieveModelMixin, + mixins.UpdateModelMixin, + mixins.ListModelMixin, + viewsets.ViewSetMixin, + generics.GenericAPIView): """ - A viewset that provides actions for `create`, `retrieve`, - `update`, `destroy` and `list` actions. + A viewset that provides `retrieve`, `update`, and `list` actions. - To use it, override the class and set the `.queryset` - and `.serializer_class` attributes. + To use it, override the class and set the `.queryset` and + `.serializer_class` attributes. """ pass By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple views across your API. -For advanced usage, it's worth noting the that `ViewSetMixin` class can also be applied to the standard Django `View` class. Doing so allows you to use REST framework's automatic routing, but don't want to use it's permissions, authentication and other API policies. +For advanced usage, it's worth noting the that `ViewSetMixin` class can also be applied to the standard Django `View` class. Doing so allows you to use REST framework's automatic routing with regular Django views. [cite]: http://guides.rubyonrails.org/routing.html \ No newline at end of file -- cgit v1.2.3 From 95abe6e8445f59f9e52609b0c54d9276830dbfd3 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 25 Apr 2013 12:47:34 +0100 Subject: Cleanup docstrings --- docs/api-guide/viewsets.md | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 5aa66196..2f0f112b 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -41,6 +41,10 @@ If we need to, we can bind this viewset into two seperate views, like so: Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. + router = DefaultRouter() + router.register(r'users', UserViewSet, 'user') + urlpatterns = router.urls + There are two main advantages of using a `ViewSet` class over using a `View` class. * Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views. -- cgit v1.2.3 From 9abaf77401573e932ba4770248c1e229a8bc25dd Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 25 Apr 2013 17:39:33 +0100 Subject: More viewset/router docs --- docs/api-guide/generic-views.md | 4 +-- docs/api-guide/routers.md | 34 +++++++++++++++++++++- docs/api-guide/viewsets.md | 63 +++++++++++++++++++++++++++++++++++++++-- 3 files changed, 96 insertions(+), 5 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 9d09af7f..4a24b7c7 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -147,8 +147,8 @@ You won't typically need to override the following methods, although you might n * `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys. * `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False)` - Returns a serializer instance. * `get_pagination_serializer(self, page)` - Returns a serializer instance to use with paginated data. -* `paginate_queryset(self, queryset, page_size)` - Paginate a queryset. -* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backend is in use. +* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. +* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backend is in use, returning a new queryset. --- diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 7411bd7b..16ad2fb8 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -14,15 +14,45 @@ REST framework adds support for automatic URL routing to Django, and provides yo Here's an example of a simple URL conf, that uses `DefaultRouter`. - router = routers.DefaultRouter() + router = routers.SimpleRouter() router.register(r'users', UserViewSet, 'user') router.register(r'accounts', AccountViewSet, 'account') urlpatterns = router.urls +There are three arguments to the `register()` method: + +* `prefix` - The URL prefix to use for this set of routes. +* `viewset` - The viewset class. +* `basename` - The base to use for the URL names that are created. + +The example above would generate the following URL patterns: + +* URL pattern: `^users/$` Name: `'user-list'` +* URL pattern: `^users/{pk}/$` Name: `'user-detail'` +* URL pattern: `^accounts/$` Name: `'account-list'` +* URL pattern: `^accounts/{pk}/$` Name: `'account-detail'` + +### Extra link and actions + +Any `@link` or `@action` methods on the viewsets will also be routed. +For example, a given method like this on the `UserViewSet` class: + + @action(permission_classes=[IsAdminOrIsSelf]) + def set_password(self, request, pk=None): + ... + +The following URL pattern would additionally be generated: + +* URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'` + + + # API Guide ## SimpleRouter +This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@link` or `@action` decorators. + @@ -37,6 +67,8 @@ Here's an example of a simple URL conf, that uses `DefaultRouter`. ## DefaultRouter +This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes. +
URL StyleHTTP MethodActionURL Name
{prefix}/GETlist{basename}-list
diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 2f0f112b..fe182e79 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -52,6 +52,67 @@ There are two main advantages of using a `ViewSet` class over using a `View` cla Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout. +## Marking extra methods for routing + +The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below: + + class UserViewSet(viewsets.VietSet): + """ + Example empty viewset demonstrating the standard + actions that will be handled by a router class. + """ + + def list(self, request): + pass + + def create(self, request): + pass + + def retrieve(self, request, pk=None): + pass + + def update(self, request, pk=None): + pass + + def partial_update(self, request, pk=None): + pass + + def destroy(self, request, pk=None): + pass + +If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@link` or `@action` decorators. The `@link` decorator will route `GET` requests, and the `@action` decroator will route `POST` requests. + +For example: + + from django.contrib.auth.models import User + from rest_framework import viewsets + from rest_framework.decorators import action + from myapp.serializers import UserSerializer + + class UserViewSet(viewsets.ModelViewSet): + """ + A viewset that provides the standard actions + """ + queryset = User.objects.all() + serializer_class = UserSerializer + + @action + def set_password(self, request, pk=None): + user = self.get_object() + serializer = PasswordSerializer(data=request.DATA) + if serializer.is_valid(): + user.set_password(serializer.data['password']) + user.save() + return Response({'status': 'password set'}) + else: + return Response(serializer.errors, + status=status.HTTP_400_BAD_REQUEST) + +The `@action` and `@link` decorators can additionally take extra arguments that will be set for the routed view only. For example... + + @action(permission_classes=[IsAdminOrIsSelf]) + def set_password(self, request, pk=None): + ... # API Reference @@ -134,6 +195,4 @@ For example, we can create a base viewset class that provides `retrieve`, `updat By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple views across your API. -For advanced usage, it's worth noting the that `ViewSetMixin` class can also be applied to the standard Django `View` class. Doing so allows you to use REST framework's automatic routing with regular Django views. - [cite]: http://guides.rubyonrails.org/routing.html \ No newline at end of file -- cgit v1.2.3 From 74b3307978d1316603a51082b8edd9a29d2016dd Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 25 Apr 2013 20:43:37 +0100 Subject: Docs, docs, docs --- docs/api-guide/routers.md | 40 +++++++++++++++++++++++++++++++++++++--- docs/api-guide/viewsets.md | 2 ++ 2 files changed, 39 insertions(+), 3 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 16ad2fb8..2fda5373 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -34,7 +34,7 @@ The example above would generate the following URL patterns: ### Extra link and actions -Any `@link` or `@action` methods on the viewsets will also be routed. +Any methods on the viewset decorated with `@link` or `@action` will also be routed. For example, a given method like this on the `UserViewSet` class: @action(permission_classes=[IsAdminOrIsSelf]) @@ -45,8 +45,6 @@ The following URL pattern would additionally be generated: * URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'` - - # API Guide ## SimpleRouter @@ -82,7 +80,43 @@ This router is similar to `SimpleRouter` as above, but additionally includes a d
URL StyleHTTP MethodActionURL Name
[.format]GETautomatically generated root viewapi-root
POST@action decorated method
+## AutoRouter + +The AutoRouter class is similar to the `DefaultRouter` class, except that it doesn't require you to register any viewsets, but instead automatically creates routes for all installed models. + +It can be useful for prototyping, although for anything more advanced you'll want to drop down to using one of the other router classes, and registering viewsets explicitly. + +The following code shows how you can automatically include a complete API for your application with just a few lines of code, using the `AutoRouter` class: + + from django.conf.urls import patterns, url, include + from rest_framework.routers import AutoRouter + + urlpatterns = patterns('', + url(r'^api/', include(AutoRouter().urls)), + url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) + ) + # Custom Routers +Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specfic requirements about how the your URLs for your API are strutured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view. + +The simplest way to implement a custom router is to subclass one of the existing router classes. The `.routes` attribute is used to template the URL patterns that will be mapped to each viewset. + +## Example + +The following example will only route to the `list` and `retrieve` actions, and unlike the routers included by REST framework, it does not use the trailing slash convention. + + class ReadOnlyRouter(SimpleRouter): + """ + A router for read-only APIs, which doesn't use trailing suffixes. + """ + routes = [ + (r'^{prefix}$', {'get': 'list'}, '{basename}-list'), + (r'^{prefix}/{lookup}$', {'get': 'retrieve'}, '{basename}-detail') + ] + +## Advanced custom routers + +If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls()` method. The method should insect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute. [cite]: http://guides.rubyonrails.org/routing.html \ No newline at end of file diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index fe182e79..c029a06d 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -114,6 +114,8 @@ The `@action` and `@link` decorators can additionally take extra arguments that def set_password(self, request, pk=None): ... +--- + # API Reference ## ViewSet -- cgit v1.2.3 From 51f80c3604d9257a3f3c3aa9e3e9b02b6cebb98a Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 26 Apr 2013 10:23:05 +0100 Subject: Fix broken queryset in example --- docs/api-guide/viewsets.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index c029a06d..1bca491d 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -23,14 +23,14 @@ Let's define a simple viewset that can be used to listing or retrieving all the """ A simple ViewSet that for listing or retrieving users. """ - queryset = User.objects.all() - def list(self, request): - serializer = UserSerializer(self.queryset, many=True) + queryset = User.objects.all() + serializer = UserSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): - user = get_object_or_404(self.queryset, pk=pk) + queryset = User.objects.all() + user = get_object_or_404(queryset, pk=pk) serializer = UserSerializer(user) return Response(serializer.data) -- cgit v1.2.3 From 50c6bc5762460ebd2a79b61edd534d10cb58c7e5 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 26 Apr 2013 13:31:19 +0100 Subject: Fix up viewset docs slightly --- docs/api-guide/viewsets.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 1bca491d..36a4dbd5 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -19,7 +19,7 @@ Typically, rather than exlicitly registering the views in a viewset in the urlco Let's define a simple viewset that can be used to listing or retrieving all the users in the system. - class UserViewSet(ViewSet): + class UserViewSet(viewsets.ViewSet): """ A simple ViewSet that for listing or retrieving users. """ @@ -45,6 +45,15 @@ Typically we wouldn't do this, but would instead register the viewset with a rou router.register(r'users', UserViewSet, 'user') urlpatterns = router.urls +Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example: + + class UserViewSet(viewsets.ModelViewSet): + """ + A viewset for viewing and editing user instances. + """ + serializer_class = UserSerializer + queryset = User.objects.all() + There are two main advantages of using a `ViewSet` class over using a `View` class. * Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views. @@ -60,6 +69,9 @@ The default routers included with REST framework will provide routes for a stand """ Example empty viewset demonstrating the standard actions that will be handled by a router class. + + If you're using format suffixes, make sure to also include + the `format=None` keyword argument for each action. """ def list(self, request): @@ -197,4 +209,4 @@ For example, we can create a base viewset class that provides `retrieve`, `updat By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple views across your API. -[cite]: http://guides.rubyonrails.org/routing.html \ No newline at end of file +[cite]: http://guides.rubyonrails.org/routing.html -- cgit v1.2.3 From e301e2d974649a932ab9a7ca32199c068fa30495 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 26 Apr 2013 14:03:26 +0100 Subject: Adding 'view or viewset' to docs appropriate. --- docs/api-guide/authentication.md | 3 ++- docs/api-guide/filtering.md | 3 ++- docs/api-guide/parsers.md | 5 +++-- docs/api-guide/permissions.md | 3 ++- docs/api-guide/renderers.md | 3 ++- docs/api-guide/throttling.md | 5 +++-- 6 files changed, 14 insertions(+), 8 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 1f08f542..c2f73901 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -43,7 +43,8 @@ The default authentication schemes may be set globally, using the `DEFAULT_AUTHE ) } -You can also set the authentication scheme on a per-view basis, using the `APIView` class based views. +You can also set the authentication scheme on a per-view or per-viewset basis, +using the `APIView` class based views. class ExampleView(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 805d82f8..53cd3e13 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -94,7 +94,8 @@ You must also set the filter backend to `DjangoFilterBackend` in your settings: ## Specifying filter fields -If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, listing the set of fields you wish to filter against. +If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, or viewset, +listing the set of fields you wish to filter against. class ProductList(generics.ListAPIView): queryset = Product.objects.all() diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index a2830492..49d59d10 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -34,7 +34,8 @@ The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSE ) } -You can also set the renderers used for an individual view, using the `APIView` class based views. +You can also set the renderers used for an individual view, or viewset, +using the `APIView` class based views. class ExampleView(APIView): """ @@ -187,4 +188,4 @@ The following third party packages are also available. [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion [messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack [juanriaza]: https://github.com/juanriaza -[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack \ No newline at end of file +[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 4772c5e0..4b3eda6d 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -39,7 +39,8 @@ If not specified, this setting defaults to allowing unrestricted access: 'rest_framework.permissions.AllowAny', ) -You can also set the authentication policy on a per-view basis, using the `APIView` class based views. +You can also set the authentication policy on a per-view, or per-viewset basis, +using the `APIView` class based views. class ExampleView(APIView): permission_classes = (IsAuthenticated,) diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index e2fc36ca..00739422 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -27,7 +27,8 @@ The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CL ) } -You can also set the renderers used for an individual view, using the `APIView` class based views. +You can also set the renderers used for an individual view, or viewset, +using the `APIView` class based views. class UserCountView(APIView): """ diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index 1abd49f4..d6de85ba 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -40,7 +40,8 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period. -You can also set the throttling policy on a per-view basis, using the `APIView` class based views. +You can also set the throttling policy on a per-view or per-viewset basis, +using the `APIView` class based views. class ExampleView(APIView): throttle_classes = (UserThrottle,) @@ -167,4 +168,4 @@ The following is an example of a rate throttle, that will randomly throttle 1 in [cite]: https://dev.twitter.com/docs/error-codes-responses [permissions]: permissions.md [cache-setting]: https://docs.djangoproject.com/en/dev/ref/settings/#caches -[cache-docs]: https://docs.djangoproject.com/en/dev/topics/cache/#setting-up-the-cache \ No newline at end of file +[cache-docs]: https://docs.djangoproject.com/en/dev/topics/cache/#setting-up-the-cache -- cgit v1.2.3 From 8fa79a7fd38dda015afa658084361c6da2856e46 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 26 Apr 2013 14:59:21 +0100 Subject: Deal with List/Instance suffixes for viewsets --- docs/api-guide/routers.md | 8 ++++---- docs/api-guide/viewsets.md | 2 +- 2 files 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 2fda5373..7b211bfd 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -15,15 +15,15 @@ REST framework adds support for automatic URL routing to Django, and provides yo Here's an example of a simple URL conf, that uses `DefaultRouter`. router = routers.SimpleRouter() - router.register(r'users', UserViewSet, 'user') - router.register(r'accounts', AccountViewSet, 'account') + router.register(r'users', UserViewSet, name='user') + router.register(r'accounts', AccountViewSet, name='account') urlpatterns = router.urls There are three arguments to the `register()` method: * `prefix` - The URL prefix to use for this set of routes. * `viewset` - The viewset class. -* `basename` - The base to use for the URL names that are created. +* `name` - The base to use for the URL names that are created. The example above would generate the following URL patterns: @@ -119,4 +119,4 @@ The following example will only route to the `list` and `retrieve` actions, and If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls()` method. The method should insect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute. -[cite]: http://guides.rubyonrails.org/routing.html \ No newline at end of file +[cite]: http://guides.rubyonrails.org/routing.html diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 36a4dbd5..8af35bb8 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -42,7 +42,7 @@ If we need to, we can bind this viewset into two seperate views, like so: Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. router = DefaultRouter() - router.register(r'users', UserViewSet, 'user') + router.register(r'users', UserViewSet, name='user') urlpatterns = router.urls Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example: -- cgit v1.2.3 From 73019f91fe55f2ac16ce179917f686bf1a931597 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 27 Apr 2013 14:29:32 +0200 Subject: Update docs on object-level permissions. Closes #801.--- docs/api-guide/permissions.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 4772c5e0..a7de77fc 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -21,7 +21,12 @@ If any permission check fails an `exceptions.PermissionDenied` exception will be REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance. -Object level permissions are run by REST framework's generic views when `.get_object()` is called. As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object. +Object level permissions are run by REST framework's generic views when `.get_object()` is called. +As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object. + +If you're writing your own views and want to enforce object level permissions, +you'll need to explicitly call the `.check_object_permissions(request, obj)` method on the view at the point at which you've retrieved the object. +This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or simply return if the view has the appropraite permissions. ## Setting the permission policy -- cgit v1.2.3 From 33a26a76f1e8e1bde715711cca3acfd3992d07db Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 27 Apr 2013 16:35:42 +0200 Subject: Typo --- docs/api-guide/permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index a7de77fc..0c82b2a3 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -26,7 +26,7 @@ As with view level permissions, an `exceptions.PermissionDenied` exception will If you're writing your own views and want to enforce object level permissions, you'll need to explicitly call the `.check_object_permissions(request, obj)` method on the view at the point at which you've retrieved the object. -This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or simply return if the view has the appropraite permissions. +This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or simply return if the view has the appropriate permissions. ## Setting the permission policy -- cgit v1.2.3 From d17e2d852fc6ebc738e324b8797d390dc0287d37 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 29 Apr 2013 12:46:57 +0100 Subject: Remove AutoRouter. (Adding shortcut to generic views/viewsets means it's unneccessary) --- docs/api-guide/routers.md | 16 ---------------- 1 file changed, 16 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 7b211bfd..7495b91c 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -80,22 +80,6 @@ This router is similar to `SimpleRouter` as above, but additionally includes a d POST@action decorated method -## AutoRouter - -The AutoRouter class is similar to the `DefaultRouter` class, except that it doesn't require you to register any viewsets, but instead automatically creates routes for all installed models. - -It can be useful for prototyping, although for anything more advanced you'll want to drop down to using one of the other router classes, and registering viewsets explicitly. - -The following code shows how you can automatically include a complete API for your application with just a few lines of code, using the `AutoRouter` class: - - from django.conf.urls import patterns, url, include - from rest_framework.routers import AutoRouter - - urlpatterns = patterns('', - url(r'^api/', include(AutoRouter().urls)), - url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) - ) - # Custom Routers Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specfic requirements about how the your URLs for your API are strutured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view. -- cgit v1.2.3 From 21ae3a66917acf4ea57e8f7940ce1a6823a2ce92 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 30 Apr 2013 08:24:33 +0100 Subject: Drop out attribute --- docs/api-guide/serializers.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 2797b5f5..c48461d8 100755 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -374,16 +374,20 @@ Returns the field instance that should be used to represent the pk field. ### get_nested_field -**Signature**: `.get_nested_field(self, model_field)` +**Signature**: `.get_nested_field(self, model_field, related_model, to_many)` Returns the field instance that should be used to represent a related field when `depth` is specified as being non-zero. +Note that the `model_field` argument will be `None` for reverse relationships. The `related_model` argument will be the model class for the target of the field. The `to_many` argument will be a boolean indicating if this is a to-one or to-many relationship. + ### get_related_field -**Signature**: `.get_related_field(self, model_field, to_many=False)` +**Signature**: `.get_related_field(self, model_field, related_model, to_many)` Returns the field instance that should be used to represent a related field when `depth` is not specified, or when nested representations are being used and the depth reaches zero. +Note that the `model_field` argument will be `None` for reverse relationships. The `related_model` argument will be the model class for the target of the field. The `to_many` argument will be a boolean indicating if this is a to-one or to-many relationship. + ### get_field **Signature**: `.get_field(self, model_field)` -- cgit v1.2.3 From b65b065375796919a57f4bd6f1dd8187ef0eb165 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 30 Apr 2013 14:34:28 +0100 Subject: Add DjangoModelPermissionsOrAnonReadOnly --- docs/api-guide/permissions.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 4b3eda6d..5dbaf338 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -96,16 +96,15 @@ This permission class ties into Django's standard `django.contrib.auth` [model p * `POST` requests require the user to have the `add` permission on the model. * `PUT` and `PATCH` requests require the user to have the `change` permission on the model. * `DELETE` requests require the user to have the `delete` permission on the model. - -If you want to use `DjangoModelPermissions` but also allow unauthenticated users to have read permission, override the class and set the `authenticated_users_only` property to `False`. For example: - - class HasModelPermissionsOrReadOnly(DjangoModelPermissions): - authenticated_users_only = False The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests. To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details. +## DjangoModelPermissionsOrAnonReadOnly + +Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API. + ## TokenHasReadWriteScope This permission class is intended for use with either of the `OAuthAuthentication` and `OAuth2Authentication` classes, and ties into the scoping that their backends provide. -- cgit v1.2.3 From 35f99cddc4a098547389fab7d9f397ad442dfff1 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 1 May 2013 09:03:09 +0100 Subject: lookup_field on hyperlinked fields, and overriddable hyperlinked fields. Closes #688 --- docs/api-guide/relations.md | 67 ++++++++++++++++++++++++++++++--------------- 1 file changed, 45 insertions(+), 22 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 623fe1a9..756e1562 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -123,9 +123,9 @@ Would serialize to a representation like this: 'album_name': 'Graceland', 'artist': 'Paul Simon' 'tracks': [ - 'http://www.example.com/api/tracks/45', - 'http://www.example.com/api/tracks/46', - 'http://www.example.com/api/tracks/47', + 'http://www.example.com/api/tracks/45/', + 'http://www.example.com/api/tracks/46/', + 'http://www.example.com/api/tracks/47/', ... ] } @@ -138,9 +138,7 @@ By default this field is read-write, although you can change this behavior using * `many` - If applied to a to-many relationship, you should set this argument to `True`. * `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. * `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. -* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`. -* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`. -* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`. +* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. ## SlugRelatedField @@ -196,7 +194,7 @@ Would serialize to a representation like this: { 'album_name': 'The Eraser', 'artist': 'Thom Yorke' - 'track_listing': 'http://www.example.com/api/track_list/12', + 'track_listing': 'http://www.example.com/api/track_list/12/', } This field is always read-only. @@ -291,32 +289,23 @@ This custom field would then serialize to the following representation. ## Reverse relations -Note that reverse relationships are not automatically generated by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you cannot simply add it to the fields list. - -**The following will not work:** +Note that reverse relationships are not automatically included by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you must explicitly add it to the fields list. For example: class AlbumSerializer(serializers.ModelSerializer): class Meta: - fields = ('tracks', ...) - -Instead, you must explicitly add it to the serializer. For example: - - class AlbumSerializer(serializers.ModelSerializer): - tracks = serializers.PrimaryKeyRelatedField(many=True) - ... - -By default, the field will uses the same accessor as it's field name to retrieve the relationship, so in this example, `Album` instances would need to have the `tracks` attribute for this relationship to work. + fields = ('tracks', ...) -The best way to ensure this is typically to make sure that the relationship on the model definition has it's `related_name` argument properly set. For example: +You'll normally want to ensure that you've set an appropriate `related_name` argument on the relationship, that you can use as the field name. For example: class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks') ... -Alternatively, you can use the `source` argument on the serializer field, to use a different accessor attribute than the field name. For example. +If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the `fields` argument. For example: class AlbumSerializer(serializers.ModelSerializer): - tracks = serializers.PrimaryKeyRelatedField(many=True, source='track_set') + class Meta: + fields = ('track_set', ...) See the Django documentation on [reverse relationships][reverse-relationships] for more details. @@ -394,6 +383,40 @@ Note that reverse generic keys, expressed using the `GenericRelation` field, can For more information see [the Django documentation on generic relations][generic-relations]. +## Advanced Hyperlinked fields + +If you have very specific requirements for the style of your hyperlinked relationships you can override `HyperlinkedRelatedField`. + +There are two methods you'll need to override. + +#### get_url(self, obj, view_name, request, format) + +This method should return the URL that corresponds to the given object. + +May raise a `NoReverseMatch` if the `view_name` and `lookup_field` +attributes are not configured to correctly match the URL conf. + +#### get_object(self, queryset, view_name, view_args, view_kwargs) + + +This method should the object that corresponds to the matched URL conf arguments. + +May raise an `ObjectDoesNotExist` exception. + +### Example + +For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this: + + class CustomHyperlinkedField(serializers.HyperlinkedRelatedField): + def get_url(self, obj, view_name, request, format): + kwargs = {'account': obj.account, 'slug': obj.slug} + return reverse(view_name, kwargs=kwargs, request=request, format=format) + + def get_object(self, queryset, view_name, view_args, view_kwargs): + account = view_kwargs['account'] + slug = view_kwargs['slug'] + return queryset.get(account=account, slug=sug) + --- ## Deprecated APIs -- cgit v1.2.3 From 8cabae22c5330da2e0a15a6d61ef038a6447756a Mon Sep 17 00:00:00 2001 From: Victor Shih Date: Wed, 1 May 2013 21:26:40 -0700 Subject: Example and spelling fixes. Change "browseable" to "browsable" for consistency. --- docs/api-guide/renderers.md | 4 ++-- docs/api-guide/serializers.md | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) mode change 100755 => 100644 docs/api-guide/serializers.md (limited to 'docs/api-guide') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 3c8396aa..19a6b90f 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -56,7 +56,7 @@ Or, if you're using the `@api_view` decorator with function based views. It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an `Accept: */*` header, or not including an `Accept` header at all, then REST framework will select the first renderer in the list to use for the response. -For example if your API serves JSON responses and the HTML browseable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header. +For example if your API serves JSON responses and the HTML browsable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header. If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making `TemplateHTMLRenderer` your default renderer, in order to play nicely with older browsers that send [broken accept headers][browser-accept-headers]. @@ -166,7 +166,7 @@ See also: `TemplateHTMLRenderer` ## BrowsableAPIRenderer -Renders data into HTML for the Browseable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page. +Renders data into HTML for the Browsable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page. **.media_type**: `text/html` diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md old mode 100755 new mode 100644 index 2797b5f5..98c6fbba --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -59,14 +59,15 @@ We can now use `CommentSerializer` to serialize a comment, or list of comments. At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`. - stream = JSONRenderer().render(data) - stream + json = JSONRenderer().render(serializer.data) + json # '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}' ## Deserializing objects Deserialization is similar. First we parse a stream into python native datatypes... + stream = StringIO(json) data = JSONParser().parse(stream) ...then we restore those native datatypes into a fully populated object instance. -- cgit v1.2.3 From 74beaefd1205503c06fdff8bb2621ba4c8c5baaa Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 2 May 2013 12:08:05 +0100 Subject: Simplifying bits of docs --- docs/api-guide/generic-views.md | 7 +++++-- docs/api-guide/routers.md | 15 ++++++++++----- docs/api-guide/viewsets.md | 2 +- 3 files changed, 16 insertions(+), 8 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 4a24b7c7..5de12bdb 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -62,6 +62,10 @@ The following attributes control the basic view behavior. * `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method. * `lookup_field` - The field that should be used to lookup individual model instances. Defaults to `'pk'`. The URL conf should include a keyword argument corresponding to this value. More complex lookup styles can be supported by overriding the `get_object()` method. +**Shortcuts**: + +* `model` - This shortcut may be used instead of setting either (or both) of the `queryset`/`serializer_class` attributes, although using the explicit style is generally preferred. If used instead of `serializer_class`, then then `DEFAULT_MODEL_SERIALIZER_CLASS` setting will determine the base serializer class. + **Pagination**: The following attibutes are used to control pagination when used with list views. @@ -75,7 +79,6 @@ The following attibutes are used to control pagination when used with list views * `filter_backend` - The filter backend class that should be used for filtering the queryset. Defaults to the same value as the `FILTER_BACKEND` setting. * `allow_empty` - Determines if an empty list should successfully display zero results, or return a 404 response. Defaults to `True`, meaning empty lists will return sucessful `200 OK` responses, with zero results. -* `model` - This shortcut may be used instead of setting either (or both) of the `queryset`/`serializer_class` attributes, although using the explicit style is generally preferred. If used instead of `serializer_class`, then then `DEFAULT_MODEL_SERIALIZER_CLASS` setting will determine the base serializer class. ### Methods @@ -160,7 +163,7 @@ The following classes are the concrete generic views. If you're using generic v Used for **create-only** endpoints. -Provides `post` method handlers. +Provides a `post` method handler. Extends: [GenericAPIView], [CreateModelMixin] diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 7495b91c..6588d7e5 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -15,15 +15,18 @@ REST framework adds support for automatic URL routing to Django, and provides yo Here's an example of a simple URL conf, that uses `DefaultRouter`. router = routers.SimpleRouter() - router.register(r'users', UserViewSet, name='user') - router.register(r'accounts', AccountViewSet, name='account') + router.register(r'users', UserViewSet) + router.register(r'accounts', AccountViewSet) urlpatterns = router.urls -There are three arguments to the `register()` method: +There are two mandatory arguments to the `register()` method: * `prefix` - The URL prefix to use for this set of routes. * `viewset` - The viewset class. -* `name` - The base to use for the URL names that are created. + +Optionally, you may also specify an additional argument: + +* `base_name` - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the `model` or `queryset` attribute on the viewset, if it has one. The example above would generate the following URL patterns: @@ -101,6 +104,8 @@ The following example will only route to the `list` and `retrieve` actions, and ## Advanced custom routers -If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls()` method. The method should insect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute. +If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should insect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute. + +You may also want to override the `get_default_base_name(self, viewset)` method, or else always explicitly set the `base_name` argument when registering your viewsets with the router. [cite]: http://guides.rubyonrails.org/routing.html diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 8af35bb8..d98f37d8 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -42,7 +42,7 @@ If we need to, we can bind this viewset into two seperate views, like so: Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. router = DefaultRouter() - router.register(r'users', UserViewSet, name='user') + router.register(r'users', UserViewSet) urlpatterns = router.urls Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example: -- cgit v1.2.3 From 5faaba9c691851ec68e385cc87d6bce82e4d4853 Mon Sep 17 00:00:00 2001 From: Michael Elovskikh Date: Sat, 4 May 2013 18:04:48 +0600 Subject: Docs for FileUploadParser --- docs/api-guide/parsers.md | 51 ++++++++++++++++++++--------------------------- 1 file changed, 22 insertions(+), 29 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index a2830492..370f406d 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -101,6 +101,28 @@ You will typically want to use both `FormParser` and `MultiPartParser` together **.media_type**: `multipart/form-data` +## FileUploadParser + +Parses raw file upload content. Returns a `DataAndFiles` object. Since we expect the whole request body to be a file content `request.DATA` will be None, and `request.FILES` will contain the only one key `'file'` matching the uploaded file. + +The `filename` property of uploaded file would be set to the result of `.get_filename()` method. By default it tries first to take it's value from the `filename` URL kwarg, and then from `Content-Disposition` HTTP header. You can implement other behaviour be overriding this method. + +Note that since this parser's `media_type` matches every HTTP request it imposes restrictions on usage in combination with other parsers for the same API view. + +Basic usage expamle: + + class FileUploadView(views.APIView): + parser_classes = (FileUploadParser,) + + def put(self, request, filename, format=None): + file_obj = request.FILES['file'] + # ... + # do some staff with uploaded file + # ... + return Response(status=204) + +**.media_type**: `*/*` + --- # Custom parsers @@ -144,35 +166,6 @@ The following is an example plaintext parser that will populate the `request.DAT """ return stream.read() -## Uploading file content - -If your custom parser needs to support file uploads, you may return a `DataAndFiles` object from the `.parse()` method. `DataAndFiles` should be instantiated with two arguments. The first argument will be used to populate the `request.DATA` property, and the second argument will be used to populate the `request.FILES` property. - -For example: - - class SimpleFileUploadParser(BaseParser): - """ - A naive raw file upload parser. - """ - media_type = '*/*' # Accept anything - - def parse(self, stream, media_type=None, parser_context=None): - content = stream.read() - name = 'example.dat' - content_type = 'application/octet-stream' - size = len(content) - charset = 'utf-8' - - # Write a temporary file based on the request content - temp = tempfile.NamedTemporaryFile(delete=False) - temp.write(content) - uploaded = UploadedFile(temp, name, content_type, size, charset) - - # Return the uploaded file - data = {} - files = {name: uploaded} - return DataAndFiles(data, files) - --- # Third party packages -- cgit v1.2.3 From 2dfd8c9697a1a0ec43a89369ae6a0239ec15b117 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 5 May 2013 16:48:12 +0100 Subject: docs, docs, docs --- docs/api-guide/generic-views.md | 12 ++++- docs/api-guide/serializers.md | 104 +++++++++++++++++++++++++++++++--------- 2 files changed, 93 insertions(+), 23 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 5de12bdb..d430710d 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -125,7 +125,7 @@ For example: #### `get_paginate_by(self)` -Returna the page size to use with pagination. By default this uses the `paginate_by` attribute, and may be overridden by the cient if the `paginate_by_param` attribute is set. +Returns the page size to use with pagination. By default this uses the `paginate_by` attribute, and may be overridden by the cient if the `paginate_by_param` attribute is set. You may want to override this method to provide more complex behavior such as modifying page sizes based on the media type of the response. @@ -143,6 +143,16 @@ The following methods are provided as placeholder interfaces. They contain empt * `pre_save(self, obj)` - A hook that is called before saving an object. * `post_save(self, obj, created=False)` - A hook that is called after saving an object. +The `pre_save` method in particular is a useful hook for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument. + + def pre_save(self, obj): + """ + Set the object's owner, based on the incoming request. + """ + obj.owner = self.request.user + +Remember that the `pre_save()` method is not called by `GenericAPIView` itself, but it is called by `create()` and `update()` methods on the `CreateModelMixin` and `UpdateModelMixin` classes. + **Other methods**: You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`. diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index c48461d8..4d63fc0a 100755 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -294,7 +294,7 @@ The context dictionary can be used within any serializer field logic, such as a --- -# ModelSerializers +# ModelSerializer Often you'll want serializer classes that map closely to model definitions. The `ModelSerializer` class lets you automatically create a Serializer class with fields that correspond to the Model fields. @@ -305,7 +305,42 @@ The `ModelSerializer` class lets you automatically create a Serializer class wit By default, all the model fields on the class will be mapped to corresponding serializer fields. -Any foreign keys on the model will be mapped to `PrimaryKeyRelatedField` if you're using a `ModelSerializer`, or `HyperlinkedRelatedField` if you're using a `HyperlinkedModelSerializer`. +Any relationships such as foreign keys on the model will be mapped to `PrimaryKeyRelatedField`. Other models fields will be mapped to a corresponding serializer field. + +## Specifying which fields should be included + +If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`. + +For example: + + class AccountSerializer(serializers.ModelSerializer): + class Meta: + model = Account + fields = ('id', 'account_name', 'users', 'created') + +## Specifying nested serialization + +The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option: + + class AccountSerializer(serializers.ModelSerializer): + class Meta: + model = Account + fields = ('id', 'account_name', 'users', 'created') + depth = 1 + +The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation. + +## Specifying which fields should be read-only + +You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so: + + class AccountSerializer(serializers.ModelSerializer): + class Meta: + model = Account + fields = ('id', 'account_name', 'users', 'created') + read_only_fields = ('account_name',) + +Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option. ## Specifying fields explicitly @@ -328,43 +363,68 @@ Alternative representations include serializing using hyperlinks, serializing co For full details see the [serializer relations][relations] documentation. -## Specifying which fields should be included +--- -If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`. +# HyperlinkedModelSerializer -For example: +The `HyperlinkedModelSerializer` class is similar to the `ModelSerializer` class except that it uses hyperlinks to represent relationships, rather than primary keys. - class AccountSerializer(serializers.ModelSerializer): - class Meta: - model = Account - exclude = ('id',) +By default the serializer will include a `url` field instead of a primary key field. -## Specifiying nested serialization +The url field will be represented using a `HyperlinkedIdentityField` serializer field, and any relationships on the model will be represented using a `HyperlinkedRelatedField` serializer field. -The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option: +You can explicitly include the primary key by adding it to the `fields` option, for example: - class AccountSerializer(serializers.ModelSerializer): + class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Account - exclude = ('id',) - depth = 1 + fields = ('url', 'id', 'account_name', 'users', 'created') -The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation. +## How hyperlinked views are determined -## Specifying which fields should be read-only +There needs to be a way of determining which views should be used for hyperlinking to model instances. -You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so: +By default hyperlinks are expected to correspond to a view name that matches the style `'{model_name}-detail'`, and looks up the instance by a `pk` keyword argument. - class AccountSerializer(serializers.ModelSerializer): +You can change the field that is used for object lookups by setting the `lookup_field` option. The value of this option should correspond both with a kwarg in the URL conf, and with an field on the model. For example: + + class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Account - read_only_fields = ('created', 'modified') + fields = ('url', 'account_name', 'users', 'created') + lookup_field = 'slug' + +For more specfic requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example: + + class AccountSerializer(serializers.HyperlinkedModelSerializer): + url = serializers.HyperlinkedIdentityField( + view_name='account_detail', + lookup_field='account_name' + ) + users = serializers.HyperlinkedRelatedField( + view_name='user-detail', + lookup_field='username', + many=True, + read_only=True + ) + + class Meta: + model = Account + fields = ('url', 'account_name', 'users', 'created') + +--- + +# Advanced serializer usage + +You can create customized subclasses of `ModelSerializer` or `HyperlinkedModelSerializer` that use a different set of default fields. + +Doing so should be considered advanced usage, and will only be needed if you have some particular serializer requirements that you often need to repeat. ## Customising the default fields -You can create customized subclasses of `ModelSerializer` that use a different set of default fields for the representation, by overriding various `get__field` methods. +The `field_mapping` attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes. -Each of these methods may either return a field or serializer instance, or `None`. +For more advanced customization than simply changing the default serializer class you can override various `get__field` methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or `None`. ### get_pk_field @@ -394,7 +454,7 @@ Note that the `model_field` argument will be `None` for reverse relationships. Returns the field instance that should be used for non-relational, non-pk fields. -### Example: +## Example The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default. -- cgit v1.2.3 From d71a5533f9a8787652244dfb16af37fb7d9059fb Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 7 May 2013 12:25:41 +0100 Subject: allow_empty -> pending deprecation in preference of overridden get_queryset. --- docs/api-guide/generic-views.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index d430710d..59912568 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -75,10 +75,9 @@ The following attibutes are used to control pagination when used with list views * `pagination_serializer_class` - The pagination serializer class to use when determining the style of paginated responses. Defaults to the same value as the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting. * `page_kwarg` - The name of a URL kwarg or URL query parameter which can be used by the client to control which page is requested. Defaults to `'page'`. -**Other**: +**Filtering**: * `filter_backend` - The filter backend class that should be used for filtering the queryset. Defaults to the same value as the `FILTER_BACKEND` setting. -* `allow_empty` - Determines if an empty list should successfully display zero results, or return a 404 response. Defaults to `True`, meaning empty lists will return sucessful `200 OK` responses, with zero results. ### Methods -- cgit v1.2.3 From 3c2bb0666063917707bfbfedf056e5692bfcc471 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 7 May 2013 13:00:44 +0100 Subject: Support for multiple filter classes --- docs/api-guide/filtering.md | 21 ++++++++++----------- docs/api-guide/generic-views.md | 2 +- docs/api-guide/settings.md | 7 ++++--- 3 files changed, 15 insertions(+), 15 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 53cd3e13..50bc6f05 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -79,23 +79,22 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/ As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex filters that can be specified by the client using query parameters. -REST framework supports pluggable backends to implement filtering, and provides an implementation which uses the [django-filter] package. +## DjangoFilterBackend -To use REST framework's filtering backend, first install `django-filter`. +To use REST framework's `DjangoFilterBackend`, first install `django-filter`. pip install django-filter You must also set the filter backend to `DjangoFilterBackend` in your settings: REST_FRAMEWORK = { - 'FILTER_BACKEND': 'rest_framework.filters.DjangoFilterBackend' + 'DEFAULT_FILTER_BACKENDS': ['rest_framework.filters.DjangoFilterBackend'] } -## Specifying filter fields +#### Specifying filter fields -If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, or viewset, -listing the set of fields you wish to filter against. +If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against. class ProductList(generics.ListAPIView): queryset = Product.objects.all() @@ -106,7 +105,7 @@ This will automatically create a `FilterSet` class for the given fields, and wil http://example.com/api/products?category=clothing&in_stock=True -## Specifying a FilterSet +#### Specifying a FilterSet For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view. For example: @@ -132,13 +131,13 @@ For more details on using filter sets see the [django-filter documentation][djan **Hints & Tips** -* By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'FILTER_BACKEND'` setting. +* By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'DEFAULT_FILTER_BACKENDS'` setting. * When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].) * `django-filter` supports filtering across relationships, using Django's double-underscore syntax. --- -### Filtering and object lookups +## Filtering and object lookups Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object. @@ -170,12 +169,12 @@ You can also provide your own generic filtering backend, or write an installable To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset. -To install the filter backend, set the `'FILTER_BACKEND'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class. +To install the filter backend, set the `'DEFAULT_FILTER_BACKENDS'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class. For example: REST_FRAMEWORK = { - 'FILTER_BACKEND': 'custom_filters.CustomFilterBackend' + 'DEFAULT_FILTER_BACKENDS': ['custom_filters.CustomFilterBackend'] } [cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 59912568..a2f54b76 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -77,7 +77,7 @@ The following attibutes are used to control pagination when used with list views **Filtering**: -* `filter_backend` - The filter backend class that should be used for filtering the queryset. Defaults to the same value as the `FILTER_BACKEND` setting. +* `filter_backends` - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the `DEFAULT_FILTER_BACKENDS` setting. ### Methods diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index c0d8d9ee..84dc8707 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -112,9 +112,10 @@ A class the determines the default serialization style for paginated responses. Default: `rest_framework.pagination.PaginationSerializer` -#### FILTER_BACKEND +#### DEFAULT_FILTER_BACKENDS -The filter backend class that should be used for generic filtering. If set to `None` then generic filtering is disabled. +A list of filter backend classes that should be used for generic filtering. +If set to `None` then generic filtering is disabled. #### PAGINATE_BY @@ -255,4 +256,4 @@ The name of a parameter in the URL conf that may be used to provide a format suf Default: `'format'` [cite]: http://www.python.org/dev/peps/pep-0020/ -[strftime]: http://docs.python.org/2/library/time.html#time.strftime \ No newline at end of file +[strftime]: http://docs.python.org/2/library/time.html#time.strftime -- cgit v1.2.3 From 3353889ae85cc21890469cf00f7073d1ea5c2070 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 7 May 2013 13:27:27 +0100 Subject: Docs for FileUploadParser --- docs/api-guide/parsers.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 20518647..7d2c056e 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -104,13 +104,18 @@ You will typically want to use both `FormParser` and `MultiPartParser` together ## FileUploadParser -Parses raw file upload content. Returns a `DataAndFiles` object. Since we expect the whole request body to be a file content `request.DATA` will be None, and `request.FILES` will contain the only one key `'file'` matching the uploaded file. +Parses raw file upload content. The `request.DATA` property will be an empty `QueryDict`, and `request.FILES` will be a dictionary with a single key `'file'` containing the uploaded file. -The `filename` property of uploaded file would be set to the result of `.get_filename()` method. By default it tries first to take it's value from the `filename` URL kwarg, and then from `Content-Disposition` HTTP header. You can implement other behaviour be overriding this method. +If the view used with `FileUploadParser` is called with a `filename` URL keyword argument, then that argument will be used as the filename. If it is called without a `filename` URL keyword argument, then the client must set the filename in the `Content-Disposition` HTTP header. For example `Content-Disposition: attachment; filename=upload.jpg`. -Note that since this parser's `media_type` matches every HTTP request it imposes restrictions on usage in combination with other parsers for the same API view. +**.media_type**: `*/*` + +##### Notes: -Basic usage expamle: +* The `FileUploadParser` is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the `MultiPartParser` parser instead. +* Since this parser's `media_type` matches any content type, `FileUploadParser` should generally be the only parser set on an API view. + +##### Basic usage example: class FileUploadView(views.APIView): parser_classes = (FileUploadParser,) @@ -122,7 +127,6 @@ Basic usage expamle: # ... return Response(status=204) -**.media_type**: `*/*` --- -- cgit v1.2.3 From 673a7a496f185c78c0322b4350eb703b02d9c607 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 8 May 2013 10:17:27 +0200 Subject: Update generic-views.md --- docs/api-guide/generic-views.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index a2f54b76..a30bfb21 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -160,7 +160,7 @@ You won't typically need to override the following methods, although you might n * `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False)` - Returns a serializer instance. * `get_pagination_serializer(self, page)` - Returns a serializer instance to use with paginated data. * `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. -* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backend is in use, returning a new queryset. +* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset. --- -- cgit v1.2.3 From 429e078eee63a120c408946cf7c1460d4ca9e9b4 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 8 May 2013 20:07:51 +0100 Subject: Allow None filename on uploaded files --- docs/api-guide/parsers.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/api-guide') diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 7d2c056e..5bd79a31 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -114,6 +114,7 @@ If the view used with `FileUploadParser` is called with a `filename` URL keyword * The `FileUploadParser` is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the `MultiPartParser` parser instead. * Since this parser's `media_type` matches any content type, `FileUploadParser` should generally be the only parser set on an API view. +* `FileUploadParser` respects Django's standard `FILE_UPLOAD_HANDLERS` setting, and the `request.upload_handlers` attribute. See the [Django documentation][upload-handlers] for more details. ##### Basic usage example: @@ -183,6 +184,7 @@ The following third party packages are also available. [jquery-ajax]: http://api.jquery.com/jQuery.ajax/ [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion +[upload-handlers]: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#upload-handlers [messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack [juanriaza]: https://github.com/juanriaza [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack -- cgit v1.2.3 From b443560080a20d52a3dd49f625a103810935affd Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 8 May 2013 20:38:50 +0100 Subject: Fix DATETIME_FORMAT, DATE_FORMAT, TIME_FORMAT settings. Closes #798 --- docs/api-guide/settings.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide') diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 84dc8707..b00ab4c1 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -203,7 +203,7 @@ A format string that should be used by default for rendering the output of `Date May be any of `None`, `'iso-8601'` or a python [strftime format][strftime] string. -Default: `None'` +Default: `None` #### DATETIME_INPUT_FORMATS -- cgit v1.2.3