mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-02 19:40:13 +03:00
Merge remote-tracking branch 'upsteam/master' into feature/action-docs-sections
This commit is contained in:
commit
c9ca4e9eef
10
.travis.yml
10
.travis.yml
|
@ -9,7 +9,6 @@ python:
|
||||||
sudo: false
|
sudo: false
|
||||||
|
|
||||||
env:
|
env:
|
||||||
- DJANGO=1.10
|
|
||||||
- DJANGO=1.11
|
- DJANGO=1.11
|
||||||
- DJANGO=2.0
|
- DJANGO=2.0
|
||||||
- DJANGO=2.1
|
- DJANGO=2.1
|
||||||
|
@ -22,6 +21,11 @@ matrix:
|
||||||
- { python: "3.6", env: DJANGO=1.11 }
|
- { python: "3.6", env: DJANGO=1.11 }
|
||||||
- { python: "3.6", env: DJANGO=2.0 }
|
- { python: "3.6", env: DJANGO=2.0 }
|
||||||
- { python: "3.6", env: DJANGO=2.1 }
|
- { python: "3.6", env: DJANGO=2.1 }
|
||||||
|
|
||||||
|
- { python: "3.7", env: DJANGO=2.0, dist: xenial, sudo: true }
|
||||||
|
- { python: "3.7", env: DJANGO=2.1, dist: xenial, sudo: true }
|
||||||
|
- { python: "3.7", env: DJANGO=master, dist: xenial, sudo: true }
|
||||||
|
|
||||||
- { python: "3.6", env: TOXENV=base }
|
- { python: "3.6", env: TOXENV=base }
|
||||||
- { python: "2.7", env: TOXENV=lint }
|
- { python: "2.7", env: TOXENV=lint }
|
||||||
- { python: "2.7", env: TOXENV=docs }
|
- { python: "2.7", env: TOXENV=docs }
|
||||||
|
@ -30,6 +34,7 @@ matrix:
|
||||||
env: TOXENV=dist
|
env: TOXENV=dist
|
||||||
script:
|
script:
|
||||||
- python setup.py bdist_wheel
|
- python setup.py bdist_wheel
|
||||||
|
- rm -r djangorestframework.egg-info # see #6139
|
||||||
- tox --installpkg ./dist/djangorestframework-*.whl
|
- tox --installpkg ./dist/djangorestframework-*.whl
|
||||||
- tox # test sdist
|
- tox # test sdist
|
||||||
|
|
||||||
|
@ -42,10 +47,9 @@ matrix:
|
||||||
|
|
||||||
allow_failures:
|
allow_failures:
|
||||||
- env: DJANGO=master
|
- env: DJANGO=master
|
||||||
- env: DJANGO=2.1
|
|
||||||
|
|
||||||
install:
|
install:
|
||||||
- pip install tox tox-travis
|
- pip install tox tox-venv tox-travis
|
||||||
|
|
||||||
script:
|
script:
|
||||||
- tox
|
- tox
|
||||||
|
|
28
README.md
28
README.md
|
@ -22,11 +22,11 @@ The initial aim is to provide a single full-time position on REST framework.
|
||||||
[![][rover-img]][rover-url]
|
[![][rover-img]][rover-url]
|
||||||
[![][sentry-img]][sentry-url]
|
[![][sentry-img]][sentry-url]
|
||||||
[![][stream-img]][stream-url]
|
[![][stream-img]][stream-url]
|
||||||
[![][machinalis-img]][machinalis-url]
|
|
||||||
[![][rollbar-img]][rollbar-url]
|
[![][rollbar-img]][rollbar-url]
|
||||||
[![][cadre-img]][cadre-url]
|
[![][cadre-img]][cadre-url]
|
||||||
|
[![][load-impact-img]][load-impact-url]
|
||||||
|
|
||||||
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Rover][rover-url], [Sentry][sentry-url], [Stream][stream-url], [Machinalis][machinalis-url], [Rollbar][rollbar-url], and [Cadre][cadre-url].
|
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Rover][rover-url], [Sentry][sentry-url], [Stream][stream-url], [Rollbar][rollbar-url], [Cadre][cadre-url], and [Load Impact][load-impact-url].
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -52,8 +52,8 @@ There is a live example API for testing purposes, [available here][sandbox].
|
||||||
|
|
||||||
# Requirements
|
# Requirements
|
||||||
|
|
||||||
* Python (2.7, 3.4, 3.5, 3.6)
|
* Python (2.7, 3.4, 3.5, 3.6, 3.7)
|
||||||
* Django (1.10, 1.11, 2.0)
|
* Django (1.11, 2.0, 2.1)
|
||||||
|
|
||||||
# Installation
|
# Installation
|
||||||
|
|
||||||
|
@ -142,14 +142,14 @@ You can now open the API in your browser at `http://127.0.0.1:8000/`, and view y
|
||||||
You can also interact with the API using command line tools such as [`curl`](https://curl.haxx.se/). For example, to list the users endpoint:
|
You can also interact with the API using command line tools such as [`curl`](https://curl.haxx.se/). For example, to list the users endpoint:
|
||||||
|
|
||||||
$ curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
|
$ curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
|
||||||
[
|
[
|
||||||
{
|
{
|
||||||
"url": "http://127.0.0.1:8000/users/1/",
|
"url": "http://127.0.0.1:8000/users/1/",
|
||||||
"username": "admin",
|
"username": "admin",
|
||||||
"email": "admin@example.com",
|
"email": "admin@example.com",
|
||||||
"is_staff": true,
|
"is_staff": true,
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
Or to create a new user:
|
Or to create a new user:
|
||||||
|
|
||||||
|
@ -191,16 +191,16 @@ Send a description of the issue via email to [rest-framework-security@googlegrou
|
||||||
[rover-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/rover-readme.png
|
[rover-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/rover-readme.png
|
||||||
[sentry-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/sentry-readme.png
|
[sentry-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/sentry-readme.png
|
||||||
[stream-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/stream-readme.png
|
[stream-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/stream-readme.png
|
||||||
[machinalis-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/machinalis-readme.png
|
|
||||||
[rollbar-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/rollbar-readme.png
|
[rollbar-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/rollbar-readme.png
|
||||||
[cadre-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cadre-readme.png
|
[cadre-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cadre-readme.png
|
||||||
|
[load-impact-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/load-impact-readme.png
|
||||||
|
|
||||||
[rover-url]: http://jobs.rover.com/
|
[rover-url]: http://jobs.rover.com/
|
||||||
[sentry-url]: https://getsentry.com/welcome/
|
[sentry-url]: https://getsentry.com/welcome/
|
||||||
[stream-url]: https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf
|
[stream-url]: https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf
|
||||||
[machinalis-url]: https://hello.machinalis.co.uk/
|
|
||||||
[rollbar-url]: https://rollbar.com/
|
[rollbar-url]: https://rollbar.com/
|
||||||
[cadre-url]: https://cadre.com/
|
[cadre-url]: https://cadre.com/
|
||||||
|
[load-impact-url]: https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf
|
||||||
|
|
||||||
[oauth1-section]: http://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth
|
[oauth1-section]: http://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth
|
||||||
[oauth2-section]: http://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit
|
[oauth2-section]: http://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit
|
||||||
|
|
|
@ -1,7 +1,8 @@
|
||||||
coverage:
|
coverage:
|
||||||
status:
|
status:
|
||||||
project: false
|
project: false
|
||||||
patch: false
|
patch: true
|
||||||
changes: false
|
changes: true
|
||||||
|
|
||||||
comment: off
|
comment:
|
||||||
|
layout: "diff"
|
||||||
|
|
|
@ -457,6 +457,43 @@ Modify your REST framework settings.
|
||||||
|
|
||||||
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
|
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
|
||||||
|
|
||||||
|
## XLSX (Binary Spreadsheet Endpoints)
|
||||||
|
|
||||||
|
XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-renderer-xlsx][drf-renderer-xlsx], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
|
||||||
|
|
||||||
|
#### Installation & configuration
|
||||||
|
|
||||||
|
Install using pip.
|
||||||
|
|
||||||
|
$ pip install drf-renderer-xlsx
|
||||||
|
|
||||||
|
Modify your REST framework settings.
|
||||||
|
|
||||||
|
REST_FRAMEWORK = {
|
||||||
|
...
|
||||||
|
|
||||||
|
'DEFAULT_RENDERER_CLASSES': (
|
||||||
|
'rest_framework.renderers.JSONRenderer',
|
||||||
|
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||||
|
'drf_renderer_xlsx.renderers.XLSXRenderer',
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the `Content-Disposition` header. If no filename is provided, it will default to `export.xlsx`. For example:
|
||||||
|
|
||||||
|
from rest_framework.viewsets import ReadOnlyModelViewSet
|
||||||
|
from drf_renderer_xlsx.mixins import XLSXFileMixin
|
||||||
|
from drf_renderer_xlsx.renderers import XLSXRenderer
|
||||||
|
|
||||||
|
from .models import MyExampleModel
|
||||||
|
from .serializers import MyExampleSerializer
|
||||||
|
|
||||||
|
class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
|
||||||
|
queryset = MyExampleModel.objects.all()
|
||||||
|
serializer_class = MyExampleSerializer
|
||||||
|
renderer_classes = (XLSXRenderer,)
|
||||||
|
filename = 'my_export.xlsx'
|
||||||
|
|
||||||
## CSV
|
## CSV
|
||||||
|
|
||||||
Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework.
|
Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework.
|
||||||
|
@ -497,6 +534,9 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
||||||
[messagepack]: https://msgpack.org/
|
[messagepack]: https://msgpack.org/
|
||||||
[juanriaza]: https://github.com/juanriaza
|
[juanriaza]: https://github.com/juanriaza
|
||||||
[mjumbewu]: https://github.com/mjumbewu
|
[mjumbewu]: https://github.com/mjumbewu
|
||||||
|
[flipperpa]: https://githuc.com/flipperpa
|
||||||
|
[wharton]: https://github.com/wharton
|
||||||
|
[drf-renderer-xlsx]: https://github.com/wharton/drf-renderer-xlsx
|
||||||
[vbabiy]: https://github.com/vbabiy
|
[vbabiy]: https://github.com/vbabiy
|
||||||
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
|
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
|
||||||
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
|
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
|
||||||
|
|
|
@ -28,7 +28,7 @@ There are two mandatory arguments to the `register()` method:
|
||||||
|
|
||||||
Optionally, you may also specify an additional argument:
|
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 `queryset` attribute of the viewset, if it has one. Note that if the viewset does not include a `queryset` attribute then you must set `base_name` when registering the viewset.
|
* `basename` - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the `queryset` attribute of the viewset, if it has one. Note that if the viewset does not include a `queryset` attribute then you must set `basename` when registering the viewset.
|
||||||
|
|
||||||
The example above would generate the following URL patterns:
|
The example above would generate the following URL patterns:
|
||||||
|
|
||||||
|
@ -39,13 +39,13 @@ The example above would generate the following URL patterns:
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Note**: The `base_name` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part.
|
**Note**: The `basename` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part.
|
||||||
|
|
||||||
Typically you won't *need* to specify the `base_name` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this:
|
Typically you won't *need* to specify the `basename` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this:
|
||||||
|
|
||||||
'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
|
'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
|
||||||
|
|
||||||
This means you'll need to explicitly set the `base_name` argument when registering the viewset, as it could not be automatically determined from the model name.
|
This means you'll need to explicitly set the `basename` argument when registering the viewset, as it could not be automatically determined from the model name.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -53,7 +53,7 @@ This means you'll need to explicitly set the `base_name` argument when registeri
|
||||||
|
|
||||||
The `.urls` attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs.
|
The `.urls` attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs.
|
||||||
|
|
||||||
For example, you can append `router.urls` to a list of existing views…
|
For example, you can append `router.urls` to a list of existing views...
|
||||||
|
|
||||||
router = routers.SimpleRouter()
|
router = routers.SimpleRouter()
|
||||||
router.register(r'users', UserViewSet)
|
router.register(r'users', UserViewSet)
|
||||||
|
@ -65,7 +65,7 @@ For example, you can append `router.urls` to a list of existing views…
|
||||||
|
|
||||||
urlpatterns += router.urls
|
urlpatterns += router.urls
|
||||||
|
|
||||||
Alternatively you can use Django's `include` function, like so…
|
Alternatively you can use Django's `include` function, like so...
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
|
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
|
||||||
|
@ -302,7 +302,7 @@ For another example of setting the `.routes` attribute, see the source code for
|
||||||
|
|
||||||
If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute.
|
If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute.
|
||||||
|
|
||||||
You may also want to override the `get_default_base_name(self, viewset)` method, or else always explicitly set the `base_name` argument when registering your viewsets with the router.
|
You may also want to override the `get_default_basename(self, viewset)` method, or else always explicitly set the `basename` argument when registering your viewsets with the router.
|
||||||
|
|
||||||
# Third Party Packages
|
# Third Party Packages
|
||||||
|
|
||||||
|
|
|
@ -243,6 +243,14 @@ You may disable schema generation for a view by setting `schema` to `None`:
|
||||||
...
|
...
|
||||||
schema = None # Will not appear in schema
|
schema = None # Will not appear in schema
|
||||||
|
|
||||||
|
This also applies to extra actions for `ViewSet`s:
|
||||||
|
|
||||||
|
class CustomViewSet(viewsets.ModelViewSet):
|
||||||
|
|
||||||
|
@action(detail=True, schema=None)
|
||||||
|
def extra_action(self, request, pk=None):
|
||||||
|
...
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Note**: For full details on `SchemaGenerator` plus the `AutoSchema` and
|
**Note**: For full details on `SchemaGenerator` plus the `AutoSchema` and
|
||||||
|
@ -601,19 +609,19 @@ that do not expect a request body.
|
||||||
|
|
||||||
### get_path_fields(self, path, method):
|
### get_path_fields(self, path, method):
|
||||||
|
|
||||||
Return a list of `coreapi.Link()` instances. One for each path parameter in the URL.
|
Return a list of `coreapi.Field()` instances. One for each path parameter in the URL.
|
||||||
|
|
||||||
### get_serializer_fields(self, path, method)
|
### get_serializer_fields(self, path, method)
|
||||||
|
|
||||||
Return a list of `coreapi.Link()` instances. One for each field in the serializer class used by the view.
|
Return a list of `coreapi.Field()` instances. One for each field in the serializer class used by the view.
|
||||||
|
|
||||||
### get_pagination_fields(self, path, method)
|
### get_pagination_fields(self, path, method)
|
||||||
|
|
||||||
Return a list of `coreapi.Link()` instances, as returned by the `get_schema_fields()` method on any pagination class used by the view.
|
Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method on any pagination class used by the view.
|
||||||
|
|
||||||
### get_filter_fields(self, path, method)
|
### get_filter_fields(self, path, method)
|
||||||
|
|
||||||
Return a list of `coreapi.Link()` instances, as returned by the `get_schema_fields()` method of any filter classes used by the view.
|
Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method of any filter classes used by the view.
|
||||||
|
|
||||||
### get_manual_fields(self, path, method)
|
### get_manual_fields(self, path, method)
|
||||||
|
|
||||||
|
|
|
@ -57,10 +57,10 @@ At this point we've translated the model instance into Python native datatypes.
|
||||||
|
|
||||||
Deserialization is similar. First we parse a stream into Python native datatypes...
|
Deserialization is similar. First we parse a stream into Python native datatypes...
|
||||||
|
|
||||||
from django.utils.six import BytesIO
|
import io
|
||||||
from rest_framework.parsers import JSONParser
|
from rest_framework.parsers import JSONParser
|
||||||
|
|
||||||
stream = BytesIO(json)
|
stream = io.BytesIO(json)
|
||||||
data = JSONParser().parse(stream)
|
data = JSONParser().parse(stream)
|
||||||
|
|
||||||
...then we restore those native datatypes into a dictionary of validated data.
|
...then we restore those native datatypes into a dictionary of validated data.
|
||||||
|
@ -1030,7 +1030,7 @@ Similar to Django forms, you can extend and reuse serializers through inheritanc
|
||||||
class MyBaseSerializer(Serializer):
|
class MyBaseSerializer(Serializer):
|
||||||
my_field = serializers.CharField()
|
my_field = serializers.CharField()
|
||||||
|
|
||||||
def validate_my_field(self):
|
def validate_my_field(self, value):
|
||||||
...
|
...
|
||||||
|
|
||||||
class MySerializer(MyBaseSerializer):
|
class MySerializer(MyBaseSerializer):
|
||||||
|
|
|
@ -398,10 +398,15 @@ A string representing the function that should be used when generating view name
|
||||||
|
|
||||||
This should be a function with the following signature:
|
This should be a function with the following signature:
|
||||||
|
|
||||||
view_name(cls, suffix=None)
|
view_name(self)
|
||||||
|
|
||||||
* `cls`: The view class. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `cls.__name__`.
|
* `self`: The view instance. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `self.__class__.__name__`.
|
||||||
* `suffix`: The optional suffix used when differentiating individual views in a viewset.
|
|
||||||
|
If the view instance inherits `ViewSet`, it may have been initialized with several optional arguments:
|
||||||
|
|
||||||
|
* `name`: A name expliticly provided to a view in the viewset. Typically, this value should be used as-is when provided.
|
||||||
|
* `suffix`: Text used when differentiating individual views in a viewset. This argument is mutually exclusive to `name`.
|
||||||
|
* `detail`: Boolean that differentiates an individual view in a viewset as either being a 'list' or 'detail' view.
|
||||||
|
|
||||||
Default: `'rest_framework.views.get_view_name'`
|
Default: `'rest_framework.views.get_view_name'`
|
||||||
|
|
||||||
|
@ -413,11 +418,15 @@ This setting can be changed to support markup styles other than the default mark
|
||||||
|
|
||||||
This should be a function with the following signature:
|
This should be a function with the following signature:
|
||||||
|
|
||||||
view_description(cls, html=False)
|
view_description(self, html=False)
|
||||||
|
|
||||||
* `cls`: The view class. Typically the description function would inspect the docstring of the class when generating a description, by accessing `cls.__doc__`
|
* `self`: The view instance. Typically the description function would inspect the docstring of the class when generating a description, by accessing `self.__class__.__doc__`
|
||||||
* `html`: A boolean indicating if HTML output is required. `True` when used in the browsable API, and `False` when used in generating `OPTIONS` responses.
|
* `html`: A boolean indicating if HTML output is required. `True` when used in the browsable API, and `False` when used in generating `OPTIONS` responses.
|
||||||
|
|
||||||
|
If the view instance inherits `ViewSet`, it may have been initialized with several optional arguments:
|
||||||
|
|
||||||
|
* `description`: A description explicitly provided to the view in the viewset. Typically, this is set by extra viewset `action`s, and should be used as-is.
|
||||||
|
|
||||||
Default: `'rest_framework.views.get_view_description'`
|
Default: `'rest_framework.views.get_view_description'`
|
||||||
|
|
||||||
## HTML Select Field cutoffs
|
## HTML Select Field cutoffs
|
||||||
|
|
|
@ -51,7 +51,7 @@ Typically we wouldn't do this, but would instead register the viewset with a rou
|
||||||
from rest_framework.routers import DefaultRouter
|
from rest_framework.routers import DefaultRouter
|
||||||
|
|
||||||
router = DefaultRouter()
|
router = DefaultRouter()
|
||||||
router.register(r'users', UserViewSet, base_name='user')
|
router.register(r'users', UserViewSet, basename='user')
|
||||||
urlpatterns = router.urls
|
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:
|
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:
|
||||||
|
@ -110,6 +110,8 @@ During dispatch, the following attributes are available on the `ViewSet`.
|
||||||
* `action` - the name of the current action (e.g., `list`, `create`).
|
* `action` - the name of the current action (e.g., `list`, `create`).
|
||||||
* `detail` - boolean indicating if the current action is configured for a list or detail view.
|
* `detail` - boolean indicating if the current action is configured for a list or detail view.
|
||||||
* `suffix` - the display suffix for the viewset type - mirrors the `detail` attribute.
|
* `suffix` - the display suffix for the viewset type - mirrors the `detail` attribute.
|
||||||
|
* `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`.
|
||||||
|
* `description` - the display description for the individual view of a viewset.
|
||||||
|
|
||||||
You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
||||||
|
|
||||||
|
@ -142,7 +144,7 @@ A more complete example of extra actions:
|
||||||
queryset = User.objects.all()
|
queryset = User.objects.all()
|
||||||
serializer_class = UserSerializer
|
serializer_class = UserSerializer
|
||||||
|
|
||||||
@action(methods=['post'], detail=True)
|
@action(detail=True, methods=['post'])
|
||||||
def set_password(self, request, pk=None):
|
def set_password(self, request, pk=None):
|
||||||
user = self.get_object()
|
user = self.get_object()
|
||||||
serializer = PasswordSerializer(data=request.data)
|
serializer = PasswordSerializer(data=request.data)
|
||||||
|
@ -168,13 +170,13 @@ A more complete example of extra actions:
|
||||||
|
|
||||||
The decorator can additionally take extra arguments that will be set for the routed view only. For example:
|
The decorator can additionally take extra arguments that will be set for the routed view only. For example:
|
||||||
|
|
||||||
@action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])
|
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])
|
||||||
def set_password(self, request, pk=None):
|
def set_password(self, request, pk=None):
|
||||||
...
|
...
|
||||||
|
|
||||||
These decorator will route `GET` requests by default, but may also accept other HTTP methods by setting the `methods` argument. For example:
|
These decorator will route `GET` requests by default, but may also accept other HTTP methods by setting the `methods` argument. For example:
|
||||||
|
|
||||||
@action(methods=['post', 'delete'], detail=True)
|
@action(detail=True, methods=['post', 'delete'])
|
||||||
def unset_password(self, request, pk=None):
|
def unset_password(self, request, pk=None):
|
||||||
...
|
...
|
||||||
|
|
||||||
|
@ -182,6 +184,22 @@ The two new actions will then be available at the urls `^users/{pk}/set_password
|
||||||
|
|
||||||
To view all extra actions, call the `.get_extra_actions()` method.
|
To view all extra actions, call the `.get_extra_actions()` method.
|
||||||
|
|
||||||
|
### Routing additional HTTP methods for extra actions
|
||||||
|
|
||||||
|
Extra actions can be mapped to different `ViewSet` methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments.
|
||||||
|
|
||||||
|
```python
|
||||||
|
@action(detail=True, methods=['put'], name='Change Password')
|
||||||
|
def password(self, request, pk=None):
|
||||||
|
"""Update the user's password."""
|
||||||
|
...
|
||||||
|
|
||||||
|
@password.mapping.delete
|
||||||
|
def delete_password(self, request, pk=None):
|
||||||
|
"""Delete the user's password."""
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
## Reversing action URLs
|
## Reversing action URLs
|
||||||
|
|
||||||
If you need to get the URL of an action, use the `.reverse_action()` method. This is a convenience wrapper for `reverse()`, automatically passing the view's `request` object and prepending the `url_name` with the `.basename` attribute.
|
If you need to get the URL of an action, use the `.reverse_action()` method. This is a convenience wrapper for `reverse()`, automatically passing the view's `request` object and prepending the `url_name` with the `.basename` attribute.
|
||||||
|
@ -251,7 +269,7 @@ Note that you can use any of the standard attributes or method overrides provide
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
return self.request.user.accounts.all()
|
return self.request.user.accounts.all()
|
||||||
|
|
||||||
Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the base_name of your Model automatically, and so you will have to specify the `base_name` kwarg as part of your [router registration][routers].
|
Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the basename of your Model automatically, and so you will have to specify the `basename` kwarg as part of your [router registration][routers].
|
||||||
|
|
||||||
Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.
|
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.
|
||||||
|
|
||||||
|
|
|
@ -119,7 +119,7 @@ This would now be split out into two separate methods.
|
||||||
instance.save()
|
instance.save()
|
||||||
return instance
|
return instance
|
||||||
|
|
||||||
def create(self, validated_data):
|
def create(self, validated_data):
|
||||||
return Snippet.objects.create(**validated_data)
|
return Snippet.objects.create(**validated_data)
|
||||||
|
|
||||||
Note that these methods should return the newly created object instance.
|
Note that these methods should return the newly created object instance.
|
||||||
|
@ -329,7 +329,7 @@ The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDe
|
||||||
model = MyModel
|
model = MyModel
|
||||||
fields = ('id', 'email', 'notes', 'is_admin')
|
fields = ('id', 'email', 'notes', 'is_admin')
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
'is_admin': {'write_only': True}
|
'is_admin': {'write_only': True}
|
||||||
}
|
}
|
||||||
|
|
||||||
Alternatively, specify the field explicitly on the serializer class:
|
Alternatively, specify the field explicitly on the serializer class:
|
||||||
|
@ -454,7 +454,7 @@ We can now use this class to serialize single `HighScore` instances:
|
||||||
def high_score(request, pk):
|
def high_score(request, pk):
|
||||||
instance = HighScore.objects.get(pk=pk)
|
instance = HighScore.objects.get(pk=pk)
|
||||||
serializer = HighScoreSerializer(instance)
|
serializer = HighScoreSerializer(instance)
|
||||||
return Response(serializer.data)
|
return Response(serializer.data)
|
||||||
|
|
||||||
Or use it to serialize multiple instances:
|
Or use it to serialize multiple instances:
|
||||||
|
|
||||||
|
@ -462,7 +462,7 @@ Or use it to serialize multiple instances:
|
||||||
def all_high_scores(request):
|
def all_high_scores(request):
|
||||||
queryset = HighScore.objects.order_by('-score')
|
queryset = HighScore.objects.order_by('-score')
|
||||||
serializer = HighScoreSerializer(queryset, many=True)
|
serializer = HighScoreSerializer(queryset, many=True)
|
||||||
return Response(serializer.data)
|
return Response(serializer.data)
|
||||||
|
|
||||||
##### Read-write `BaseSerializer` classes.
|
##### Read-write `BaseSerializer` classes.
|
||||||
|
|
||||||
|
@ -493,8 +493,8 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
|
||||||
'player_name': 'May not be more than 10 characters.'
|
'player_name': 'May not be more than 10 characters.'
|
||||||
})
|
})
|
||||||
|
|
||||||
# Return the validated values. This will be available as
|
# Return the validated values. This will be available as
|
||||||
# the `.validated_data` property.
|
# the `.validated_data` property.
|
||||||
return {
|
return {
|
||||||
'score': int(score),
|
'score': int(score),
|
||||||
'player_name': player_name
|
'player_name': player_name
|
|
@ -123,7 +123,7 @@ If you only wish to support a subset of the supported languages, use Django's st
|
||||||
('en', _('English')),
|
('en', _('English')),
|
||||||
]
|
]
|
||||||
|
|
||||||
For more details, see the [internationalization documentation](internationalization.md).
|
For more details, see the [internationalization documentation][internationalization].
|
||||||
|
|
||||||
Many thanks to [Craig Blaszczyk](https://github.com/jakul) for helping push this through.
|
Many thanks to [Craig Blaszczyk](https://github.com/jakul) for helping push this through.
|
||||||
|
|
||||||
|
@ -205,5 +205,5 @@ This will either be made as a single 3.2 release, or split across two separate r
|
||||||
[custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling
|
[custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling
|
||||||
[pagination]: ../api-guide/pagination.md
|
[pagination]: ../api-guide/pagination.md
|
||||||
[versioning]: ../api-guide/versioning.md
|
[versioning]: ../api-guide/versioning.md
|
||||||
[internationalization]: internationalization.md
|
[internationalization]: ../topics/internationalization.md
|
||||||
[customizing-field-mappings]: ../api-guide/serializers.md#customizing-field-mappings
|
[customizing-field-mappings]: ../api-guide/serializers.md#customizing-field-mappings
|
|
@ -83,7 +83,7 @@ When using `allow_null` with `ListField` or a nested `many=True` serializer the
|
||||||
|
|
||||||
For example, take the following field:
|
For example, take the following field:
|
||||||
|
|
||||||
NestedSerializer(many=True, allow_null=True)
|
NestedSerializer(many=True, allow_null=True)
|
||||||
|
|
||||||
Previously the validation behavior would be:
|
Previously the validation behavior would be:
|
||||||
|
|
||||||
|
@ -110,4 +110,4 @@ This release is planned to include:
|
||||||
* Improvements and public API for our templated HTML forms and fields.
|
* Improvements and public API for our templated HTML forms and fields.
|
||||||
* Nested object and list support in HTML forms.
|
* Nested object and list support in HTML forms.
|
||||||
|
|
||||||
Thanks once again to all our sponsors and supporters.
|
Thanks once again to all our sponsors and supporters.
|
|
@ -37,8 +37,8 @@ This brings our supported versions into line with Django's [currently supported
|
||||||
The AJAX based support for the browsable API means that there are a number of internal cleanups in the `request` class. For the vast majority of developers this should largely remain transparent:
|
The AJAX based support for the browsable API means that there are a number of internal cleanups in the `request` class. For the vast majority of developers this should largely remain transparent:
|
||||||
|
|
||||||
* To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.
|
* To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.
|
||||||
* The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class](browser-enhancements.md#url-based-accept-headers).
|
* The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class][accept-headers].
|
||||||
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware](browser-enhancements.md#http-header-based-method-overriding).
|
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
|
||||||
|
|
||||||
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.
|
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.
|
||||||
|
|
||||||
|
@ -52,7 +52,9 @@ The following pagination view attributes and settings have been moved into attri
|
||||||
|
|
||||||
The `ModelSerializer` and `HyperlinkedModelSerializer` classes should now include either a `fields` or `exclude` option, although the `fields = '__all__'` shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings `ModelSerializer` more closely in line with Django's `ModelForm` behavior.
|
The `ModelSerializer` and `HyperlinkedModelSerializer` classes should now include either a `fields` or `exclude` option, although the `fields = '__all__'` shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings `ModelSerializer` more closely in line with Django's `ModelForm` behavior.
|
||||||
|
|
||||||
[forms-api]: html-and-forms.md
|
[forms-api]: ../topics/html-and-forms.md
|
||||||
[ajax-form]: https://github.com/encode/ajax-form
|
[ajax-form]: https://github.com/encode/ajax-form
|
||||||
[jsonfield]: ../../api-guide/fields#jsonfield
|
[jsonfield]: ../api-guide/fields#jsonfield
|
||||||
[django-supported-versions]: https://www.djangoproject.com/download/#supported-versions
|
[accept-headers]: ../topics/browser-enhancements.md#url-based-accept-headers
|
||||||
|
[method-override]: ../topics/browser-enhancements.md#http-header-based-method-overriding
|
||||||
|
[django-supported-versions]: https://www.djangoproject.com/download/#supported-versions
|
|
@ -185,10 +185,10 @@ The full set of itemized release notes [are available here][release-notes].
|
||||||
[swagger]: https://openapis.org/specification
|
[swagger]: https://openapis.org/specification
|
||||||
[hyperschema]: http://json-schema.org/latest/json-schema-hypermedia.html
|
[hyperschema]: http://json-schema.org/latest/json-schema-hypermedia.html
|
||||||
[api-blueprint]: https://apiblueprint.org/
|
[api-blueprint]: https://apiblueprint.org/
|
||||||
[tut-7]: ../../tutorial/7-schemas-and-client-libraries/
|
[tut-7]: ../tutorial/7-schemas-and-client-libraries/
|
||||||
[schema-generation]: ../../api-guide/schemas/
|
[schema-generation]: ../api-guide/schemas/
|
||||||
[api-clients]: api-clients.md
|
[api-clients]: ../topics/api-clients.md
|
||||||
[milestone]: https://github.com/encode/django-rest-framework/milestone/35
|
[milestone]: https://github.com/encode/django-rest-framework/milestone/35
|
||||||
[release-notes]: release-notes#34
|
[release-notes]: release-notes#34
|
||||||
[metadata]: ../../api-guide/metadata/#custom-metadata-classes
|
[metadata]: ../api-guide/metadata/#custom-metadata-classes
|
||||||
[gh3751]: https://github.com/encode/django-rest-framework/issues/3751
|
[gh3751]: https://github.com/encode/django-rest-framework/issues/3751
|
|
@ -194,6 +194,6 @@ on realtime support, for the 3.7 release.
|
||||||
|
|
||||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||||
[funding]: funding.md
|
[funding]: funding.md
|
||||||
[api-docs]: documenting-your-api.md
|
[api-docs]: ../topics/documenting-your-api.md
|
||||||
[js-docs]: api-clients.md#javascript-client-library
|
[js-docs]: ../topics/api-clients.md#javascript-client-library
|
||||||
[py-docs]: api-clients.md#python-client-library
|
[py-docs]: ../topics/api-clients.md#python-client-library
|
|
@ -174,23 +174,23 @@ This subscription is recommended for individuals with an interest in seeing REST
|
||||||
If you are using REST framework as a full-time employee, consider recommending that your company takes out a [corporate plan](#corporate-plans).
|
If you are using REST framework as a full-time employee, consider recommending that your company takes out a [corporate plan](#corporate-plans).
|
||||||
|
|
||||||
<div class="pricing">
|
<div class="pricing">
|
||||||
<div class="span4">
|
<div class="span4">
|
||||||
<div class="chart first">
|
<div class="chart first">
|
||||||
<div class="quantity">
|
<div class="quantity">
|
||||||
<span class="dollar">{{ symbol }}</span>
|
<span class="dollar">{{ symbol }}</span>
|
||||||
<span class="price">{{ rates.personal1 }}</span>
|
<span class="price">{{ rates.personal1 }}</span>
|
||||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="plan-name">Individual</div>
|
<div class="plan-name">Individual</div>
|
||||||
<div class="specs freelancer">
|
<div class="specs freelancer">
|
||||||
<div class="spec">
|
<div class="spec">
|
||||||
Support ongoing development
|
Support ongoing development
|
||||||
</div>
|
</div>
|
||||||
<div class="spec">
|
<div class="spec">
|
||||||
Credited on the site
|
Credited on the site
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.personal1 }}/" method="POST">
|
<form class="signup" action="/signup/{{ currency }}-{{ rates.personal1 }}/" method="POST">
|
||||||
<script
|
<script
|
||||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||||
data-key="{{ stripe_public }}"
|
data-key="{{ stripe_public }}"
|
||||||
|
@ -204,9 +204,9 @@ If you are using REST framework as a full-time employee, consider recommending t
|
||||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||||
</script>
|
</script>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div style="clear: both; padding-top: 50px"></div>
|
<div style="clear: both; padding-top: 50px"></div>
|
||||||
|
|
||||||
*Billing is monthly and you can cancel at any time.*
|
*Billing is monthly and you can cancel at any time.*
|
||||||
|
@ -222,23 +222,23 @@ In exchange for funding you'll also receive advertising space on our site, allow
|
||||||
Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.
|
Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.
|
||||||
|
|
||||||
<div class="pricing">
|
<div class="pricing">
|
||||||
<div class="span4">
|
<div class="span4">
|
||||||
<div class="chart first">
|
<div class="chart first">
|
||||||
<div class="quantity">
|
<div class="quantity">
|
||||||
<span class="dollar">{{ symbol }}</span>
|
<span class="dollar">{{ symbol }}</span>
|
||||||
<span class="price">{{ rates.corporate1 }}</span>
|
<span class="price">{{ rates.corporate1 }}</span>
|
||||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="plan-name">Basic</div>
|
<div class="plan-name">Basic</div>
|
||||||
<div class="specs startup">
|
<div class="specs startup">
|
||||||
<div class="spec">
|
<div class="spec">
|
||||||
Support ongoing development
|
Support ongoing development
|
||||||
</div>
|
</div>
|
||||||
<div class="spec">
|
<div class="spec">
|
||||||
<span class="variable">Funding page</span> ad placement
|
<span class="variable">Funding page</span> ad placement
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate1 }}/" method="POST">
|
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate1 }}/" method="POST">
|
||||||
<script
|
<script
|
||||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||||
data-key="{{ stripe_public }}"
|
data-key="{{ stripe_public }}"
|
||||||
|
@ -252,28 +252,28 @@ Our professional and premium plans also include **priority support**. At any tim
|
||||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||||
</script>
|
</script>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="span4">
|
<div class="span4">
|
||||||
<div class="chart">
|
<div class="chart">
|
||||||
<div class="quantity">
|
<div class="quantity">
|
||||||
<span class="dollar">{{ symbol }}</span>
|
<span class="dollar">{{ symbol }}</span>
|
||||||
<span class="price">{{ rates.corporate2 }}</span>
|
<span class="price">{{ rates.corporate2 }}</span>
|
||||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="plan-name">Professional</div>
|
<div class="plan-name">Professional</div>
|
||||||
<div class="specs">
|
<div class="specs">
|
||||||
<div class="spec">
|
<div class="spec">
|
||||||
Support ongoing development
|
Support ongoing development
|
||||||
</div>
|
</div>
|
||||||
<div class="spec">
|
<div class="spec">
|
||||||
<span class="variable">Sidebar</span> ad placement
|
<span class="variable">Sidebar</span> ad placement
|
||||||
</div>
|
</div>
|
||||||
<div class="spec">
|
<div class="spec">
|
||||||
<span class="variable">Priority support</span> for your engineers
|
<span class="variable">Priority support</span> for your engineers
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate2 }}/" method="POST">
|
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate2 }}/" method="POST">
|
||||||
<script
|
<script
|
||||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||||
data-key="{{ stripe_public }}"
|
data-key="{{ stripe_public }}"
|
||||||
|
@ -287,31 +287,31 @@ Our professional and premium plans also include **priority support**. At any tim
|
||||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||||
</script>
|
</script>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="span4">
|
<div class="span4">
|
||||||
<div class="chart last">
|
<div class="chart last">
|
||||||
<div class="quantity">
|
<div class="quantity">
|
||||||
<span class="dollar">{{ symbol }}</span>
|
<span class="dollar">{{ symbol }}</span>
|
||||||
<span class="price">{{ rates.corporate3 }}</span>
|
<span class="price">{{ rates.corporate3 }}</span>
|
||||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="plan-name">Premium</div>
|
<div class="plan-name">Premium</div>
|
||||||
<div class="specs">
|
<div class="specs">
|
||||||
<div class="spec">
|
<div class="spec">
|
||||||
Support ongoing development
|
Support ongoing development
|
||||||
</div>
|
</div>
|
||||||
<div class="spec">
|
<div class="spec">
|
||||||
<span class="variable">Homepage</span> ad placement
|
<span class="variable">Homepage</span> ad placement
|
||||||
</div>
|
</div>
|
||||||
<div class="spec">
|
<div class="spec">
|
||||||
<span class="variable">Sidebar</span> ad placement
|
<span class="variable">Sidebar</span> ad placement
|
||||||
</div>
|
</div>
|
||||||
<div class="spec">
|
<div class="spec">
|
||||||
<span class="variable">Priority support</span> for your engineers
|
<span class="variable">Priority support</span> for your engineers
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate3 }}/" method="POST">
|
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate3 }}/" method="POST">
|
||||||
<script
|
<script
|
||||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||||
data-key="{{ stripe_public }}"
|
data-key="{{ stripe_public }}"
|
||||||
|
@ -325,9 +325,9 @@ Our professional and premium plans also include **priority support**. At any tim
|
||||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||||
</script>
|
</script>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div style="clear: both; padding-top: 50px"></div>
|
<div style="clear: both; padding-top: 50px"></div>
|
||||||
|
|
||||||
|
@ -346,22 +346,22 @@ In an effort to keep the project as transparent as possible, we are releasing [m
|
||||||
<!-- Begin MailChimp Signup Form -->
|
<!-- Begin MailChimp Signup Form -->
|
||||||
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
|
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
|
||||||
<style type="text/css">
|
<style type="text/css">
|
||||||
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
</style>
|
</style>
|
||||||
<div id="mc_embed_signup">
|
<div id="mc_embed_signup">
|
||||||
<form action="//encode.us13.list-manage.com/subscribe/post?u=b6b66bb5e4c7cb484a85c8dd7&id=e382ef68ef" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
<form action="//encode.us13.list-manage.com/subscribe/post?u=b6b66bb5e4c7cb484a85c8dd7&id=e382ef68ef" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
<div id="mc_embed_signup_scroll">
|
<div id="mc_embed_signup_scroll">
|
||||||
<h2>Stay up to date, with our monthly progress reports...</h2>
|
<h2>Stay up to date, with our monthly progress reports...</h2>
|
||||||
<div class="mc-field-group">
|
<div class="mc-field-group">
|
||||||
<label for="mce-EMAIL">Email Address </label>
|
<label for="mce-EMAIL">Email Address </label>
|
||||||
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
|
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
|
||||||
</div>
|
</div>
|
||||||
<div id="mce-responses" class="clear">
|
<div id="mce-responses" class="clear">
|
||||||
<div class="response" id="mce-error-response" style="display:none"></div>
|
<div class="response" id="mce-error-response" style="display:none"></div>
|
||||||
<div class="response" id="mce-success-response" style="display:none"></div>
|
<div class="response" id="mce-success-response" style="display:none"></div>
|
||||||
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
|
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
|
||||||
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_b6b66bb5e4c7cb484a85c8dd7_e382ef68ef" tabindex="-1" value=""></div>
|
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_b6b66bb5e4c7cb484a85c8dd7_e382ef68ef" tabindex="-1" value=""></div>
|
||||||
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
</div>
|
</div>
|
|
@ -42,22 +42,22 @@ funded via the [REST framework paid plans](funding.md).
|
||||||
<!-- Begin MailChimp Signup Form -->
|
<!-- Begin MailChimp Signup Form -->
|
||||||
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
|
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
|
||||||
<style type="text/css">
|
<style type="text/css">
|
||||||
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
</style>
|
</style>
|
||||||
<div id="mc_embed_signup">
|
<div id="mc_embed_signup">
|
||||||
<form action="//encode.us13.list-manage.com/subscribe/post?u=b6b66bb5e4c7cb484a85c8dd7&id=e382ef68ef" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
<form action="//encode.us13.list-manage.com/subscribe/post?u=b6b66bb5e4c7cb484a85c8dd7&id=e382ef68ef" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
<div id="mc_embed_signup_scroll">
|
<div id="mc_embed_signup_scroll">
|
||||||
<h2>Stay up to date, with our monthly progress reports...</h2>
|
<h2>Stay up to date, with our monthly progress reports...</h2>
|
||||||
<div class="mc-field-group">
|
<div class="mc-field-group">
|
||||||
<label for="mce-EMAIL">Email Address </label>
|
<label for="mce-EMAIL">Email Address </label>
|
||||||
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
|
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
|
||||||
</div>
|
</div>
|
||||||
<div id="mce-responses" class="clear">
|
<div id="mce-responses" class="clear">
|
||||||
<div class="response" id="mce-error-response" style="display:none"></div>
|
<div class="response" id="mce-error-response" style="display:none"></div>
|
||||||
<div class="response" id="mce-success-response" style="display:none"></div>
|
<div class="response" id="mce-success-response" style="display:none"></div>
|
||||||
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
|
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
|
||||||
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_b6b66bb5e4c7cb484a85c8dd7_e382ef68ef" tabindex="-1" value=""></div>
|
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_b6b66bb5e4c7cb484a85c8dd7_e382ef68ef" tabindex="-1" value=""></div>
|
||||||
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
</div>
|
</div>
|
|
@ -38,6 +38,16 @@ You can determine your currently installed version using `pip show`:
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 3.9.x series
|
||||||
|
|
||||||
|
### 3.9.0
|
||||||
|
|
||||||
|
**Date**: Unreleased
|
||||||
|
|
||||||
|
* Deprecate the `Router.register` `base_name` argument in favor of `basename`. [#5990][gh5990]
|
||||||
|
* Deprecate the `Router.get_default_base_name` method in favor of `Router.get_default_basename`. [#5990][gh5990]
|
||||||
|
|
||||||
|
|
||||||
## 3.8.x series
|
## 3.8.x series
|
||||||
|
|
||||||
### 3.8.2
|
### 3.8.2
|
||||||
|
@ -1961,3 +1971,6 @@ For older release notes, [please see the version 2.x documentation][old-release-
|
||||||
[gh5922]: https://github.com/encode/django-rest-framework/issues/5922
|
[gh5922]: https://github.com/encode/django-rest-framework/issues/5922
|
||||||
[gh5921]: https://github.com/encode/django-rest-framework/issues/5921
|
[gh5921]: https://github.com/encode/django-rest-framework/issues/5921
|
||||||
[gh5920]: https://github.com/encode/django-rest-framework/issues/5920
|
[gh5920]: https://github.com/encode/django-rest-framework/issues/5920
|
||||||
|
|
||||||
|
<!-- 3.9.0 -->
|
||||||
|
[gh5990]: https://github.com/encode/django-rest-framework/issues/5990
|
|
@ -14,6 +14,9 @@ There are a wide range of resources available for learning and using Django REST
|
||||||
<a class="book-cover" href="https://wsvincent.com/books/">
|
<a class="book-cover" href="https://wsvincent.com/books/">
|
||||||
<img src="../../img/books/rad-cover.png"/>
|
<img src="../../img/books/rad-cover.png"/>
|
||||||
</a>
|
</a>
|
||||||
|
<a class="book-cover" href="https://books.agiliq.com/projects/django-api-polls-tutorial/en/latest/">
|
||||||
|
<img src="../../img/books/bda-cover.png"/>
|
||||||
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
## Tutorials
|
## Tutorials
|
BIN
docs/img/books/bda-cover.png
Normal file
BIN
docs/img/books/bda-cover.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 46 KiB |
BIN
docs/img/premium/load-impact-readme.png
Normal file
BIN
docs/img/premium/load-impact-readme.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 22 KiB |
156
docs/index.md
156
docs/index.md
|
@ -31,10 +31,6 @@
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Note**: This is the documentation for the **version 3** of REST framework. Documentation for [version 2](https://tomchristie.github.io/rest-framework-2-docs/) is also available.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
<h1 style="position: absolute;
|
<h1 style="position: absolute;
|
||||||
width: 1px;
|
width: 1px;
|
||||||
|
@ -73,13 +69,13 @@ continued development by **[signing up for a paid plan][funding]**.
|
||||||
<li><a href="http://jobs.rover.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
<li><a href="http://jobs.rover.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
||||||
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||||
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||||
<li><a href="https://hello.machinalis.co.uk/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</a></li>
|
|
||||||
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
|
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
|
||||||
<li><a href="https://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
|
<li><a href="https://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
|
||||||
|
<li><a href="https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/load-impact.png)">Load Impact</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
<div style="clear: both; padding-bottom: 20px;"></div>
|
<div style="clear: both; padding-bottom: 20px;"></div>
|
||||||
|
|
||||||
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Rover](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://hello.machinalis.co.uk/), [Rollbar](https://rollbar.com), and [Cadre](https://cadre.com).*
|
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Rover](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Rollbar](https://rollbar.com), [Cadre](https://cadre.com), and [Load Impact](https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf).*
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -87,8 +83,8 @@ continued development by **[signing up for a paid plan][funding]**.
|
||||||
|
|
||||||
REST framework requires the following:
|
REST framework requires the following:
|
||||||
|
|
||||||
* Python (2.7, 3.4, 3.5, 3.6)
|
* Python (2.7, 3.4, 3.5, 3.6, 3.7)
|
||||||
* Django (1.10, 1.11, 2.0)
|
* Django (1.11, 2.0, 2.1)
|
||||||
|
|
||||||
The following packages are optional:
|
The following packages are optional:
|
||||||
|
|
||||||
|
@ -151,11 +147,11 @@ Here's our project's root `urls.py` module:
|
||||||
from django.contrib.auth.models import User
|
from django.contrib.auth.models import User
|
||||||
from rest_framework import routers, serializers, viewsets
|
from rest_framework import routers, serializers, viewsets
|
||||||
|
|
||||||
# Serializers define the API representation.
|
# Serializers define the API representation.
|
||||||
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
class Meta:
|
class Meta:
|
||||||
model = User
|
model = User
|
||||||
fields = ('url', 'username', 'email', 'is_staff')
|
fields = ('url', 'username', 'email', 'is_staff')
|
||||||
|
|
||||||
# ViewSets define the view behavior.
|
# ViewSets define the view behavior.
|
||||||
class UserViewSet(viewsets.ModelViewSet):
|
class UserViewSet(viewsets.ModelViewSet):
|
||||||
|
@ -179,83 +175,6 @@ You can now open the API in your browser at [http://127.0.0.1:8000/](http://127.
|
||||||
|
|
||||||
Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running, and building APIs with REST framework.
|
Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running, and building APIs with REST framework.
|
||||||
|
|
||||||
## Tutorial
|
|
||||||
|
|
||||||
The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.
|
|
||||||
|
|
||||||
* [1 - Serialization][tut-1]
|
|
||||||
* [2 - Requests & Responses][tut-2]
|
|
||||||
* [3 - Class-based views][tut-3]
|
|
||||||
* [4 - Authentication & permissions][tut-4]
|
|
||||||
* [5 - Relationships & hyperlinked APIs][tut-5]
|
|
||||||
* [6 - Viewsets & routers][tut-6]
|
|
||||||
* [7 - Schemas & client libraries][tut-7]
|
|
||||||
|
|
||||||
There is a live example API of the finished tutorial API for testing purposes, [available here][sandbox].
|
|
||||||
|
|
||||||
## API Guide
|
|
||||||
|
|
||||||
The API guide is your complete reference manual to all the functionality provided by REST framework.
|
|
||||||
|
|
||||||
* [Requests][request]
|
|
||||||
* [Responses][response]
|
|
||||||
* [Views][views]
|
|
||||||
* [Generic views][generic-views]
|
|
||||||
* [Viewsets][viewsets]
|
|
||||||
* [Routers][routers]
|
|
||||||
* [Parsers][parsers]
|
|
||||||
* [Renderers][renderers]
|
|
||||||
* [Serializers][serializers]
|
|
||||||
* [Serializer fields][fields]
|
|
||||||
* [Serializer relations][relations]
|
|
||||||
* [Validators][validators]
|
|
||||||
* [Authentication][authentication]
|
|
||||||
* [Permissions][permissions]
|
|
||||||
* [Throttling][throttling]
|
|
||||||
* [Filtering][filtering]
|
|
||||||
* [Pagination][pagination]
|
|
||||||
* [Versioning][versioning]
|
|
||||||
* [Content negotiation][contentnegotiation]
|
|
||||||
* [Metadata][metadata]
|
|
||||||
* [Schemas][schemas]
|
|
||||||
* [Format suffixes][formatsuffixes]
|
|
||||||
* [Returning URLs][reverse]
|
|
||||||
* [Exceptions][exceptions]
|
|
||||||
* [Status codes][status]
|
|
||||||
* [Testing][testing]
|
|
||||||
* [Settings][settings]
|
|
||||||
|
|
||||||
## Topics
|
|
||||||
|
|
||||||
General guides to using REST framework.
|
|
||||||
|
|
||||||
* [Documenting your API][documenting-your-api]
|
|
||||||
* [API Clients][api-clients]
|
|
||||||
* [Internationalization][internationalization]
|
|
||||||
* [AJAX, CSRF & CORS][ajax-csrf-cors]
|
|
||||||
* [HTML & Forms][html-and-forms]
|
|
||||||
* [Browser enhancements][browser-enhancements]
|
|
||||||
* [The Browsable API][browsableapi]
|
|
||||||
* [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas]
|
|
||||||
* [Third Party Packages][third-party-packages]
|
|
||||||
* [Tutorials and Resources][tutorials-and-resources]
|
|
||||||
* [Contributing to REST framework][contributing]
|
|
||||||
* [Project management][project-management]
|
|
||||||
* [3.0 Announcement][3.0-announcement]
|
|
||||||
* [3.1 Announcement][3.1-announcement]
|
|
||||||
* [3.2 Announcement][3.2-announcement]
|
|
||||||
* [3.3 Announcement][3.3-announcement]
|
|
||||||
* [3.4 Announcement][3.4-announcement]
|
|
||||||
* [3.5 Announcement][3.5-announcement]
|
|
||||||
* [3.6 Announcement][3.6-announcement]
|
|
||||||
* [3.7 Announcement][3.7-announcement]
|
|
||||||
* [3.8 Announcement][3.8-announcement]
|
|
||||||
* [Kickstarter Announcement][kickstarter-announcement]
|
|
||||||
* [Mozilla Grant][mozilla-grant]
|
|
||||||
* [Funding][funding]
|
|
||||||
* [Release Notes][release-notes]
|
|
||||||
* [Jobs][jobs]
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
See the [Contribution guidelines][contributing] for information on how to clone
|
See the [Contribution guidelines][contributing] for information on how to clone
|
||||||
|
@ -323,68 +242,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||||
|
|
||||||
[quickstart]: tutorial/quickstart.md
|
[quickstart]: tutorial/quickstart.md
|
||||||
[tut-1]: tutorial/1-serialization.md
|
|
||||||
[tut-2]: tutorial/2-requests-and-responses.md
|
|
||||||
[tut-3]: tutorial/3-class-based-views.md
|
|
||||||
[tut-4]: tutorial/4-authentication-and-permissions.md
|
|
||||||
[tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md
|
|
||||||
[tut-6]: tutorial/6-viewsets-and-routers.md
|
|
||||||
[tut-7]: tutorial/7-schemas-and-client-libraries.md
|
|
||||||
|
|
||||||
[request]: api-guide/requests.md
|
|
||||||
[response]: api-guide/responses.md
|
|
||||||
[views]: api-guide/views.md
|
|
||||||
[generic-views]: api-guide/generic-views.md
|
[generic-views]: api-guide/generic-views.md
|
||||||
[viewsets]: api-guide/viewsets.md
|
[viewsets]: api-guide/viewsets.md
|
||||||
[routers]: api-guide/routers.md
|
[routers]: api-guide/routers.md
|
||||||
[parsers]: api-guide/parsers.md
|
|
||||||
[renderers]: api-guide/renderers.md
|
|
||||||
[serializers]: api-guide/serializers.md
|
[serializers]: api-guide/serializers.md
|
||||||
[fields]: api-guide/fields.md
|
|
||||||
[relations]: api-guide/relations.md
|
|
||||||
[validators]: api-guide/validators.md
|
|
||||||
[authentication]: api-guide/authentication.md
|
[authentication]: api-guide/authentication.md
|
||||||
[permissions]: api-guide/permissions.md
|
|
||||||
[throttling]: api-guide/throttling.md
|
|
||||||
[filtering]: api-guide/filtering.md
|
|
||||||
[pagination]: api-guide/pagination.md
|
|
||||||
[versioning]: api-guide/versioning.md
|
|
||||||
[contentnegotiation]: api-guide/content-negotiation.md
|
|
||||||
[metadata]: api-guide/metadata.md
|
|
||||||
[schemas]: api-guide/schemas.md
|
|
||||||
[formatsuffixes]: api-guide/format-suffixes.md
|
|
||||||
[reverse]: api-guide/reverse.md
|
|
||||||
[exceptions]: api-guide/exceptions.md
|
|
||||||
[status]: api-guide/status-codes.md
|
|
||||||
[testing]: api-guide/testing.md
|
|
||||||
[settings]: api-guide/settings.md
|
|
||||||
|
|
||||||
[documenting-your-api]: topics/documenting-your-api.md
|
[contributing]: community/contributing.md
|
||||||
[api-clients]: topics/api-clients.md
|
[funding]: community/funding.md
|
||||||
[internationalization]: topics/internationalization.md
|
|
||||||
[ajax-csrf-cors]: topics/ajax-csrf-cors.md
|
|
||||||
[html-and-forms]: topics/html-and-forms.md
|
|
||||||
[browser-enhancements]: topics/browser-enhancements.md
|
|
||||||
[browsableapi]: topics/browsable-api.md
|
|
||||||
[rest-hypermedia-hateoas]: topics/rest-hypermedia-hateoas.md
|
|
||||||
[contributing]: topics/contributing.md
|
|
||||||
[project-management]: topics/project-management.md
|
|
||||||
[third-party-packages]: topics/third-party-packages.md
|
|
||||||
[tutorials-and-resources]: topics/tutorials-and-resources.md
|
|
||||||
[3.0-announcement]: topics/3.0-announcement.md
|
|
||||||
[3.1-announcement]: topics/3.1-announcement.md
|
|
||||||
[3.2-announcement]: topics/3.2-announcement.md
|
|
||||||
[3.3-announcement]: topics/3.3-announcement.md
|
|
||||||
[3.4-announcement]: topics/3.4-announcement.md
|
|
||||||
[3.5-announcement]: topics/3.5-announcement.md
|
|
||||||
[3.6-announcement]: topics/3.6-announcement.md
|
|
||||||
[3.7-announcement]: topics/3.7-announcement.md
|
|
||||||
[3.8-announcement]: topics/3.8-announcement.md
|
|
||||||
[kickstarter-announcement]: topics/kickstarter-announcement.md
|
|
||||||
[mozilla-grant]: topics/mozilla-grant.md
|
|
||||||
[funding]: topics/funding.md
|
|
||||||
[release-notes]: topics/release-notes.md
|
|
||||||
[jobs]: topics/jobs.md
|
|
||||||
|
|
||||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||||
[botbot]: https://botbot.me/freenode/restframework/
|
[botbot]: https://botbot.me/freenode/restframework/
|
||||||
|
|
|
@ -1,158 +0,0 @@
|
||||||
# Django REST framework 2.2
|
|
||||||
|
|
||||||
The 2.2 release represents an important point for REST framework, with the addition of Python 3 support, and the introduction of an official deprecation policy.
|
|
||||||
|
|
||||||
## Python 3 support
|
|
||||||
|
|
||||||
Thanks to some fantastic work from [Xavier Ordoquy][xordoquy], Django REST framework 2.2 now supports Python 3. You'll need to be running Django 1.5, and it's worth keeping in mind that Django's Python 3 support is currently [considered experimental][django-python-3].
|
|
||||||
|
|
||||||
Django 1.6's Python 3 support is expected to be officially labeled as 'production-ready'.
|
|
||||||
|
|
||||||
If you want to start ensuring that your own projects are Python 3 ready, we can highly recommend Django's [Porting to Python 3][porting-python-3] documentation.
|
|
||||||
|
|
||||||
Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line with [Django 1.5's Python compatibility][python-compat].
|
|
||||||
|
|
||||||
## Deprecation policy
|
|
||||||
|
|
||||||
We've now introduced an official deprecation policy, which is in line with [Django's deprecation policy][django-deprecation-policy]. This policy will make it easy for you to continue to track the latest, greatest version of REST framework.
|
|
||||||
|
|
||||||
The timeline for deprecation works as follows:
|
|
||||||
|
|
||||||
* Version 2.2 introduces some API changes as detailed in the release notes. It remains fully backwards compatible with 2.1, but will raise `PendingDeprecationWarning` warnings if you use bits of API that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using `python -Wd manage.py test`, you'll be warned of any API changes you need to make.
|
|
||||||
|
|
||||||
* Version 2.3 will escalate these warnings to `DeprecationWarning`, which is loud by default.
|
|
||||||
|
|
||||||
* Version 2.4 will remove the deprecated bits of API entirely.
|
|
||||||
|
|
||||||
Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.
|
|
||||||
|
|
||||||
## Community
|
|
||||||
|
|
||||||
As of the 2.2 merge, we've also hit an impressive milestone. The number of committers listed in [the credits][credits], is now at over **one hundred individuals**. Each name on that list represents at least one merged pull request, however large or small.
|
|
||||||
|
|
||||||
Our [mailing list][mailing-list] and #restframework IRC channel are also very active, and we've got a really impressive rate of development both on REST framework itself, and on third party packages such as the great [django-rest-framework-docs][django-rest-framework-docs] package from [Marc Gibbons][marcgibbons].
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## API changes
|
|
||||||
|
|
||||||
The 2.2 release makes a few changes to the API, in order to make it more consistent, simple, and easier to use.
|
|
||||||
|
|
||||||
### Cleaner to-many related fields
|
|
||||||
|
|
||||||
The `ManyRelatedField()` style is being deprecated in favor of a new `RelatedField(many=True)` syntax.
|
|
||||||
|
|
||||||
For example, if a user is associated with multiple questions, which we want to represent using a primary key relationship, we might use something like the following:
|
|
||||||
|
|
||||||
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
|
||||||
questions = serializers.PrimaryKeyRelatedField(many=True)
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
fields = ('username', 'questions')
|
|
||||||
|
|
||||||
The new syntax is cleaner and more obvious, and the change will also make the documentation cleaner, simplify the internal API, and make writing custom relational fields easier.
|
|
||||||
|
|
||||||
The change also applies to serializers. If you have a nested serializer, you should start using `many=True` for to-many relationships. For example, a serializer representation of an Album that can contain many Tracks might look something like this:
|
|
||||||
|
|
||||||
class TrackSerializer(serializer.ModelSerializer):
|
|
||||||
class Meta:
|
|
||||||
model = Track
|
|
||||||
fields = ('name', 'duration')
|
|
||||||
|
|
||||||
class AlbumSerializer(serializer.ModelSerializer):
|
|
||||||
tracks = TrackSerializer(many=True)
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = Album
|
|
||||||
fields = ('album_name', 'artist', 'tracks')
|
|
||||||
|
|
||||||
Additionally, the change also applies when serializing or deserializing data. For example to serialize a queryset of models you should now use the `many=True` flag.
|
|
||||||
|
|
||||||
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
|
|
||||||
serializer.data
|
|
||||||
|
|
||||||
This more explicit behavior on serializing and deserializing data [makes integration with non-ORM backends such as MongoDB easier][564], as instances to be serialized can include the `__iter__` method, without incorrectly triggering list-based serialization, or requiring workarounds.
|
|
||||||
|
|
||||||
The implicit to-many behavior on serializers, and the `ManyRelatedField` style classes will continue to function, but will raise a `PendingDeprecationWarning`, which can be made visible using the `-Wd` flag.
|
|
||||||
|
|
||||||
**Note**: If you need to forcibly turn off the implicit "`many=True` for `__iter__` objects" behavior, you can now do so by specifying `many=False`. This will become the default (instead of the current default of `None`) once the deprecation of the implicit behavior is finalised in version 2.4.
|
|
||||||
|
|
||||||
### Cleaner optional relationships
|
|
||||||
|
|
||||||
Serializer relationships for nullable Foreign Keys will change from using the current `null=True` flag, to instead using `required=False`.
|
|
||||||
|
|
||||||
For example, is a user account has an optional foreign key to a company, that you want to express using a hyperlink, you might use the following field in a `Serializer` class:
|
|
||||||
|
|
||||||
current_company = serializers.HyperlinkedRelatedField(required=False)
|
|
||||||
|
|
||||||
This is in line both with the rest of the serializer fields API, and with Django's `Form` and `ModelForm` API.
|
|
||||||
|
|
||||||
Using `required` throughout the serializers API means you won't need to consider if a particular field should take `blank` or `null` arguments instead of `required`, and also means there will be more consistent behavior for how fields are treated when they are not present in the incoming data.
|
|
||||||
|
|
||||||
The `null=True` argument will continue to function, and will imply `required=False`, but will raise a `PendingDeprecationWarning`.
|
|
||||||
|
|
||||||
### Cleaner CharField syntax
|
|
||||||
|
|
||||||
The `CharField` API previously took an optional `blank=True` argument, which was intended to differentiate between null CharField input, and blank CharField input.
|
|
||||||
|
|
||||||
In keeping with Django's CharField API, REST framework's `CharField` will only ever return the empty string, for missing or `None` inputs. The `blank` flag will no longer be in use, and you should instead just use the `required=<bool>` flag. For example:
|
|
||||||
|
|
||||||
extra_details = CharField(required=False)
|
|
||||||
|
|
||||||
The `blank` keyword argument will continue to function, but will raise a `PendingDeprecationWarning`.
|
|
||||||
|
|
||||||
### Simpler object-level permissions
|
|
||||||
|
|
||||||
Custom permissions classes previously used the signature `.has_permission(self, request, view, obj=None)`. This method would be called twice, firstly for the global permissions check, with the `obj` parameter set to `None`, and again for the object-level permissions check when appropriate, with the `obj` parameter set to the relevant model instance.
|
|
||||||
|
|
||||||
The global permissions check and object-level permissions check are now separated into two separate methods, which gives a cleaner, more obvious API.
|
|
||||||
|
|
||||||
* Global permission checks now use the `.has_permission(self, request, view)` signature.
|
|
||||||
* Object-level permission checks use a new method `.has_object_permission(self, request, view, obj)`.
|
|
||||||
|
|
||||||
For example, the following custom permission class:
|
|
||||||
|
|
||||||
class IsOwner(permissions.BasePermission):
|
|
||||||
"""
|
|
||||||
Custom permission to only allow owners of an object to view or edit it.
|
|
||||||
Model instances are expected to include an `owner` attribute.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def has_permission(self, request, view, obj=None):
|
|
||||||
if obj is None:
|
|
||||||
# Ignore global permissions check
|
|
||||||
return True
|
|
||||||
|
|
||||||
return obj.owner == request.user
|
|
||||||
|
|
||||||
Now becomes:
|
|
||||||
|
|
||||||
class IsOwner(permissions.BasePermission):
|
|
||||||
"""
|
|
||||||
Custom permission to only allow owners of an object to view or edit it.
|
|
||||||
Model instances are expected to include an `owner` attribute.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def has_object_permission(self, request, view, obj):
|
|
||||||
return obj.owner == request.user
|
|
||||||
|
|
||||||
If you're overriding the `BasePermission` class, the old-style signature will continue to function, and will correctly handle both global and object-level permissions checks, but its use will raise a `PendingDeprecationWarning`.
|
|
||||||
|
|
||||||
Note also that the usage of the internal APIs for permission checking on the `View` class has been cleaned up slightly, and is now documented and subject to the deprecation policy in all future versions.
|
|
||||||
|
|
||||||
### More explicit hyperlink relations behavior
|
|
||||||
|
|
||||||
When using a serializer with a `HyperlinkedRelatedField` or `HyperlinkedIdentityField`, the hyperlinks would previously use absolute URLs if the serializer context included a `'request'` key, and fall back to using relative URLs otherwise. This could lead to non-obvious behavior, as it might not be clear why some serializers generated absolute URLs, and others do not.
|
|
||||||
|
|
||||||
From version 2.2 onwards, serializers with hyperlinked relationships *always* require a `'request'` key to be supplied in the context dictionary. The implicit behavior will continue to function, but its use will raise a `PendingDeprecationWarning`.
|
|
||||||
|
|
||||||
[xordoquy]: https://github.com/xordoquy
|
|
||||||
[django-python-3]: https://docs.djangoproject.com/en/stable/faq/install/#can-i-use-django-with-python-3
|
|
||||||
[porting-python-3]: https://docs.djangoproject.com/en/stable/topics/python3/
|
|
||||||
[python-compat]: https://docs.djangoproject.com/en/stable/releases/1.5/#python-compatibility
|
|
||||||
[django-deprecation-policy]: https://docs.djangoproject.com/en/stable/internals/release-process/#internal-release-deprecation-policy
|
|
||||||
[credits]: http://www.django-rest-framework.org/topics/credits
|
|
||||||
[mailing-list]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
|
||||||
[django-rest-framework-docs]: https://github.com/marcgibbons/django-rest-framework-docs
|
|
||||||
[marcgibbons]: https://github.com/marcgibbons/
|
|
||||||
[564]: https://github.com/encode/django-rest-framework/issues/564
|
|
|
@ -1,264 +0,0 @@
|
||||||
# Django REST framework 2.3
|
|
||||||
|
|
||||||
REST framework 2.3 makes it even quicker and easier to build your Web APIs.
|
|
||||||
|
|
||||||
## ViewSets and Routers
|
|
||||||
|
|
||||||
The 2.3 release introduces the [ViewSet][viewset] and [Router][router] classes.
|
|
||||||
|
|
||||||
A viewset is simply a type of class-based view that allows you to group multiple views into a single common class.
|
|
||||||
|
|
||||||
Routers allow you to automatically determine the URLconf for your viewset classes.
|
|
||||||
|
|
||||||
As an example of just how simple REST framework APIs can now be, here's an API written in a single `urls.py` module:
|
|
||||||
|
|
||||||
"""
|
|
||||||
A REST framework API for viewing and editing users and groups.
|
|
||||||
"""
|
|
||||||
from django.conf.urls.defaults import url, include
|
|
||||||
from django.contrib.auth.models import User, Group
|
|
||||||
from rest_framework import viewsets, routers
|
|
||||||
|
|
||||||
|
|
||||||
# ViewSets define the view behavior.
|
|
||||||
class UserViewSet(viewsets.ModelViewSet):
|
|
||||||
model = User
|
|
||||||
|
|
||||||
class GroupViewSet(viewsets.ModelViewSet):
|
|
||||||
model = Group
|
|
||||||
|
|
||||||
|
|
||||||
# Routers provide an easy way of automatically determining the URL conf
|
|
||||||
router = routers.DefaultRouter()
|
|
||||||
router.register(r'users', UserViewSet)
|
|
||||||
router.register(r'groups', GroupViewSet)
|
|
||||||
|
|
||||||
|
|
||||||
# Wire up our API using automatic URL routing.
|
|
||||||
# Additionally, we include login URLs for the browsable API.
|
|
||||||
urlpatterns = [
|
|
||||||
url(r'^', include(router.urls)),
|
|
||||||
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
|
||||||
]
|
|
||||||
|
|
||||||
The best place to get started with ViewSets and Routers is to take a look at the [newest section in the tutorial][part-6], which demonstrates their usage.
|
|
||||||
|
|
||||||
## Simpler views
|
|
||||||
|
|
||||||
This release rationalises the API and implementation of the generic views, dropping the dependency on Django's `SingleObjectMixin` and `MultipleObjectMixin` classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with.
|
|
||||||
|
|
||||||
This improvement is reflected in improved documentation for the `GenericAPIView` base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses.
|
|
||||||
|
|
||||||
## Easier Serializers
|
|
||||||
|
|
||||||
REST framework lets you be totally explicit regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships.
|
|
||||||
|
|
||||||
The ability to specify exactly how you want to represent relationships is powerful, but it also introduces complexity. In order to keep things more simple, REST framework now allows you to include reverse relationships simply by including the field name in the `fields` metadata of the serializer class.
|
|
||||||
|
|
||||||
For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class.
|
|
||||||
|
|
||||||
class BlogSerializer(serializers.ModelSerializer):
|
|
||||||
comments = serializers.PrimaryKeyRelatedField(many=True)
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = Blog
|
|
||||||
fields = ('id', 'title', 'created', 'comments')
|
|
||||||
|
|
||||||
As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship.
|
|
||||||
|
|
||||||
class BlogSerializer(serializers.ModelSerializer):
|
|
||||||
"""
|
|
||||||
Don't need to specify the 'comments' field explicitly anymore.
|
|
||||||
"""
|
|
||||||
class Meta:
|
|
||||||
model = Blog
|
|
||||||
fields = ('id', 'title', 'created', 'comments')
|
|
||||||
|
|
||||||
Similarly, you can now easily include the primary key in hyperlinked relationships, simply by adding the field name to the metadata.
|
|
||||||
|
|
||||||
class BlogSerializer(serializers.HyperlinkedModelSerializer):
|
|
||||||
"""
|
|
||||||
This is a hyperlinked serializer, which default to using
|
|
||||||
a field named 'url' as the primary identifier.
|
|
||||||
Note that we can now easily also add in the 'id' field.
|
|
||||||
"""
|
|
||||||
class Meta:
|
|
||||||
model = Blog
|
|
||||||
fields = ('url', 'id', 'title', 'created', 'comments')
|
|
||||||
|
|
||||||
## More flexible filtering
|
|
||||||
|
|
||||||
The `FILTER_BACKEND` setting has moved to pending deprecation, in favor of a `DEFAULT_FILTER_BACKENDS` setting that takes a *list* of filter backend classes, instead of a single filter backend class.
|
|
||||||
|
|
||||||
The generic view `filter_backend` attribute has also been moved to pending deprecation in favor of a `filter_backends` setting.
|
|
||||||
|
|
||||||
Being able to specify multiple filters will allow for more flexible, powerful behavior. New filter classes to handle searching and ordering of results are planned to be released shortly.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# API Changes
|
|
||||||
|
|
||||||
## Simplified generic view classes
|
|
||||||
|
|
||||||
The functionality provided by `SingleObjectAPIView` and `MultipleObjectAPIView` base classes has now been moved into the base class `GenericAPIView`. The implementation of this base class is simple enough that providing subclasses for the base classes of detail and list views is somewhat unnecessary.
|
|
||||||
|
|
||||||
Additionally the base generic view no longer inherits from Django's `SingleObjectMixin` or `MultipleObjectMixin` classes, simplifying the implementation, and meaning you don't need to cross-reference across to Django's codebase.
|
|
||||||
|
|
||||||
Using the `SingleObjectAPIView` and `MultipleObjectAPIView` base classes continues to be supported, but will raise a `PendingDeprecationWarning`. You should instead simply use `GenericAPIView` as the base for any generic view subclasses.
|
|
||||||
|
|
||||||
### Removed attributes
|
|
||||||
|
|
||||||
The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unused and have now been entirely removed.
|
|
||||||
|
|
||||||
* context_object_name
|
|
||||||
* get_context_data()
|
|
||||||
* get_context_object_name()
|
|
||||||
|
|
||||||
The following attributes and methods, which were previously present as part of Django's generic view implementations have also been entirely removed.
|
|
||||||
|
|
||||||
* paginator_class
|
|
||||||
* get_paginator()
|
|
||||||
* get_allow_empty()
|
|
||||||
* get_slug_field()
|
|
||||||
|
|
||||||
There may be cases when removing these bits of API might mean you need to write a little more code if your view has highly customized behavior, but generally we believe that providing a coarser-grained API will make the views easier to work with, and is the right trade-off to make for the vast majority of cases.
|
|
||||||
|
|
||||||
Note that the listed attributes and methods have never been a documented part of the REST framework API, and as such are not covered by the deprecation policy.
|
|
||||||
|
|
||||||
### Simplified methods
|
|
||||||
|
|
||||||
The `get_object` and `get_paginate_by` methods no longer take an optional queryset argument. This makes overridden these methods more obvious, and a little more simple.
|
|
||||||
|
|
||||||
Using an optional queryset with these methods continues to be supported, but will raise a `PendingDeprecationWarning`.
|
|
||||||
|
|
||||||
The `paginate_queryset` method no longer takes a `page_size` argument, or returns a four-tuple of pagination information. Instead it simply takes a queryset argument, and either returns a `page` object with an appropriate page size, or returns `None`, if pagination is not configured for the view.
|
|
||||||
|
|
||||||
Using the `page_size` argument is still supported and will trigger the old-style return type, but will raise a `PendingDeprecationWarning`.
|
|
||||||
|
|
||||||
### Deprecated attributes
|
|
||||||
|
|
||||||
The following attributes are used to control queryset lookup, and have all been moved into a pending deprecation state.
|
|
||||||
|
|
||||||
* pk_url_kwarg = 'pk'
|
|
||||||
* slug_url_kwarg = 'slug'
|
|
||||||
* slug_field = 'slug'
|
|
||||||
|
|
||||||
Their usage is replaced with a single attribute:
|
|
||||||
|
|
||||||
* lookup_field = 'pk'
|
|
||||||
|
|
||||||
This attribute is used both as the regex keyword argument in the URL conf, and as the model field to filter against when looking up a model instance. To use non-pk based lookup, simply set the `lookup_field` argument to an alternative field, and ensure that the keyword argument in the url conf matches the field name.
|
|
||||||
|
|
||||||
For example, a view with 'username' based lookup might look like this:
|
|
||||||
|
|
||||||
class UserDetail(generics.RetrieveAPIView):
|
|
||||||
lookup_field = 'username'
|
|
||||||
queryset = User.objects.all()
|
|
||||||
serializer_class = UserSerializer
|
|
||||||
|
|
||||||
And would have the following entry in the urlconf:
|
|
||||||
|
|
||||||
url(r'^users/(?P<username>\w+)/$', UserDetail.as_view()),
|
|
||||||
|
|
||||||
Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`.
|
|
||||||
|
|
||||||
The `allow_empty` attribute is also deprecated. To use `allow_empty=False` style behavior you should explicitly override `get_queryset` and raise an `Http404` on empty querysets.
|
|
||||||
|
|
||||||
For example:
|
|
||||||
|
|
||||||
class DisallowEmptyQuerysetMixin(object):
|
|
||||||
def get_queryset(self):
|
|
||||||
queryset = super(DisallowEmptyQuerysetMixin, self).get_queryset()
|
|
||||||
if not queryset.exists():
|
|
||||||
raise Http404
|
|
||||||
return queryset
|
|
||||||
|
|
||||||
In our opinion removing lesser-used attributes like `allow_empty` helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-enforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views.
|
|
||||||
|
|
||||||
## Simpler URL lookups
|
|
||||||
|
|
||||||
The `HyperlinkedRelatedField` class now takes a single optional `lookup_field` argument, that replaces the `pk_url_kwarg`, `slug_url_kwarg`, and `slug_field` arguments.
|
|
||||||
|
|
||||||
For example, you might have a field that references it's relationship by a hyperlink based on a slug field:
|
|
||||||
|
|
||||||
account = HyperlinkedRelatedField(read_only=True,
|
|
||||||
lookup_field='slug',
|
|
||||||
view_name='account-detail')
|
|
||||||
|
|
||||||
Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`.
|
|
||||||
|
|
||||||
## FileUploadParser
|
|
||||||
|
|
||||||
2.3 adds a `FileUploadParser` parser class, that supports raw file uploads, in addition to the existing multipart upload support.
|
|
||||||
|
|
||||||
## DecimalField
|
|
||||||
|
|
||||||
2.3 introduces a `DecimalField` serializer field, which returns `Decimal` instances.
|
|
||||||
|
|
||||||
For most cases APIs using model fields will behave as previously, however if you are using a custom renderer, not provided by REST framework, then you may now need to add support for rendering `Decimal` instances to your renderer implementation.
|
|
||||||
|
|
||||||
## ModelSerializers and reverse relationships
|
|
||||||
|
|
||||||
The support for adding reverse relationships to the `fields` option on a `ModelSerializer` class means that the `get_related_field` and `get_nested_field` method signatures have now changed.
|
|
||||||
|
|
||||||
In the unlikely event that you're providing a custom serializer class, and implementing these methods you should note the new call signature for both methods is now `(self, model_field, related_model, to_many)`. For reverse relationships `model_field` will be `None`.
|
|
||||||
|
|
||||||
The old-style signature will continue to function but will raise a `PendingDeprecationWarning`.
|
|
||||||
|
|
||||||
## View names and descriptions
|
|
||||||
|
|
||||||
The mechanics of how the names and descriptions used in the browsable API are generated has been modified and cleaned up somewhat.
|
|
||||||
|
|
||||||
If you've been customizing this behavior, for example perhaps to use `rst` markup for the browsable API, then you'll need to take a look at the implementation to see what updates you need to make.
|
|
||||||
|
|
||||||
Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# Other notes
|
|
||||||
|
|
||||||
## More explicit style
|
|
||||||
|
|
||||||
The usage of `model` attribute in generic Views is still supported, but it's usage is generally being discouraged throughout the documentation, in favour of the setting the more explicit `queryset` and `serializer_class` attributes.
|
|
||||||
|
|
||||||
For example, the following is now the recommended style for using generic views:
|
|
||||||
|
|
||||||
class AccountListView(generics.RetrieveAPIView):
|
|
||||||
queryset = MyModel.objects.all()
|
|
||||||
serializer_class = MyModelSerializer
|
|
||||||
|
|
||||||
Using an explicit `queryset` and `serializer_class` attributes makes the functioning of the view more clear than using the shortcut `model` attribute.
|
|
||||||
|
|
||||||
It also makes the usage of the `get_queryset()` or `get_serializer_class()` methods more obvious.
|
|
||||||
|
|
||||||
class AccountListView(generics.RetrieveAPIView):
|
|
||||||
serializer_class = MyModelSerializer
|
|
||||||
|
|
||||||
def get_queryset(self):
|
|
||||||
"""
|
|
||||||
Determine the queryset dynamically, depending on the
|
|
||||||
user making the request.
|
|
||||||
|
|
||||||
Note that overriding this method follows on more obviously now
|
|
||||||
that an explicit `queryset` attribute is the usual view style.
|
|
||||||
"""
|
|
||||||
return self.user.accounts
|
|
||||||
|
|
||||||
## Django 1.3 support
|
|
||||||
|
|
||||||
The 2.3.x release series will be the last series to provide compatibility with Django 1.3.
|
|
||||||
|
|
||||||
## Version 2.2 API changes
|
|
||||||
|
|
||||||
All API changes in 2.2 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default.
|
|
||||||
|
|
||||||
## What comes next?
|
|
||||||
|
|
||||||
* Support for read-write nested serializers is almost complete, and due to be released in the next few weeks.
|
|
||||||
* Extra filter backends for searching and ordering of results are planned to be added shortly.
|
|
||||||
|
|
||||||
The next few months should see a renewed focus on addressing outstanding tickets. The 2.4 release is currently planned for around August-September.
|
|
||||||
|
|
||||||
[viewset]: ../api-guide/viewsets.md
|
|
||||||
[router]: ../api-guide/routers.md
|
|
||||||
[part-6]: ../tutorial/6-viewsets-and-routers.md
|
|
|
@ -1,172 +0,0 @@
|
||||||
# Django REST framework 2.4
|
|
||||||
|
|
||||||
The 2.4 release is largely an intermediate step, tying up some outstanding issues prior to the 3.x series.
|
|
||||||
|
|
||||||
## Version requirements
|
|
||||||
|
|
||||||
Support for Django 1.3 has been dropped.
|
|
||||||
The lowest supported version of Django is now 1.4.2.
|
|
||||||
|
|
||||||
The current plan is for REST framework to remain in lockstep with [Django's long-term support policy][lts-releases].
|
|
||||||
|
|
||||||
## Django 1.7 support
|
|
||||||
|
|
||||||
The optional authtoken application now includes support for *both* Django 1.7 schema migrations, *and* for old-style `south` migrations.
|
|
||||||
|
|
||||||
**If you are using authtoken, and you want to continue using `south`, you must upgrade your `south` package to version 1.0.**
|
|
||||||
|
|
||||||
## Deprecation of `.model` view attribute
|
|
||||||
|
|
||||||
The `.model` attribute on view classes is an optional shortcut for either or both of `.serializer_class` and `.queryset`. Its usage results in more implicit, less obvious behavior.
|
|
||||||
|
|
||||||
The documentation has previously stated that usage of the more explicit style is prefered, and we're now taking that one step further and deprecating the usage of the `.model` shortcut.
|
|
||||||
|
|
||||||
Doing so will mean that there are cases of API code where you'll now need to include a serializer class where you previously were just using the `.model` shortcut. However we firmly believe that it is the right trade-off to make.
|
|
||||||
|
|
||||||
Removing the shortcut takes away an unnecessary layer of abstraction, and makes your codebase more explicit without any significant extra complexity. It also results in better consistency, as there's now only one way to set the serializer class and queryset attributes for the view, instead of two.
|
|
||||||
|
|
||||||
The `DEFAULT_MODEL_SERIALIZER_CLASS` API setting is now also deprecated.
|
|
||||||
|
|
||||||
## Updated test runner
|
|
||||||
|
|
||||||
We now have a new test runner for developing against the project,, that uses the excellent [py.test](https://docs.pytest.org/) library.
|
|
||||||
|
|
||||||
To use it make sure you have first installed the test requirements.
|
|
||||||
|
|
||||||
pip install -r requirements-test.txt
|
|
||||||
|
|
||||||
Then run the `runtests.py` script.
|
|
||||||
|
|
||||||
./runtests.py
|
|
||||||
|
|
||||||
The new test runner also includes [flake8](https://flake8.readthedocs.io) code linting, which should help keep our coding style consistent.
|
|
||||||
|
|
||||||
#### Test runner flags
|
|
||||||
|
|
||||||
Run using a more concise output style.
|
|
||||||
|
|
||||||
./runtests -q
|
|
||||||
|
|
||||||
Run the tests using a more concise output style, no coverage, no flake8.
|
|
||||||
|
|
||||||
./runtests --fast
|
|
||||||
|
|
||||||
Don't run the flake8 code linting.
|
|
||||||
|
|
||||||
./runtests --nolint
|
|
||||||
|
|
||||||
Only run the flake8 code linting, don't run the tests.
|
|
||||||
|
|
||||||
./runtests --lintonly
|
|
||||||
|
|
||||||
Run the tests for a given test case.
|
|
||||||
|
|
||||||
./runtests MyTestCase
|
|
||||||
|
|
||||||
Run the tests for a given test method.
|
|
||||||
|
|
||||||
./runtests MyTestCase.test_this_method
|
|
||||||
|
|
||||||
Shorter form to run the tests for a given test method.
|
|
||||||
|
|
||||||
./runtests test_this_method
|
|
||||||
|
|
||||||
Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
|
|
||||||
|
|
||||||
## Improved viewset routing
|
|
||||||
|
|
||||||
The `@action` and `@link` decorators were inflexible in that they only allowed additional routes to be added against instance style URLs, not against list style URLs.
|
|
||||||
|
|
||||||
The `@action` and `@link` decorators have now been moved to pending deprecation, and the `@list_route` and `@detail_route` decorators have been introduced.
|
|
||||||
|
|
||||||
Here's an example of using the new decorators. Firstly we have a detail-type route named "set_password" that acts on a single instance, and takes a `pk` argument in the URL. Secondly we have a list-type route named "recent_users" that acts on a queryset, and does not take any arguments in the URL.
|
|
||||||
|
|
||||||
class UserViewSet(viewsets.ModelViewSet):
|
|
||||||
"""
|
|
||||||
A viewset that provides the standard actions
|
|
||||||
"""
|
|
||||||
queryset = User.objects.all()
|
|
||||||
serializer_class = UserSerializer
|
|
||||||
|
|
||||||
@detail_route(methods=['post'])
|
|
||||||
def set_password(self, request, pk=None):
|
|
||||||
user = self.get_object()
|
|
||||||
serializer = PasswordSerializer(data=request.DATA)
|
|
||||||
if serializer.is_valid():
|
|
||||||
user.set_password(serializer.data['password'])
|
|
||||||
user.save()
|
|
||||||
return Response({'status': 'password set'})
|
|
||||||
else:
|
|
||||||
return Response(serializer.errors,
|
|
||||||
status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
@list_route()
|
|
||||||
def recent_users(self, request):
|
|
||||||
recent_users = User.objects.all().order('-last_login')
|
|
||||||
page = self.paginate_queryset(recent_users)
|
|
||||||
serializer = self.get_pagination_serializer(page)
|
|
||||||
return Response(serializer.data)
|
|
||||||
|
|
||||||
For more details, see the [viewsets documentation](../api-guide/viewsets.md).
|
|
||||||
|
|
||||||
## Throttle behavior
|
|
||||||
|
|
||||||
There's one bugfix in 2.4 that's worth calling out, as it will *invalidate existing throttle caches* when you upgrade.
|
|
||||||
|
|
||||||
We've now fixed a typo on the `cache_format` attribute. Previously this was named `"throtte_%(scope)s_%(ident)s"`, it is now `"throttle_%(scope)s_%(ident)s"`.
|
|
||||||
|
|
||||||
If you're concerned about the invalidation you have two options.
|
|
||||||
|
|
||||||
* Manually pre-populate your cache with the fixed version.
|
|
||||||
* Set the `cache_format` attribute on your throttle class in order to retain the previous incorrect spelling.
|
|
||||||
|
|
||||||
## Other features
|
|
||||||
|
|
||||||
There are also a number of other features and bugfixes as [listed in the release notes][2-4-release-notes]. In particular these include:
|
|
||||||
|
|
||||||
[Customizable view name and description functions][view-name-and-description-settings] for use with the browsable API, by using the `VIEW_NAME_FUNCTION` and `VIEW_DESCRIPTION_FUNCTION` settings.
|
|
||||||
|
|
||||||
Smarter [client IP identification for throttling][client-ip-identification], with the addition of the `NUM_PROXIES` setting.
|
|
||||||
|
|
||||||
Added the standardized `Retry-After` header to throttled responses, as per [RFC 6585](https://tools.ietf.org/html/rfc6585). This should now be used in preference to the custom `X-Throttle-Wait-Seconds` header which will be fully deprecated in 3.0.
|
|
||||||
|
|
||||||
## Deprecations
|
|
||||||
|
|
||||||
All API changes in 2.3 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default.
|
|
||||||
|
|
||||||
All API changes in 2.3 that previously raised `DeprecationWarning` have now been removed entirely.
|
|
||||||
|
|
||||||
Furter details on these deprecations is available in the [2.3 announcement][2-3-announcement].
|
|
||||||
|
|
||||||
## Labels and milestones
|
|
||||||
|
|
||||||
Although not strictly part of the 2.4 release it's also worth noting here that we've been working hard towards improving our triage process.
|
|
||||||
|
|
||||||
The [labels that we use in GitHub][github-labels] have been cleaned up, and all existing tickets triaged. Any given ticket should have one and only one label, indicating its current state.
|
|
||||||
|
|
||||||
We've also [started using milestones][github-milestones] in order to track tickets against particular releases.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
**Above**: *Overview of our current use of labels and milestones in GitHub.*
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
We hope both of these changes will help make the management process more clear and obvious and help keep tickets well-organised and relevant.
|
|
||||||
|
|
||||||
## Next steps
|
|
||||||
|
|
||||||
The next planned release will be 3.0, featuring an improved and simplified serializer implementation.
|
|
||||||
|
|
||||||
Once again, many thanks to all the generous [backers and sponsors][kickstarter-sponsors] who've helped make this possible!
|
|
||||||
|
|
||||||
[lts-releases]: https://docs.djangoproject.com/en/stable/internals/release-process/#long-term-support-lts-releases
|
|
||||||
[2-4-release-notes]: release-notes#240
|
|
||||||
[view-name-and-description-settings]: ../api-guide/settings#view-names-and-descriptions
|
|
||||||
[client-ip-identification]: ../api-guide/throttling#how-clients-are-identified
|
|
||||||
[2-3-announcement]: 2.3-announcement
|
|
||||||
[github-labels]: https://github.com/encode/django-rest-framework/issues
|
|
||||||
[github-milestones]: https://github.com/encode/django-rest-framework/milestones
|
|
||||||
[kickstarter-sponsors]: kickstarter-announcement#sponsors
|
|
|
@ -1,6 +1,6 @@
|
||||||
# HTML & Forms
|
# HTML & Forms
|
||||||
|
|
||||||
REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.
|
REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can be used as HTML forms and rendered in templates.
|
||||||
|
|
||||||
## Rendering HTML
|
## Rendering HTML
|
||||||
|
|
||||||
|
|
|
@ -1,97 +0,0 @@
|
||||||
# Django REST framework 2.0
|
|
||||||
|
|
||||||
> Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result.
|
|
||||||
>
|
|
||||||
> — [Roy Fielding][cite]
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Announcement:** REST framework 2 released - Tue 30th Oct 2012
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
REST framework 2 is an almost complete reworking of the original framework, which comprehensively addresses some of the original design issues.
|
|
||||||
|
|
||||||
Because the latest version should be considered a re-release, rather than an incremental improvement, we've skipped a version, and called this release Django REST framework 2.0.
|
|
||||||
|
|
||||||
This article is intended to give you a flavor of what REST framework 2 is, and why you might want to give it a try.
|
|
||||||
|
|
||||||
## User feedback
|
|
||||||
|
|
||||||
Before we get cracking, let's start with the hard sell, with a few bits of feedback from some early adopters…
|
|
||||||
|
|
||||||
"Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - [Kit La Touche][quote1]
|
|
||||||
|
|
||||||
"Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - [Ian Strachan][quote2]
|
|
||||||
|
|
||||||
"I switched to the 2.0 branch and I don't regret it - fully refactored my code in another ½ day and it's *much* more to my tastes" - [Bruno Desthuilliers][quote3]
|
|
||||||
|
|
||||||
Sounds good, right? Let's get into some details...
|
|
||||||
|
|
||||||
## Serialization
|
|
||||||
|
|
||||||
REST framework 2 includes a totally re-worked serialization engine, that was initially intended as a replacement for Django's existing inflexible fixture serialization, and which meets the following design goals:
|
|
||||||
|
|
||||||
* A declarative serialization API, that mirrors Django's `Forms`/`ModelForms` API.
|
|
||||||
* Structural concerns are decoupled from encoding concerns.
|
|
||||||
* Able to support rendering and parsing to many formats, including both machine-readable representations and HTML forms.
|
|
||||||
* Validation that can be mapped to obvious and comprehensive error responses.
|
|
||||||
* Serializers that support both nested, flat, and partially-nested representations.
|
|
||||||
* Relationships that can be expressed as primary keys, hyperlinks, slug fields, and other custom representations.
|
|
||||||
|
|
||||||
Mapping between the internal state of the system and external representations of that state is the core concern of building Web APIs. Designing serializers that allow the developer to do so in a flexible and obvious way is a deceptively difficult design task, and with the new serialization API we think we've pretty much nailed it.
|
|
||||||
|
|
||||||
## Generic views
|
|
||||||
|
|
||||||
When REST framework was initially released at the start of 2011, the current Django release was version 1.2. REST framework included a backport of Django 1.3's upcoming `View` class, but it didn't take full advantage of the generic view implementations.
|
|
||||||
|
|
||||||
With the new release the generic views in REST framework now tie in with Django's generic views. The end result is that framework is clean, lightweight and easy to use.
|
|
||||||
|
|
||||||
## Requests, Responses & Views
|
|
||||||
|
|
||||||
REST framework 2 includes `Request` and `Response` classes, than are used in place of Django's existing `HttpRequest` and `HttpResponse` classes. Doing so allows logic such as parsing the incoming request or rendering the outgoing response to be supported transparently by the framework.
|
|
||||||
|
|
||||||
The `Request`/`Response` approach leads to a much cleaner API, less logic in the view itself, and a simple, obvious request-response cycle.
|
|
||||||
|
|
||||||
REST framework 2 also allows you to work with both function-based and class-based views. For simple API views all you need is a single `@api_view` decorator, and you're good to go.
|
|
||||||
|
|
||||||
|
|
||||||
## API Design
|
|
||||||
|
|
||||||
Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independently of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions.
|
|
||||||
|
|
||||||
## The Browsable API
|
|
||||||
|
|
||||||
Django REST framework's most unique feature is the way it is able to serve up both machine-readable representations, and a fully browsable HTML representation to the same endpoints.
|
|
||||||
|
|
||||||
Browsable Web APIs are easier to work with, visualize and debug, and generally makes it easier and more frictionless to inspect and work with.
|
|
||||||
|
|
||||||
With REST framework 2, the browsable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with.
|
|
||||||
|
|
||||||
There are also some functionality improvements - actions such as as `POST` and `DELETE` will only display if the user has the appropriate permissions.
|
|
||||||
|
|
||||||
![Browsable API][image]
|
|
||||||
|
|
||||||
**Image above**: An example of the browsable API in REST framework 2
|
|
||||||
|
|
||||||
## Documentation
|
|
||||||
|
|
||||||
As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling.
|
|
||||||
|
|
||||||
We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great.
|
|
||||||
|
|
||||||
## Summary
|
|
||||||
|
|
||||||
In short, we've engineered the hell outta this thing, and we're incredibly proud of the result.
|
|
||||||
|
|
||||||
If you're interested please take a browse around the documentation. [The tutorial][tut] is a great place to get started.
|
|
||||||
|
|
||||||
There's also a [live sandbox version of the tutorial API][sandbox] available for testing.
|
|
||||||
|
|
||||||
[cite]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-724
|
|
||||||
[quote1]: https://twitter.com/kobutsu/status/261689665952833536
|
|
||||||
[quote2]: https://groups.google.com/d/msg/django-rest-framework/heRGHzG6BWQ/ooVURgpwVC0J
|
|
||||||
[quote3]: https://groups.google.com/d/msg/django-rest-framework/flsXbvYqRoY/9lSyntOf5cUJ
|
|
||||||
[image]: ../img/quickstart.png
|
|
||||||
[tut]: ../tutorial/1-serialization.md
|
|
||||||
[sandbox]: https://restframework.herokuapp.com/
|
|
|
@ -12,17 +12,17 @@ Nested data structures are easy enough to work with if they're read-only - simpl
|
||||||
|
|
||||||
*Example of a **read-only** nested serializer. Nothing complex to worry about here.*
|
*Example of a **read-only** nested serializer. Nothing complex to worry about here.*
|
||||||
|
|
||||||
class ToDoItemSerializer(serializers.ModelSerializer):
|
class ToDoItemSerializer(serializers.ModelSerializer):
|
||||||
class Meta:
|
class Meta:
|
||||||
model = ToDoItem
|
model = ToDoItem
|
||||||
fields = ('text', 'is_completed')
|
fields = ('text', 'is_completed')
|
||||||
|
|
||||||
class ToDoListSerializer(serializers.ModelSerializer):
|
class ToDoListSerializer(serializers.ModelSerializer):
|
||||||
items = ToDoItemSerializer(many=True, read_only=True)
|
items = ToDoItemSerializer(many=True, read_only=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = ToDoList
|
model = ToDoList
|
||||||
fields = ('title', 'items')
|
fields = ('title', 'items')
|
||||||
|
|
||||||
Some example output from our serializer.
|
Some example output from our serializer.
|
||||||
|
|
||||||
|
|
|
@ -154,9 +154,9 @@ At this point we've translated the model instance into Python native datatypes.
|
||||||
|
|
||||||
Deserialization is similar. First we parse a stream into Python native datatypes...
|
Deserialization is similar. First we parse a stream into Python native datatypes...
|
||||||
|
|
||||||
from django.utils.six import BytesIO
|
import io
|
||||||
|
|
||||||
stream = BytesIO(content)
|
stream = io.BytesIO(content)
|
||||||
data = JSONParser().parse(stream)
|
data = JSONParser().parse(stream)
|
||||||
|
|
||||||
...then we restore those native datatypes into a fully populated object instance.
|
...then we restore those native datatypes into a fully populated object instance.
|
||||||
|
@ -299,18 +299,18 @@ Now we can start up a sample server that serves our snippets.
|
||||||
|
|
||||||
Quit out of the shell...
|
Quit out of the shell...
|
||||||
|
|
||||||
quit()
|
quit()
|
||||||
|
|
||||||
...and start up Django's development server.
|
...and start up Django's development server.
|
||||||
|
|
||||||
python manage.py runserver
|
python manage.py runserver
|
||||||
|
|
||||||
Validating models...
|
Validating models...
|
||||||
|
|
||||||
0 errors found
|
0 errors found
|
||||||
Django version 1.11, using settings 'tutorial.settings'
|
Django version 1.11, using settings 'tutorial.settings'
|
||||||
Development server is running at http://127.0.0.1:8000/
|
Development server is running at http://127.0.0.1:8000/
|
||||||
Quit the server with CONTROL-C.
|
Quit the server with CONTROL-C.
|
||||||
|
|
||||||
In another terminal window, we can test the server.
|
In another terminal window, we can test the server.
|
||||||
|
|
||||||
|
|
|
@ -83,7 +83,7 @@ We'll also add a couple of views to `views.py`. We'd like to just use read-only
|
||||||
|
|
||||||
Make sure to also import the `UserSerializer` class
|
Make sure to also import the `UserSerializer` class
|
||||||
|
|
||||||
from snippets.serializers import UserSerializer
|
from snippets.serializers import UserSerializer
|
||||||
|
|
||||||
Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `snippets/urls.py`.
|
Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `snippets/urls.py`.
|
||||||
|
|
||||||
|
|
|
@ -56,7 +56,7 @@ We'll also create an initial user named `admin` with a password of `password123`
|
||||||
|
|
||||||
python manage.py createsuperuser --email admin@example.com --username admin
|
python manage.py createsuperuser --email admin@example.com --username admin
|
||||||
|
|
||||||
Once you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding...
|
Once you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding...
|
||||||
|
|
||||||
## Serializers
|
## Serializers
|
||||||
|
|
||||||
|
|
37
mkdocs.yml
37
mkdocs.yml
|
@ -59,21 +59,22 @@ pages:
|
||||||
- 'Browser Enhancements': 'topics/browser-enhancements.md'
|
- 'Browser Enhancements': 'topics/browser-enhancements.md'
|
||||||
- 'The Browsable API': 'topics/browsable-api.md'
|
- 'The Browsable API': 'topics/browsable-api.md'
|
||||||
- 'REST, Hypermedia & HATEOAS': 'topics/rest-hypermedia-hateoas.md'
|
- 'REST, Hypermedia & HATEOAS': 'topics/rest-hypermedia-hateoas.md'
|
||||||
- 'Third Party Packages': 'topics/third-party-packages.md'
|
- Community:
|
||||||
- 'Tutorials and Resources': 'topics/tutorials-and-resources.md'
|
- 'Tutorials and Resources': 'community/tutorials-and-resources.md'
|
||||||
- 'Contributing to REST framework': 'topics/contributing.md'
|
- 'Third Party Packages': 'community/third-party-packages.md'
|
||||||
- 'Project management': 'topics/project-management.md'
|
- 'Contributing to REST framework': 'community/contributing.md'
|
||||||
- 'Jobs': 'topics/jobs.md'
|
- 'Project management': 'community/project-management.md'
|
||||||
- '3.0 Announcement': 'topics/3.0-announcement.md'
|
- 'Release Notes': 'community/release-notes.md'
|
||||||
- '3.1 Announcement': 'topics/3.1-announcement.md'
|
- '3.8 Announcement': 'community/3.8-announcement.md'
|
||||||
- '3.2 Announcement': 'topics/3.2-announcement.md'
|
- '3.7 Announcement': 'community/3.7-announcement.md'
|
||||||
- '3.3 Announcement': 'topics/3.3-announcement.md'
|
- '3.6 Announcement': 'community/3.6-announcement.md'
|
||||||
- '3.4 Announcement': 'topics/3.4-announcement.md'
|
- '3.5 Announcement': 'community/3.5-announcement.md'
|
||||||
- '3.5 Announcement': 'topics/3.5-announcement.md'
|
- '3.4 Announcement': 'community/3.4-announcement.md'
|
||||||
- '3.6 Announcement': 'topics/3.6-announcement.md'
|
- '3.3 Announcement': 'community/3.3-announcement.md'
|
||||||
- '3.7 Announcement': 'topics/3.7-announcement.md'
|
- '3.2 Announcement': 'community/3.2-announcement.md'
|
||||||
- '3.8 Announcement': 'topics/3.8-announcement.md'
|
- '3.1 Announcement': 'community/3.1-announcement.md'
|
||||||
- 'Kickstarter Announcement': 'topics/kickstarter-announcement.md'
|
- '3.0 Announcement': 'community/3.0-announcement.md'
|
||||||
- 'Mozilla Grant': 'topics/mozilla-grant.md'
|
- 'Kickstarter Announcement': 'community/kickstarter-announcement.md'
|
||||||
- 'Funding': 'topics/funding.md'
|
- 'Mozilla Grant': 'community/mozilla-grant.md'
|
||||||
- 'Release Notes': 'topics/release-notes.md'
|
- 'Funding': 'community/funding.md'
|
||||||
|
- 'Jobs': 'community/jobs.md'
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
# Optional packages which may be used with REST framework.
|
# Optional packages which may be used with REST framework.
|
||||||
pytz==2017.2
|
psycopg2-binary==2.7.5
|
||||||
psycopg2-binary==2.7.4
|
markdown==2.6.11
|
||||||
markdown==2.6.4
|
|
||||||
django-guardian==1.4.9
|
django-guardian==1.4.9
|
||||||
django-filter==1.1.0
|
django-filter==1.1.0
|
||||||
coreapi==2.3.1
|
coreapi==2.3.1
|
||||||
|
|
|
@ -6,13 +6,12 @@ from __future__ import unicode_literals
|
||||||
import base64
|
import base64
|
||||||
import binascii
|
import binascii
|
||||||
|
|
||||||
from django.contrib.auth import get_user_model
|
from django.contrib.auth import authenticate, get_user_model
|
||||||
from django.middleware.csrf import CsrfViewMiddleware
|
from django.middleware.csrf import CsrfViewMiddleware
|
||||||
from django.utils.six import text_type
|
from django.utils.six import text_type
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
from rest_framework import HTTP_HEADER_ENCODING, exceptions
|
from rest_framework import HTTP_HEADER_ENCODING, exceptions
|
||||||
from rest_framework.compat import authenticate
|
|
||||||
|
|
||||||
|
|
||||||
def get_authorization_header(request):
|
def get_authorization_header(request):
|
||||||
|
@ -136,7 +135,10 @@ class SessionAuthentication(BaseAuthentication):
|
||||||
"""
|
"""
|
||||||
Enforce CSRF validation for session based authentication.
|
Enforce CSRF validation for session based authentication.
|
||||||
"""
|
"""
|
||||||
reason = CSRFCheck().process_view(request, None, (), {})
|
check = CSRFCheck()
|
||||||
|
# populates request.META['CSRF_COOKIE'], which is used in process_view()
|
||||||
|
check.process_request(request)
|
||||||
|
reason = check.process_view(request, None, (), {})
|
||||||
if reason:
|
if reason:
|
||||||
# CSRF failed, bail with explicit error message
|
# CSRF failed, bail with explicit error message
|
||||||
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
|
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
|
from django.contrib.auth import authenticate
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
from rest_framework.compat import authenticate
|
|
||||||
|
|
||||||
|
|
||||||
class AuthTokenSerializer(serializers.Serializer):
|
class AuthTokenSerializer(serializers.Serializer):
|
||||||
|
|
|
@ -5,12 +5,18 @@ versions of Django/Python, and compatibility wrappers around optional packages.
|
||||||
|
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
import django
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core import validators
|
from django.core import validators
|
||||||
from django.utils import six
|
from django.utils import six
|
||||||
from django.views.generic import View
|
from django.views.generic import View
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Python 3 (required for 3.8+)
|
||||||
|
from collections.abc import Mapping # noqa
|
||||||
|
except ImportError:
|
||||||
|
# Python 2.7
|
||||||
|
from collections import Mapping # noqa
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from django.urls import ( # noqa
|
from django.urls import ( # noqa
|
||||||
URLPattern,
|
URLPattern,
|
||||||
|
@ -139,14 +145,11 @@ except ImportError:
|
||||||
requests = None
|
requests = None
|
||||||
|
|
||||||
|
|
||||||
# Django-guardian is optional. Import only if guardian is in INSTALLED_APPS
|
def is_guardian_installed():
|
||||||
# Fixes (#1712). We keep the try/except for the test suite.
|
"""
|
||||||
guardian = None
|
django-guardian is optional and only imported if in INSTALLED_APPS.
|
||||||
try:
|
"""
|
||||||
if 'guardian' in settings.INSTALLED_APPS:
|
return 'guardian' in settings.INSTALLED_APPS
|
||||||
import guardian # noqa
|
|
||||||
except ImportError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
# PATCH method is not implemented by Django
|
# PATCH method is not implemented by Django
|
||||||
|
@ -245,12 +248,6 @@ else:
|
||||||
def md_filter_add_syntax_highlight(md):
|
def md_filter_add_syntax_highlight(md):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# pytz is required from Django 1.11. Remove when dropping Django 1.10 support.
|
|
||||||
try:
|
|
||||||
import pytz # noqa
|
|
||||||
from pytz.exceptions import InvalidTimeError
|
|
||||||
except ImportError:
|
|
||||||
InvalidTimeError = Exception
|
|
||||||
|
|
||||||
# Django 1.x url routing syntax. Remove when dropping Django 1.11 support.
|
# Django 1.x url routing syntax. Remove when dropping Django 1.11 support.
|
||||||
try:
|
try:
|
||||||
|
@ -301,11 +298,3 @@ class MinLengthValidator(CustomValidatorMessage, validators.MinLengthValidator):
|
||||||
|
|
||||||
class MaxLengthValidator(CustomValidatorMessage, validators.MaxLengthValidator):
|
class MaxLengthValidator(CustomValidatorMessage, validators.MaxLengthValidator):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def authenticate(request=None, **credentials):
|
|
||||||
from django.contrib.auth import authenticate
|
|
||||||
if django.VERSION < (1, 11):
|
|
||||||
return authenticate(**credentials)
|
|
||||||
else:
|
|
||||||
return authenticate(request=request, **credentials)
|
|
||||||
|
|
|
@ -11,6 +11,7 @@ from __future__ import unicode_literals
|
||||||
import types
|
import types
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
|
from django.forms.utils import pretty_name
|
||||||
from django.utils import six
|
from django.utils import six
|
||||||
|
|
||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
|
@ -130,7 +131,7 @@ def schema(view_inspector):
|
||||||
return decorator
|
return decorator
|
||||||
|
|
||||||
|
|
||||||
def action(methods=None, detail=None, url_path=None, url_name=None, **kwargs):
|
def action(methods=None, detail=None, name=None, url_path=None, url_name=None, **kwargs):
|
||||||
"""
|
"""
|
||||||
Mark a ViewSet method as a routable action.
|
Mark a ViewSet method as a routable action.
|
||||||
|
|
||||||
|
@ -145,15 +146,81 @@ def action(methods=None, detail=None, url_path=None, url_name=None, **kwargs):
|
||||||
)
|
)
|
||||||
|
|
||||||
def decorator(func):
|
def decorator(func):
|
||||||
func.bind_to_methods = methods
|
func.mapping = MethodMapper(func, methods)
|
||||||
|
|
||||||
func.detail = detail
|
func.detail = detail
|
||||||
|
func.name = name if name else pretty_name(func.__name__)
|
||||||
func.url_path = url_path if url_path else func.__name__
|
func.url_path = url_path if url_path else func.__name__
|
||||||
func.url_name = url_name if url_name else func.__name__.replace('_', '-')
|
func.url_name = url_name if url_name else func.__name__.replace('_', '-')
|
||||||
func.kwargs = kwargs
|
func.kwargs = kwargs
|
||||||
|
func.kwargs.update({
|
||||||
|
'name': func.name,
|
||||||
|
'description': func.__doc__ or None
|
||||||
|
})
|
||||||
|
|
||||||
return func
|
return func
|
||||||
return decorator
|
return decorator
|
||||||
|
|
||||||
|
|
||||||
|
class MethodMapper(dict):
|
||||||
|
"""
|
||||||
|
Enables mapping HTTP methods to different ViewSet methods for a single,
|
||||||
|
logical action.
|
||||||
|
|
||||||
|
Example usage:
|
||||||
|
|
||||||
|
class MyViewSet(ViewSet):
|
||||||
|
|
||||||
|
@action(detail=False)
|
||||||
|
def example(self, request, **kwargs):
|
||||||
|
...
|
||||||
|
|
||||||
|
@example.mapping.post
|
||||||
|
def create_example(self, request, **kwargs):
|
||||||
|
...
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, action, methods):
|
||||||
|
self.action = action
|
||||||
|
for method in methods:
|
||||||
|
self[method] = self.action.__name__
|
||||||
|
|
||||||
|
def _map(self, method, func):
|
||||||
|
assert method not in self, (
|
||||||
|
"Method '%s' has already been mapped to '.%s'." % (method, self[method]))
|
||||||
|
assert func.__name__ != self.action.__name__, (
|
||||||
|
"Method mapping does not behave like the property decorator. You "
|
||||||
|
"cannot use the same method name for each mapping declaration.")
|
||||||
|
|
||||||
|
self[method] = func.__name__
|
||||||
|
|
||||||
|
return func
|
||||||
|
|
||||||
|
def get(self, func):
|
||||||
|
return self._map('get', func)
|
||||||
|
|
||||||
|
def post(self, func):
|
||||||
|
return self._map('post', func)
|
||||||
|
|
||||||
|
def put(self, func):
|
||||||
|
return self._map('put', func)
|
||||||
|
|
||||||
|
def patch(self, func):
|
||||||
|
return self._map('patch', func)
|
||||||
|
|
||||||
|
def delete(self, func):
|
||||||
|
return self._map('delete', func)
|
||||||
|
|
||||||
|
def head(self, func):
|
||||||
|
return self._map('head', func)
|
||||||
|
|
||||||
|
def options(self, func):
|
||||||
|
return self._map('options', func)
|
||||||
|
|
||||||
|
def trace(self, func):
|
||||||
|
return self._map('trace', func)
|
||||||
|
|
||||||
|
|
||||||
def detail_route(methods=None, **kwargs):
|
def detail_route(methods=None, **kwargs):
|
||||||
"""
|
"""
|
||||||
Used to mark a method on a ViewSet that should be routed for detail requests.
|
Used to mark a method on a ViewSet that should be routed for detail requests.
|
||||||
|
|
|
@ -29,11 +29,12 @@ from django.utils.functional import lazy
|
||||||
from django.utils.ipv6 import clean_ipv6_address
|
from django.utils.ipv6 import clean_ipv6_address
|
||||||
from django.utils.timezone import utc
|
from django.utils.timezone import utc
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
from pytz.exceptions import InvalidTimeError
|
||||||
|
|
||||||
from rest_framework import ISO_8601
|
from rest_framework import ISO_8601
|
||||||
from rest_framework.compat import (
|
from rest_framework.compat import (
|
||||||
InvalidTimeError, MaxLengthValidator, MaxValueValidator,
|
MaxLengthValidator, MaxValueValidator, MinLengthValidator,
|
||||||
MinLengthValidator, MinValueValidator, unicode_repr, unicode_to_repr
|
MinValueValidator, unicode_repr, unicode_to_repr
|
||||||
)
|
)
|
||||||
from rest_framework.exceptions import ErrorDetail, ValidationError
|
from rest_framework.exceptions import ErrorDetail, ValidationError
|
||||||
from rest_framework.settings import api_settings
|
from rest_framework.settings import api_settings
|
||||||
|
@ -233,10 +234,21 @@ def get_error_detail(exc_info):
|
||||||
with the `code` populated.
|
with the `code` populated.
|
||||||
"""
|
"""
|
||||||
code = getattr(exc_info, 'code', None) or 'invalid'
|
code = getattr(exc_info, 'code', None) or 'invalid'
|
||||||
return [
|
|
||||||
ErrorDetail(msg, code=code)
|
try:
|
||||||
for msg in exc_info.messages
|
error_dict = exc_info.error_dict
|
||||||
]
|
except AttributeError:
|
||||||
|
return [
|
||||||
|
ErrorDetail(error.message % (error.params or ()),
|
||||||
|
code=error.code if error.code else code)
|
||||||
|
for error in exc_info.error_list]
|
||||||
|
return {
|
||||||
|
k: [
|
||||||
|
ErrorDetail(error.message % (error.params or ()),
|
||||||
|
code=error.code if error.code else code)
|
||||||
|
for error in errors
|
||||||
|
] for k, errors in error_dict.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class CreateOnlyDefault(object):
|
class CreateOnlyDefault(object):
|
||||||
|
|
|
@ -16,7 +16,9 @@ from django.utils import six
|
||||||
from django.utils.encoding import force_text
|
from django.utils.encoding import force_text
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
from rest_framework.compat import coreapi, coreschema, distinct, guardian
|
from rest_framework.compat import (
|
||||||
|
coreapi, coreschema, distinct, is_guardian_installed
|
||||||
|
)
|
||||||
from rest_framework.settings import api_settings
|
from rest_framework.settings import api_settings
|
||||||
|
|
||||||
|
|
||||||
|
@ -282,7 +284,7 @@ class DjangoObjectPermissionsFilter(BaseFilterBackend):
|
||||||
has read object level permissions.
|
has read object level permissions.
|
||||||
"""
|
"""
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
assert guardian, 'Using DjangoObjectPermissionsFilter, but django-guardian is not installed'
|
assert is_guardian_installed(), 'Using DjangoObjectPermissionsFilter, but django-guardian is not installed'
|
||||||
|
|
||||||
perm_format = '%(app_label)s.view_%(model_name)s'
|
perm_format = '%(app_label)s.view_%(model_name)s'
|
||||||
|
|
||||||
|
@ -290,6 +292,7 @@ class DjangoObjectPermissionsFilter(BaseFilterBackend):
|
||||||
# We want to defer this import until run-time, rather than import-time.
|
# We want to defer this import until run-time, rather than import-time.
|
||||||
# See https://github.com/encode/django-rest-framework/issues/4608
|
# See https://github.com/encode/django-rest-framework/issues/4608
|
||||||
# (Also see #1624 for why we need to make this import explicitly)
|
# (Also see #1624 for why we need to make this import explicitly)
|
||||||
|
from guardian import VERSION as guardian_version
|
||||||
from guardian.shortcuts import get_objects_for_user
|
from guardian.shortcuts import get_objects_for_user
|
||||||
|
|
||||||
extra = {}
|
extra = {}
|
||||||
|
@ -300,7 +303,7 @@ class DjangoObjectPermissionsFilter(BaseFilterBackend):
|
||||||
'model_name': model_cls._meta.model_name
|
'model_name': model_cls._meta.model_name
|
||||||
}
|
}
|
||||||
permission = self.perm_format % kwargs
|
permission = self.perm_format % kwargs
|
||||||
if tuple(guardian.VERSION) >= (1, 3):
|
if tuple(guardian_version) >= (1, 3):
|
||||||
# Maintain behavior compatibility with versions prior to 1.3
|
# Maintain behavior compatibility with versions prior to 1.3
|
||||||
extra = {'accept_global_perms': False}
|
extra = {'accept_global_perms': False}
|
||||||
else:
|
else:
|
||||||
|
|
|
@ -1 +0,0 @@
|
||||||
# Just to keep things like ./manage.py test happy
|
|
|
@ -544,12 +544,11 @@ class CursorPagination(BasePagination):
|
||||||
has_following_position = False
|
has_following_position = False
|
||||||
following_position = None
|
following_position = None
|
||||||
|
|
||||||
# If we have a reverse queryset, then the query ordering was in reverse
|
|
||||||
# so we need to reverse the items again before returning them to the user.
|
|
||||||
if reverse:
|
if reverse:
|
||||||
|
# If we have a reverse queryset, then the query ordering was in reverse
|
||||||
|
# so we need to reverse the items again before returning them to the user.
|
||||||
self.page = list(reversed(self.page))
|
self.page = list(reversed(self.page))
|
||||||
|
|
||||||
if reverse:
|
|
||||||
# Determine next and previous positions for reverse cursors.
|
# Determine next and previous positions for reverse cursors.
|
||||||
self.has_next = (current_position is not None) or (offset > 0)
|
self.has_next = (current_position is not None) or (offset > 0)
|
||||||
self.has_previous = has_following_position
|
self.has_previous = has_following_position
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
# coding: utf-8
|
# coding: utf-8
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
|
import sys
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
|
|
||||||
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
|
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
|
||||||
|
@ -31,6 +32,20 @@ def method_overridden(method_name, klass, instance):
|
||||||
return default_method is not getattr(instance, method_name).__func__
|
return default_method is not getattr(instance, method_name).__func__
|
||||||
|
|
||||||
|
|
||||||
|
class ObjectValueError(ValueError):
|
||||||
|
"""
|
||||||
|
Raised when `queryset.get()` failed due to an underlying `ValueError`.
|
||||||
|
Wrapping prevents calling code conflating this with unrelated errors.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class ObjectTypeError(TypeError):
|
||||||
|
"""
|
||||||
|
Raised when `queryset.get()` failed due to an underlying `TypeError`.
|
||||||
|
Wrapping prevents calling code conflating this with unrelated errors.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
class Hyperlink(six.text_type):
|
class Hyperlink(six.text_type):
|
||||||
"""
|
"""
|
||||||
A string like object that additionally has an associated name.
|
A string like object that additionally has an associated name.
|
||||||
|
@ -296,7 +311,16 @@ class HyperlinkedRelatedField(RelatedField):
|
||||||
"""
|
"""
|
||||||
lookup_value = view_kwargs[self.lookup_url_kwarg]
|
lookup_value = view_kwargs[self.lookup_url_kwarg]
|
||||||
lookup_kwargs = {self.lookup_field: lookup_value}
|
lookup_kwargs = {self.lookup_field: lookup_value}
|
||||||
return self.get_queryset().get(**lookup_kwargs)
|
queryset = self.get_queryset()
|
||||||
|
|
||||||
|
try:
|
||||||
|
return queryset.get(**lookup_kwargs)
|
||||||
|
except ValueError:
|
||||||
|
exc = ObjectValueError(str(sys.exc_info()[1]))
|
||||||
|
six.reraise(type(exc), exc, sys.exc_info()[2])
|
||||||
|
except TypeError:
|
||||||
|
exc = ObjectTypeError(str(sys.exc_info()[1]))
|
||||||
|
six.reraise(type(exc), exc, sys.exc_info()[2])
|
||||||
|
|
||||||
def get_url(self, obj, view_name, request, format):
|
def get_url(self, obj, view_name, request, format):
|
||||||
"""
|
"""
|
||||||
|
@ -346,7 +370,7 @@ class HyperlinkedRelatedField(RelatedField):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
return self.get_object(match.view_name, match.args, match.kwargs)
|
return self.get_object(match.view_name, match.args, match.kwargs)
|
||||||
except (ObjectDoesNotExist, TypeError, ValueError):
|
except (ObjectDoesNotExist, ObjectValueError, ObjectTypeError):
|
||||||
self.fail('does_not_exist')
|
self.fail('does_not_exist')
|
||||||
|
|
||||||
def to_representation(self, value):
|
def to_representation(self, value):
|
||||||
|
|
|
@ -18,6 +18,7 @@ from django.core.paginator import Page
|
||||||
from django.http.multipartparser import parse_header
|
from django.http.multipartparser import parse_header
|
||||||
from django.template import engines, loader
|
from django.template import engines, loader
|
||||||
from django.test.client import encode_multipart
|
from django.test.client import encode_multipart
|
||||||
|
from django.urls import NoReverseMatch
|
||||||
from django.utils import six
|
from django.utils import six
|
||||||
from django.utils.html import mark_safe
|
from django.utils.html import mark_safe
|
||||||
|
|
||||||
|
@ -612,6 +613,11 @@ class BrowsableAPIRenderer(BaseRenderer):
|
||||||
def get_breadcrumbs(self, request):
|
def get_breadcrumbs(self, request):
|
||||||
return get_breadcrumbs(request.path, request)
|
return get_breadcrumbs(request.path, request)
|
||||||
|
|
||||||
|
def get_extra_actions(self, view):
|
||||||
|
if hasattr(view, 'get_extra_action_url_map'):
|
||||||
|
return view.get_extra_action_url_map()
|
||||||
|
return None
|
||||||
|
|
||||||
def get_filter_form(self, data, view, request):
|
def get_filter_form(self, data, view, request):
|
||||||
if not hasattr(view, 'get_queryset') or not hasattr(view, 'filter_backends'):
|
if not hasattr(view, 'get_queryset') or not hasattr(view, 'filter_backends'):
|
||||||
return
|
return
|
||||||
|
@ -698,6 +704,8 @@ class BrowsableAPIRenderer(BaseRenderer):
|
||||||
'delete_form': self.get_rendered_html_form(data, view, 'DELETE', request),
|
'delete_form': self.get_rendered_html_form(data, view, 'DELETE', request),
|
||||||
'options_form': self.get_rendered_html_form(data, view, 'OPTIONS', request),
|
'options_form': self.get_rendered_html_form(data, view, 'OPTIONS', request),
|
||||||
|
|
||||||
|
'extra_actions': self.get_extra_actions(view),
|
||||||
|
|
||||||
'filter_form': self.get_filter_form(data, view, request),
|
'filter_form': self.get_filter_form(data, view, request),
|
||||||
|
|
||||||
'raw_data_put_form': raw_data_put_form,
|
'raw_data_put_form': raw_data_put_form,
|
||||||
|
@ -808,6 +816,12 @@ class AdminRenderer(BrowsableAPIRenderer):
|
||||||
columns = [key for key in header if key != 'url']
|
columns = [key for key in header if key != 'url']
|
||||||
details = [key for key in header if key != 'url']
|
details = [key for key in header if key != 'url']
|
||||||
|
|
||||||
|
if isinstance(results, list) and 'view' in renderer_context:
|
||||||
|
for result in results:
|
||||||
|
url = self.get_result_url(result, context['view'])
|
||||||
|
if url is not None:
|
||||||
|
result.setdefault('url', url)
|
||||||
|
|
||||||
context['style'] = style
|
context['style'] = style
|
||||||
context['columns'] = columns
|
context['columns'] = columns
|
||||||
context['details'] = details
|
context['details'] = details
|
||||||
|
@ -816,6 +830,26 @@ class AdminRenderer(BrowsableAPIRenderer):
|
||||||
context['error_title'] = getattr(self, 'error_title', None)
|
context['error_title'] = getattr(self, 'error_title', None)
|
||||||
return context
|
return context
|
||||||
|
|
||||||
|
def get_result_url(self, result, view):
|
||||||
|
"""
|
||||||
|
Attempt to reverse the result's detail view URL.
|
||||||
|
|
||||||
|
This only works with views that are generic-like (has `.lookup_field`)
|
||||||
|
and viewset-like (has `.basename` / `.reverse_action()`).
|
||||||
|
"""
|
||||||
|
if not hasattr(view, 'reverse_action') or \
|
||||||
|
not hasattr(view, 'lookup_field'):
|
||||||
|
return
|
||||||
|
|
||||||
|
lookup_field = view.lookup_field
|
||||||
|
lookup_url_kwarg = getattr(view, 'lookup_url_kwarg', None) or lookup_field
|
||||||
|
|
||||||
|
try:
|
||||||
|
kwargs = {lookup_url_kwarg: result[lookup_field]}
|
||||||
|
return view.reverse_action('detail', kwargs=kwargs)
|
||||||
|
except (KeyError, NoReverseMatch):
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
class DocumentationRenderer(BaseRenderer):
|
class DocumentationRenderer(BaseRenderer):
|
||||||
media_type = 'text/html'
|
media_type = 'text/html'
|
||||||
|
|
|
@ -10,6 +10,7 @@ The wrapped request then offers a richer API, in particular :
|
||||||
"""
|
"""
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
|
import io
|
||||||
import sys
|
import sys
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
@ -301,7 +302,7 @@ class Request(object):
|
||||||
elif not self._request._read_started:
|
elif not self._request._read_started:
|
||||||
self._stream = self._request
|
self._stream = self._request
|
||||||
else:
|
else:
|
||||||
self._stream = six.BytesIO(self.body)
|
self._stream = io.BytesIO(self.body)
|
||||||
|
|
||||||
def _supports_form_parsing(self):
|
def _supports_form_parsing(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -22,6 +22,8 @@ from collections import OrderedDict, namedtuple
|
||||||
from django.conf.urls import url
|
from django.conf.urls import url
|
||||||
from django.core.exceptions import ImproperlyConfigured
|
from django.core.exceptions import ImproperlyConfigured
|
||||||
from django.urls import NoReverseMatch
|
from django.urls import NoReverseMatch
|
||||||
|
from django.utils import six
|
||||||
|
from django.utils.deprecation import RenameMethodsBase
|
||||||
|
|
||||||
from rest_framework import views
|
from rest_framework import views
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
|
@ -73,21 +75,37 @@ def flatten(list_of_lists):
|
||||||
return itertools.chain(*list_of_lists)
|
return itertools.chain(*list_of_lists)
|
||||||
|
|
||||||
|
|
||||||
class BaseRouter(object):
|
class RenameRouterMethods(RenameMethodsBase):
|
||||||
|
renamed_methods = (
|
||||||
|
('get_default_base_name', 'get_default_basename', DeprecationWarning),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class BaseRouter(six.with_metaclass(RenameRouterMethods)):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.registry = []
|
self.registry = []
|
||||||
|
|
||||||
def register(self, prefix, viewset, base_name=None):
|
def register(self, prefix, viewset, basename=None, base_name=None):
|
||||||
if base_name is None:
|
if base_name is not None:
|
||||||
base_name = self.get_default_base_name(viewset)
|
msg = "The `base_name` argument has been deprecated in favor of `basename`."
|
||||||
self.registry.append((prefix, viewset, base_name))
|
warnings.warn(msg, DeprecationWarning, 2)
|
||||||
|
|
||||||
def get_default_base_name(self, viewset):
|
assert not (basename and base_name), (
|
||||||
|
"Do not provide both the `basename` and `base_name` arguments.")
|
||||||
|
|
||||||
|
if basename is None:
|
||||||
|
basename = base_name
|
||||||
|
|
||||||
|
if basename is None:
|
||||||
|
basename = self.get_default_basename(viewset)
|
||||||
|
self.registry.append((prefix, viewset, basename))
|
||||||
|
|
||||||
|
def get_default_basename(self, viewset):
|
||||||
"""
|
"""
|
||||||
If `base_name` is not specified, attempt to automatically determine
|
If `basename` is not specified, attempt to automatically determine
|
||||||
it from the viewset.
|
it from the viewset.
|
||||||
"""
|
"""
|
||||||
raise NotImplementedError('get_default_base_name must be overridden')
|
raise NotImplementedError('get_default_basename must be overridden')
|
||||||
|
|
||||||
def get_urls(self):
|
def get_urls(self):
|
||||||
"""
|
"""
|
||||||
|
@ -151,14 +169,14 @@ class SimpleRouter(BaseRouter):
|
||||||
self.trailing_slash = '/' if trailing_slash else ''
|
self.trailing_slash = '/' if trailing_slash else ''
|
||||||
super(SimpleRouter, self).__init__()
|
super(SimpleRouter, self).__init__()
|
||||||
|
|
||||||
def get_default_base_name(self, viewset):
|
def get_default_basename(self, viewset):
|
||||||
"""
|
"""
|
||||||
If `base_name` is not specified, attempt to automatically determine
|
If `basename` is not specified, attempt to automatically determine
|
||||||
it from the viewset.
|
it from the viewset.
|
||||||
"""
|
"""
|
||||||
queryset = getattr(viewset, 'queryset', None)
|
queryset = getattr(viewset, 'queryset', None)
|
||||||
|
|
||||||
assert queryset is not None, '`base_name` argument not specified, and could ' \
|
assert queryset is not None, '`basename` argument not specified, and could ' \
|
||||||
'not automatically determine the name from the viewset, as ' \
|
'not automatically determine the name from the viewset, as ' \
|
||||||
'it does not have a `.queryset` attribute.'
|
'it does not have a `.queryset` attribute.'
|
||||||
|
|
||||||
|
@ -208,8 +226,7 @@ class SimpleRouter(BaseRouter):
|
||||||
|
|
||||||
return Route(
|
return Route(
|
||||||
url=route.url.replace('{url_path}', url_path),
|
url=route.url.replace('{url_path}', url_path),
|
||||||
mapping={http_method: action.__name__
|
mapping=action.mapping,
|
||||||
for http_method in action.bind_to_methods},
|
|
||||||
name=route.name.replace('{url_name}', action.url_name),
|
name=route.name.replace('{url_name}', action.url_name),
|
||||||
detail=route.detail,
|
detail=route.detail,
|
||||||
initkwargs=initkwargs,
|
initkwargs=initkwargs,
|
||||||
|
|
|
@ -218,6 +218,10 @@ class EndpointEnumerator(object):
|
||||||
if callback.cls.schema is None:
|
if callback.cls.schema is None:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
if 'schema' in callback.initkwargs:
|
||||||
|
if callback.initkwargs['schema'] is None:
|
||||||
|
return False
|
||||||
|
|
||||||
if path.endswith('.{format}') or path.endswith('.{format}/'):
|
if path.endswith('.{format}') or path.endswith('.{format}/'):
|
||||||
return False # Ignore .json style URLs.
|
return False # Ignore .json style URLs.
|
||||||
|
|
||||||
|
@ -365,9 +369,7 @@ class SchemaGenerator(object):
|
||||||
"""
|
"""
|
||||||
Given a callback, return an actual view instance.
|
Given a callback, return an actual view instance.
|
||||||
"""
|
"""
|
||||||
view = callback.cls()
|
view = callback.cls(**getattr(callback, 'initkwargs', {}))
|
||||||
for attr, val in getattr(callback, 'initkwargs', {}).items():
|
|
||||||
setattr(view, attr, val)
|
|
||||||
view.args = ()
|
view.args = ()
|
||||||
view.kwargs = {}
|
view.kwargs = {}
|
||||||
view.format_kwarg = None
|
view.format_kwarg = None
|
||||||
|
|
|
@ -7,6 +7,7 @@ See schemas.__init__.py for package overview.
|
||||||
import re
|
import re
|
||||||
import warnings
|
import warnings
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
|
from weakref import WeakKeyDictionary
|
||||||
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.utils.encoding import force_text, smart_text
|
from django.utils.encoding import force_text, smart_text
|
||||||
|
@ -128,6 +129,10 @@ class ViewInspector(object):
|
||||||
|
|
||||||
Provide subclass for per-view schema generation
|
Provide subclass for per-view schema generation
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.instance_schemas = WeakKeyDictionary()
|
||||||
|
|
||||||
def __get__(self, instance, owner):
|
def __get__(self, instance, owner):
|
||||||
"""
|
"""
|
||||||
Enables `ViewInspector` as a Python _Descriptor_.
|
Enables `ViewInspector` as a Python _Descriptor_.
|
||||||
|
@ -144,9 +149,17 @@ class ViewInspector(object):
|
||||||
See: https://docs.python.org/3/howto/descriptor.html for info on
|
See: https://docs.python.org/3/howto/descriptor.html for info on
|
||||||
descriptor usage.
|
descriptor usage.
|
||||||
"""
|
"""
|
||||||
|
if instance in self.instance_schemas:
|
||||||
|
return self.instance_schemas[instance]
|
||||||
|
|
||||||
self.view = instance
|
self.view = instance
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
def __set__(self, instance, other):
|
||||||
|
self.instance_schemas[instance] = other
|
||||||
|
if other is not None:
|
||||||
|
other.view = instance
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def view(self):
|
def view(self):
|
||||||
"""View property."""
|
"""View property."""
|
||||||
|
@ -189,6 +202,7 @@ class AutoSchema(ViewInspector):
|
||||||
* `manual_fields`: list of `coreapi.Field` instances that
|
* `manual_fields`: list of `coreapi.Field` instances that
|
||||||
will be added to auto-generated fields, overwriting on `Field.name`
|
will be added to auto-generated fields, overwriting on `Field.name`
|
||||||
"""
|
"""
|
||||||
|
super(AutoSchema, self).__init__()
|
||||||
if manual_fields is None:
|
if manual_fields is None:
|
||||||
manual_fields = []
|
manual_fields = []
|
||||||
self._manual_fields = manual_fields
|
self._manual_fields = manual_fields
|
||||||
|
@ -456,6 +470,7 @@ class ManualSchema(ViewInspector):
|
||||||
* `fields`: list of `coreapi.Field` instances.
|
* `fields`: list of `coreapi.Field` instances.
|
||||||
* `descripton`: String description for view. Optional.
|
* `descripton`: String description for view. Optional.
|
||||||
"""
|
"""
|
||||||
|
super(ManualSchema, self).__init__()
|
||||||
assert all(isinstance(f, coreapi.Field) for f in fields), "`fields` must be a list of coreapi.Field instances"
|
assert all(isinstance(f, coreapi.Field) for f in fields), "`fields` must be a list of coreapi.Field instances"
|
||||||
self._fields = fields
|
self._fields = fields
|
||||||
self._description = description
|
self._description = description
|
||||||
|
@ -475,9 +490,13 @@ class ManualSchema(ViewInspector):
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class DefaultSchema(object):
|
class DefaultSchema(ViewInspector):
|
||||||
"""Allows overriding AutoSchema using DEFAULT_SCHEMA_CLASS setting"""
|
"""Allows overriding AutoSchema using DEFAULT_SCHEMA_CLASS setting"""
|
||||||
def __get__(self, instance, owner):
|
def __get__(self, instance, owner):
|
||||||
|
result = super(DefaultSchema, self).__get__(instance, owner)
|
||||||
|
if not isinstance(result, DefaultSchema):
|
||||||
|
return result
|
||||||
|
|
||||||
inspector_class = api_settings.DEFAULT_SCHEMA_CLASS
|
inspector_class = api_settings.DEFAULT_SCHEMA_CLASS
|
||||||
assert issubclass(inspector_class, ViewInspector), "DEFAULT_SCHEMA_CLASS must be set to a ViewInspector (usually an AutoSchema) subclass"
|
assert issubclass(inspector_class, ViewInspector), "DEFAULT_SCHEMA_CLASS must be set to a ViewInspector (usually an AutoSchema) subclass"
|
||||||
inspector = inspector_class()
|
inspector = inspector_class()
|
||||||
|
|
|
@ -15,7 +15,7 @@ from __future__ import unicode_literals
|
||||||
import copy
|
import copy
|
||||||
import inspect
|
import inspect
|
||||||
import traceback
|
import traceback
|
||||||
from collections import Mapping, OrderedDict
|
from collections import OrderedDict
|
||||||
|
|
||||||
from django.core.exceptions import ImproperlyConfigured
|
from django.core.exceptions import ImproperlyConfigured
|
||||||
from django.core.exceptions import ValidationError as DjangoValidationError
|
from django.core.exceptions import ValidationError as DjangoValidationError
|
||||||
|
@ -27,7 +27,7 @@ from django.utils import six, timezone
|
||||||
from django.utils.functional import cached_property
|
from django.utils.functional import cached_property
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
from rest_framework.compat import postgres_fields, unicode_to_repr
|
from rest_framework.compat import Mapping, postgres_fields, unicode_to_repr
|
||||||
from rest_framework.exceptions import ErrorDetail, ValidationError
|
from rest_framework.exceptions import ErrorDetail, ValidationError
|
||||||
from rest_framework.fields import get_error_detail, set_value
|
from rest_framework.fields import get_error_detail, set_value
|
||||||
from rest_framework.settings import api_settings
|
from rest_framework.settings import api_settings
|
||||||
|
@ -937,19 +937,21 @@ class ModelSerializer(Serializer):
|
||||||
many_to_many[field_name] = validated_data.pop(field_name)
|
many_to_many[field_name] = validated_data.pop(field_name)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
instance = ModelClass.objects.create(**validated_data)
|
instance = ModelClass._default_manager.create(**validated_data)
|
||||||
except TypeError:
|
except TypeError:
|
||||||
tb = traceback.format_exc()
|
tb = traceback.format_exc()
|
||||||
msg = (
|
msg = (
|
||||||
'Got a `TypeError` when calling `%s.objects.create()`. '
|
'Got a `TypeError` when calling `%s.%s.create()`. '
|
||||||
'This may be because you have a writable field on the '
|
'This may be because you have a writable field on the '
|
||||||
'serializer class that is not a valid argument to '
|
'serializer class that is not a valid argument to '
|
||||||
'`%s.objects.create()`. You may need to make the field '
|
'`%s.%s.create()`. You may need to make the field '
|
||||||
'read-only, or override the %s.create() method to handle '
|
'read-only, or override the %s.create() method to handle '
|
||||||
'this correctly.\nOriginal exception was:\n %s' %
|
'this correctly.\nOriginal exception was:\n %s' %
|
||||||
(
|
(
|
||||||
ModelClass.__name__,
|
ModelClass.__name__,
|
||||||
|
ModelClass._default_manager.name,
|
||||||
ModelClass.__name__,
|
ModelClass.__name__,
|
||||||
|
ModelClass._default_manager.name,
|
||||||
self.__class__.__name__,
|
self.__class__.__name__,
|
||||||
tb
|
tb
|
||||||
)
|
)
|
||||||
|
|
|
@ -110,6 +110,20 @@
|
||||||
</form>
|
</form>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
|
{% if extra_actions %}
|
||||||
|
<div class="dropdown" style="float: right; margin-right: 10px">
|
||||||
|
<button class="btn btn-default" id="extra-actions-menu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
|
||||||
|
{% trans "Extra Actions" %}
|
||||||
|
<span class="caret"></span>
|
||||||
|
</button>
|
||||||
|
<ul class="dropdown-menu" aria-labelledby="extra-actions-menu">
|
||||||
|
{% for action_name, url in extra_actions|items %}
|
||||||
|
<li><a href="{{ url }}">{{ action_name }}</a></li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
{% if filter_form %}
|
{% if filter_form %}
|
||||||
<button style="float: right; margin-right: 10px" data-toggle="modal" data-target="#filtersModal" class="btn btn-default">
|
<button style="float: right; margin-right: 10px" data-toggle="modal" data-target="#filtersModal" class="btn btn-default">
|
||||||
<span class="glyphicon glyphicon-wrench" aria-hidden="true"></span>
|
<span class="glyphicon glyphicon-wrench" aria-hidden="true"></span>
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
{% load rest_framework %}
|
{% load rest_framework %}
|
||||||
<table class="table table-striped">
|
<table class="table table-striped">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>{% for column in columns%}<th>{{ column|capfirst }}</th>{% endfor %}<th></th></tr>
|
<tr>{% for column in columns%}<th>{{ column|capfirst }}</th>{% endfor %}<th class="col-xs-1"></th></tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for row in results %}
|
{% for row in results %}
|
||||||
|
@ -14,7 +14,11 @@
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
<td>
|
<td>
|
||||||
|
{% if row.url %}
|
||||||
<a href="{{ row.url }}"><span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span></a>
|
<a href="{{ row.url }}"><span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span></a>
|
||||||
|
{% else %}
|
||||||
|
<span class="glyphicon glyphicon-chevron-right text-muted" aria-hidden="true"></span>
|
||||||
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
|
|
@ -128,6 +128,20 @@
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
|
{% if extra_actions %}
|
||||||
|
<div class="dropdown" style="float: right; margin-right: 10px">
|
||||||
|
<button class="btn btn-default" id="extra-actions-menu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
|
||||||
|
{% trans "Extra Actions" %}
|
||||||
|
<span class="caret"></span>
|
||||||
|
</button>
|
||||||
|
<ul class="dropdown-menu" aria-labelledby="extra-actions-menu">
|
||||||
|
{% for action_name, url in extra_actions|items %}
|
||||||
|
<li><a href="{{ url }}">{{ action_name }}</a></li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
{% if filter_form %}
|
{% if filter_form %}
|
||||||
<button style="float: right; margin-right: 10px" data-toggle="modal" data-target="#filtersModal" class="btn btn-default">
|
<button style="float: right; margin-right: 10px" data-toggle="modal" data-target="#filtersModal" class="btn btn-default">
|
||||||
<span class="glyphicon glyphicon-wrench" aria-hidden="true"></span>
|
<span class="glyphicon glyphicon-wrench" aria-hidden="true"></span>
|
||||||
|
|
|
@ -13,22 +13,11 @@ You should make sure your authentication settings include `SessionAuthentication
|
||||||
"""
|
"""
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
import django
|
|
||||||
from django.conf.urls import url
|
from django.conf.urls import url
|
||||||
from django.contrib.auth import views
|
from django.contrib.auth import views
|
||||||
|
|
||||||
if django.VERSION < (1, 11):
|
|
||||||
login = views.login
|
|
||||||
login_kwargs = {'template_name': 'rest_framework/login.html'}
|
|
||||||
logout = views.logout
|
|
||||||
else:
|
|
||||||
login = views.LoginView.as_view(template_name='rest_framework/login.html')
|
|
||||||
login_kwargs = {}
|
|
||||||
logout = views.LogoutView.as_view()
|
|
||||||
|
|
||||||
|
|
||||||
app_name = 'rest_framework'
|
app_name = 'rest_framework'
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
url(r'^login/$', login, login_kwargs, name='login'),
|
url(r'^login/$', views.LoginView.as_view(template_name='rest_framework/login.html'), name='login'),
|
||||||
url(r'^logout/$', logout, name='logout'),
|
url(r'^logout/$', views.LogoutView.as_view(), name='logout'),
|
||||||
]
|
]
|
||||||
|
|
|
@ -30,7 +30,6 @@ def get_breadcrumbs(url, request=None):
|
||||||
# Probably an optional trailing slash.
|
# Probably an optional trailing slash.
|
||||||
if not seen or seen[-1] != view:
|
if not seen or seen[-1] != view:
|
||||||
c = cls(**initkwargs)
|
c = cls(**initkwargs)
|
||||||
c.suffix = getattr(view, 'suffix', None)
|
|
||||||
name = c.get_view_name()
|
name = c.get_view_name()
|
||||||
insert_url = preserve_builtin_query_params(prefix + url, request)
|
insert_url = preserve_builtin_query_params(prefix + url, request)
|
||||||
breadcrumbs_list.insert(0, (name, insert_url))
|
breadcrumbs_list.insert(0, (name, insert_url))
|
||||||
|
|
|
@ -21,31 +21,43 @@ from rest_framework.settings import api_settings
|
||||||
from rest_framework.utils import formatting
|
from rest_framework.utils import formatting
|
||||||
|
|
||||||
|
|
||||||
def get_view_name(view_cls, suffix=None):
|
def get_view_name(view):
|
||||||
"""
|
"""
|
||||||
Given a view class, return a textual name to represent the view.
|
Given a view class, return a textual name to represent the view.
|
||||||
This name is used in the browsable API, and in OPTIONS responses.
|
This name is used in the browsable API, and in OPTIONS responses.
|
||||||
|
|
||||||
This function is the default for the `VIEW_NAME_FUNCTION` setting.
|
This function is the default for the `VIEW_NAME_FUNCTION` setting.
|
||||||
"""
|
"""
|
||||||
name = view_cls.__name__
|
# Name may be set by some Views, such as a ViewSet.
|
||||||
|
name = getattr(view, 'name', None)
|
||||||
|
if name is not None:
|
||||||
|
return name
|
||||||
|
|
||||||
|
name = view.__class__.__name__
|
||||||
name = formatting.remove_trailing_string(name, 'View')
|
name = formatting.remove_trailing_string(name, 'View')
|
||||||
name = formatting.remove_trailing_string(name, 'ViewSet')
|
name = formatting.remove_trailing_string(name, 'ViewSet')
|
||||||
name = formatting.camelcase_to_spaces(name)
|
name = formatting.camelcase_to_spaces(name)
|
||||||
|
|
||||||
|
# Suffix may be set by some Views, such as a ViewSet.
|
||||||
|
suffix = getattr(view, 'suffix', None)
|
||||||
if suffix:
|
if suffix:
|
||||||
name += ' ' + suffix
|
name += ' ' + suffix
|
||||||
|
|
||||||
return name
|
return name
|
||||||
|
|
||||||
|
|
||||||
def get_view_description(view_cls, html=False):
|
def get_view_description(view, html=False):
|
||||||
"""
|
"""
|
||||||
Given a view class, return a textual description to represent the view.
|
Given a view class, return a textual description to represent the view.
|
||||||
This name is used in the browsable API, and in OPTIONS responses.
|
This name is used in the browsable API, and in OPTIONS responses.
|
||||||
|
|
||||||
This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting.
|
This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting.
|
||||||
"""
|
"""
|
||||||
description = view_cls.__doc__ or ''
|
# Description may be set by some Views, such as a ViewSet.
|
||||||
|
description = getattr(view, 'description', None)
|
||||||
|
if description is None:
|
||||||
|
description = view.__class__.__doc__ or ''
|
||||||
|
|
||||||
description = formatting.dedent(smart_text(description))
|
description = formatting.dedent(smart_text(description))
|
||||||
if html:
|
if html:
|
||||||
return formatting.markup_description(description)
|
return formatting.markup_description(description)
|
||||||
|
@ -224,7 +236,7 @@ class APIView(View):
|
||||||
browsable API.
|
browsable API.
|
||||||
"""
|
"""
|
||||||
func = self.settings.VIEW_NAME_FUNCTION
|
func = self.settings.VIEW_NAME_FUNCTION
|
||||||
return func(self.__class__, getattr(self, 'suffix', None))
|
return func(self)
|
||||||
|
|
||||||
def get_view_description(self, html=False):
|
def get_view_description(self, html=False):
|
||||||
"""
|
"""
|
||||||
|
@ -232,7 +244,7 @@ class APIView(View):
|
||||||
and in the browsable API.
|
and in the browsable API.
|
||||||
"""
|
"""
|
||||||
func = self.settings.VIEW_DESCRIPTION_FUNCTION
|
func = self.settings.VIEW_DESCRIPTION_FUNCTION
|
||||||
return func(self.__class__, html)
|
return func(self, html)
|
||||||
|
|
||||||
# API policy instantiation methods
|
# API policy instantiation methods
|
||||||
|
|
||||||
|
|
|
@ -18,9 +18,11 @@ automatically.
|
||||||
"""
|
"""
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
|
from collections import OrderedDict
|
||||||
from functools import update_wrapper
|
from functools import update_wrapper
|
||||||
from inspect import getmembers
|
from inspect import getmembers
|
||||||
|
|
||||||
|
from django.urls import NoReverseMatch
|
||||||
from django.utils.decorators import classonlymethod
|
from django.utils.decorators import classonlymethod
|
||||||
from django.views.decorators.csrf import csrf_exempt
|
from django.views.decorators.csrf import csrf_exempt
|
||||||
|
|
||||||
|
@ -29,7 +31,7 @@ from rest_framework.reverse import reverse
|
||||||
|
|
||||||
|
|
||||||
def _is_extra_action(attr):
|
def _is_extra_action(attr):
|
||||||
return hasattr(attr, 'bind_to_methods')
|
return hasattr(attr, 'mapping')
|
||||||
|
|
||||||
|
|
||||||
class ViewSetMixin(object):
|
class ViewSetMixin(object):
|
||||||
|
@ -52,7 +54,13 @@ class ViewSetMixin(object):
|
||||||
instantiated view, we need to totally reimplement `.as_view`,
|
instantiated view, we need to totally reimplement `.as_view`,
|
||||||
and slightly modify the view function that is created and returned.
|
and slightly modify the view function that is created and returned.
|
||||||
"""
|
"""
|
||||||
|
# The name and description initkwargs may be explicitly overridden for
|
||||||
|
# certain route confiugurations. eg, names of extra actions.
|
||||||
|
cls.name = None
|
||||||
|
cls.description = None
|
||||||
|
|
||||||
# The suffix initkwarg is reserved for displaying the viewset type.
|
# The suffix initkwarg is reserved for displaying the viewset type.
|
||||||
|
# This initkwarg should have no effect if the name is provided.
|
||||||
# eg. 'List' or 'Instance'.
|
# eg. 'List' or 'Instance'.
|
||||||
cls.suffix = None
|
cls.suffix = None
|
||||||
|
|
||||||
|
@ -79,6 +87,11 @@ class ViewSetMixin(object):
|
||||||
raise TypeError("%s() received an invalid keyword %r" % (
|
raise TypeError("%s() received an invalid keyword %r" % (
|
||||||
cls.__name__, key))
|
cls.__name__, key))
|
||||||
|
|
||||||
|
# name and suffix are mutually exclusive
|
||||||
|
if 'name' in initkwargs and 'suffix' in initkwargs:
|
||||||
|
raise TypeError("%s() received both `name` and `suffix`, which are "
|
||||||
|
"mutually exclusive arguments." % (cls.__name__))
|
||||||
|
|
||||||
def view(request, *args, **kwargs):
|
def view(request, *args, **kwargs):
|
||||||
self = cls(**initkwargs)
|
self = cls(**initkwargs)
|
||||||
# We also store the mapping of request methods to actions,
|
# We also store the mapping of request methods to actions,
|
||||||
|
@ -114,7 +127,6 @@ class ViewSetMixin(object):
|
||||||
# resolved URL.
|
# resolved URL.
|
||||||
view.cls = cls
|
view.cls = cls
|
||||||
view.initkwargs = initkwargs
|
view.initkwargs = initkwargs
|
||||||
view.suffix = initkwargs.get('suffix', None)
|
|
||||||
view.actions = actions
|
view.actions = actions
|
||||||
return csrf_exempt(view)
|
return csrf_exempt(view)
|
||||||
|
|
||||||
|
@ -149,6 +161,34 @@ class ViewSetMixin(object):
|
||||||
"""
|
"""
|
||||||
return [method for _, method in getmembers(cls, _is_extra_action)]
|
return [method for _, method in getmembers(cls, _is_extra_action)]
|
||||||
|
|
||||||
|
def get_extra_action_url_map(self):
|
||||||
|
"""
|
||||||
|
Build a map of {names: urls} for the extra actions.
|
||||||
|
|
||||||
|
This method will noop if `detail` was not provided as a view initkwarg.
|
||||||
|
"""
|
||||||
|
action_urls = OrderedDict()
|
||||||
|
|
||||||
|
# exit early if `detail` has not been provided
|
||||||
|
if self.detail is None:
|
||||||
|
return action_urls
|
||||||
|
|
||||||
|
# filter for the relevant extra actions
|
||||||
|
actions = [
|
||||||
|
action for action in self.get_extra_actions()
|
||||||
|
if action.detail == self.detail
|
||||||
|
]
|
||||||
|
|
||||||
|
for action in actions:
|
||||||
|
try:
|
||||||
|
url_name = '%s-%s' % (self.basename, action.url_name)
|
||||||
|
url = reverse(url_name, self.args, self.kwargs, request=self.request)
|
||||||
|
action_urls[action.name] = url
|
||||||
|
except NoReverseMatch:
|
||||||
|
pass # URL requires additional arguments, ignore
|
||||||
|
|
||||||
|
return action_urls
|
||||||
|
|
||||||
|
|
||||||
class ViewSet(ViewSetMixin, views.APIView):
|
class ViewSet(ViewSetMixin, views.APIView):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -5,7 +5,7 @@ universal = 1
|
||||||
license_file = LICENSE.md
|
license_file = LICENSE.md
|
||||||
|
|
||||||
[tool:pytest]
|
[tool:pytest]
|
||||||
addopts=--tb=short --strict
|
addopts=--tb=short --strict -ra
|
||||||
testspath = tests
|
testspath = tests
|
||||||
|
|
||||||
[flake8]
|
[flake8]
|
||||||
|
@ -17,7 +17,7 @@ skip=.tox
|
||||||
atomic=true
|
atomic=true
|
||||||
multi_line_output=5
|
multi_line_output=5
|
||||||
known_standard_library=types
|
known_standard_library=types
|
||||||
known_third_party=pytest,_pytest,django
|
known_third_party=pytest,_pytest,django,pytz
|
||||||
known_first_party=rest_framework
|
known_first_party=rest_framework
|
||||||
|
|
||||||
[coverage:run]
|
[coverage:run]
|
||||||
|
|
2
setup.py
2
setup.py
|
@ -58,9 +58,9 @@ setup(
|
||||||
'Development Status :: 5 - Production/Stable',
|
'Development Status :: 5 - Production/Stable',
|
||||||
'Environment :: Web Environment',
|
'Environment :: Web Environment',
|
||||||
'Framework :: Django',
|
'Framework :: Django',
|
||||||
'Framework :: Django :: 1.10',
|
|
||||||
'Framework :: Django :: 1.11',
|
'Framework :: Django :: 1.11',
|
||||||
'Framework :: Django :: 2.0',
|
'Framework :: Django :: 2.0',
|
||||||
|
'Framework :: Django :: 2.1',
|
||||||
'Intended Audience :: Developers',
|
'Intended Audience :: Developers',
|
||||||
'License :: OSI Approved :: BSD License',
|
'License :: OSI Approved :: BSD License',
|
||||||
'Operating System :: OS Independent',
|
'Operating System :: OS Independent',
|
||||||
|
|
|
@ -5,6 +5,7 @@ from __future__ import unicode_literals
|
||||||
import base64
|
import base64
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
from django.conf import settings
|
||||||
from django.conf.urls import include, url
|
from django.conf.urls import include, url
|
||||||
from django.contrib.auth.models import User
|
from django.contrib.auth.models import User
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
@ -202,6 +203,26 @@ class SessionAuthTests(TestCase):
|
||||||
response = self.csrf_client.post('/session/', {'example': 'example'})
|
response = self.csrf_client.post('/session/', {'example': 'example'})
|
||||||
assert response.status_code == status.HTTP_403_FORBIDDEN
|
assert response.status_code == status.HTTP_403_FORBIDDEN
|
||||||
|
|
||||||
|
def test_post_form_session_auth_passing_csrf(self):
|
||||||
|
"""
|
||||||
|
Ensure POSTing form over session authentication with CSRF token succeeds.
|
||||||
|
Regression test for #6088
|
||||||
|
"""
|
||||||
|
from django.middleware.csrf import _get_new_csrf_token
|
||||||
|
|
||||||
|
self.csrf_client.login(username=self.username, password=self.password)
|
||||||
|
|
||||||
|
# Set the csrf_token cookie so that CsrfViewMiddleware._get_token() works
|
||||||
|
token = _get_new_csrf_token()
|
||||||
|
self.csrf_client.cookies[settings.CSRF_COOKIE_NAME] = token
|
||||||
|
|
||||||
|
# Post the token matching the cookie value
|
||||||
|
response = self.csrf_client.post('/session/', {
|
||||||
|
'example': 'example',
|
||||||
|
'csrfmiddlewaretoken': token,
|
||||||
|
})
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
|
||||||
def test_post_form_session_auth_passing(self):
|
def test_post_form_session_auth_passing(self):
|
||||||
"""
|
"""
|
||||||
Ensure POSTing form over session authentication with logged in
|
Ensure POSTing form over session authentication with logged in
|
||||||
|
|
|
@ -175,26 +175,85 @@ class ActionDecoratorTestCase(TestCase):
|
||||||
def test_defaults(self):
|
def test_defaults(self):
|
||||||
@action(detail=True)
|
@action(detail=True)
|
||||||
def test_action(request):
|
def test_action(request):
|
||||||
pass
|
"""Description"""
|
||||||
|
|
||||||
assert test_action.bind_to_methods == ['get']
|
assert test_action.mapping == {'get': 'test_action'}
|
||||||
assert test_action.detail is True
|
assert test_action.detail is True
|
||||||
|
assert test_action.name == 'Test action'
|
||||||
assert test_action.url_path == 'test_action'
|
assert test_action.url_path == 'test_action'
|
||||||
assert test_action.url_name == 'test-action'
|
assert test_action.url_name == 'test-action'
|
||||||
|
assert test_action.kwargs == {
|
||||||
|
'name': 'Test action',
|
||||||
|
'description': 'Description',
|
||||||
|
}
|
||||||
|
|
||||||
def test_detail_required(self):
|
def test_detail_required(self):
|
||||||
with pytest.raises(AssertionError) as excinfo:
|
with pytest.raises(AssertionError) as excinfo:
|
||||||
@action()
|
@action()
|
||||||
def test_action(request):
|
def test_action(request):
|
||||||
pass
|
raise NotImplementedError
|
||||||
|
|
||||||
assert str(excinfo.value) == "@action() missing required argument: 'detail'"
|
assert str(excinfo.value) == "@action() missing required argument: 'detail'"
|
||||||
|
|
||||||
|
def test_method_mapping_http_methods(self):
|
||||||
|
# All HTTP methods should be mappable
|
||||||
|
@action(detail=False, methods=[])
|
||||||
|
def test_action():
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
for name in APIView.http_method_names:
|
||||||
|
def method():
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
# Python 2.x compatibility - cast __name__ to str
|
||||||
|
method.__name__ = str(name)
|
||||||
|
getattr(test_action.mapping, name)(method)
|
||||||
|
|
||||||
|
# ensure the mapping returns the correct method name
|
||||||
|
for name in APIView.http_method_names:
|
||||||
|
assert test_action.mapping[name] == name
|
||||||
|
|
||||||
|
def test_method_mapping(self):
|
||||||
|
@action(detail=False)
|
||||||
|
def test_action(request):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
@test_action.mapping.post
|
||||||
|
def test_action_post(request):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
# The secondary handler methods should not have the action attributes
|
||||||
|
for name in ['mapping', 'detail', 'name', 'url_path', 'url_name', 'kwargs']:
|
||||||
|
assert hasattr(test_action, name) and not hasattr(test_action_post, name)
|
||||||
|
|
||||||
|
def test_method_mapping_already_mapped(self):
|
||||||
|
@action(detail=True)
|
||||||
|
def test_action(request):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
msg = "Method 'get' has already been mapped to '.test_action'."
|
||||||
|
with self.assertRaisesMessage(AssertionError, msg):
|
||||||
|
@test_action.mapping.get
|
||||||
|
def test_action_get(request):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def test_method_mapping_overwrite(self):
|
||||||
|
@action(detail=True)
|
||||||
|
def test_action():
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
msg = ("Method mapping does not behave like the property decorator. You "
|
||||||
|
"cannot use the same method name for each mapping declaration.")
|
||||||
|
with self.assertRaisesMessage(AssertionError, msg):
|
||||||
|
@test_action.mapping.post
|
||||||
|
def test_action():
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
def test_detail_route_deprecation(self):
|
def test_detail_route_deprecation(self):
|
||||||
with pytest.warns(PendingDeprecationWarning) as record:
|
with pytest.warns(PendingDeprecationWarning) as record:
|
||||||
@detail_route()
|
@detail_route()
|
||||||
def view(request):
|
def view(request):
|
||||||
pass
|
raise NotImplementedError
|
||||||
|
|
||||||
assert len(record) == 1
|
assert len(record) == 1
|
||||||
assert str(record[0].message) == (
|
assert str(record[0].message) == (
|
||||||
|
@ -207,7 +266,7 @@ class ActionDecoratorTestCase(TestCase):
|
||||||
with pytest.warns(PendingDeprecationWarning) as record:
|
with pytest.warns(PendingDeprecationWarning) as record:
|
||||||
@list_route()
|
@list_route()
|
||||||
def view(request):
|
def view(request):
|
||||||
pass
|
raise NotImplementedError
|
||||||
|
|
||||||
assert len(record) == 1
|
assert len(record) == 1
|
||||||
assert str(record[0].message) == (
|
assert str(record[0].message) == (
|
||||||
|
@ -221,7 +280,7 @@ class ActionDecoratorTestCase(TestCase):
|
||||||
with pytest.warns(PendingDeprecationWarning):
|
with pytest.warns(PendingDeprecationWarning):
|
||||||
@list_route(url_path='foo_bar')
|
@list_route(url_path='foo_bar')
|
||||||
def view(request):
|
def view(request):
|
||||||
pass
|
raise NotImplementedError
|
||||||
|
|
||||||
assert view.url_path == 'foo_bar'
|
assert view.url_path == 'foo_bar'
|
||||||
assert view.url_name == 'foo-bar'
|
assert view.url_name == 'foo-bar'
|
||||||
|
|
|
@ -85,6 +85,22 @@ class TestViewNamesAndDescriptions(TestCase):
|
||||||
pass
|
pass
|
||||||
assert MockView().get_view_name() == 'Mock'
|
assert MockView().get_view_name() == 'Mock'
|
||||||
|
|
||||||
|
def test_view_name_uses_name_attribute(self):
|
||||||
|
class MockView(APIView):
|
||||||
|
name = 'Foo'
|
||||||
|
assert MockView().get_view_name() == 'Foo'
|
||||||
|
|
||||||
|
def test_view_name_uses_suffix_attribute(self):
|
||||||
|
class MockView(APIView):
|
||||||
|
suffix = 'List'
|
||||||
|
assert MockView().get_view_name() == 'Mock List'
|
||||||
|
|
||||||
|
def test_view_name_preferences_name_over_suffix(self):
|
||||||
|
class MockView(APIView):
|
||||||
|
name = 'Foo'
|
||||||
|
suffix = 'List'
|
||||||
|
assert MockView().get_view_name() == 'Foo'
|
||||||
|
|
||||||
def test_view_description_uses_docstring(self):
|
def test_view_description_uses_docstring(self):
|
||||||
"""Ensure view descriptions are based on the docstring."""
|
"""Ensure view descriptions are based on the docstring."""
|
||||||
class MockView(APIView):
|
class MockView(APIView):
|
||||||
|
@ -112,6 +128,17 @@ class TestViewNamesAndDescriptions(TestCase):
|
||||||
|
|
||||||
assert MockView().get_view_description() == DESCRIPTION
|
assert MockView().get_view_description() == DESCRIPTION
|
||||||
|
|
||||||
|
def test_view_description_uses_description_attribute(self):
|
||||||
|
class MockView(APIView):
|
||||||
|
description = 'Foo'
|
||||||
|
assert MockView().get_view_description() == 'Foo'
|
||||||
|
|
||||||
|
def test_view_description_allows_empty_description(self):
|
||||||
|
class MockView(APIView):
|
||||||
|
"""Description."""
|
||||||
|
description = ''
|
||||||
|
assert MockView().get_view_description() == ''
|
||||||
|
|
||||||
def test_view_description_can_be_empty(self):
|
def test_view_description_can_be_empty(self):
|
||||||
"""
|
"""
|
||||||
Ensure that if a view has no docstring,
|
Ensure that if a view has no docstring,
|
||||||
|
|
|
@ -6,20 +6,17 @@ import uuid
|
||||||
from decimal import ROUND_DOWN, ROUND_UP, Decimal
|
from decimal import ROUND_DOWN, ROUND_UP, Decimal
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
import pytz
|
||||||
|
from django.core.exceptions import ValidationError as DjangoValidationError
|
||||||
from django.http import QueryDict
|
from django.http import QueryDict
|
||||||
from django.test import TestCase, override_settings
|
from django.test import TestCase, override_settings
|
||||||
from django.utils import six
|
from django.utils import six
|
||||||
from django.utils.timezone import activate, deactivate, override, utc
|
from django.utils.timezone import activate, deactivate, override, utc
|
||||||
|
|
||||||
import rest_framework
|
import rest_framework
|
||||||
from rest_framework import compat, serializers
|
from rest_framework import exceptions, serializers
|
||||||
from rest_framework.fields import DjangoImageField, is_simple_callable
|
from rest_framework.fields import DjangoImageField, is_simple_callable
|
||||||
|
|
||||||
try:
|
|
||||||
import pytz
|
|
||||||
except ImportError:
|
|
||||||
pytz = None
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import typings
|
import typings
|
||||||
except ImportError:
|
except ImportError:
|
||||||
|
@ -1308,7 +1305,6 @@ class TestNaiveDateTimeField(FieldValues):
|
||||||
field = serializers.DateTimeField(default_timezone=None)
|
field = serializers.DateTimeField(default_timezone=None)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.skipif(pytz is None, reason='pytz not installed')
|
|
||||||
class TestTZWithDateTimeField(FieldValues):
|
class TestTZWithDateTimeField(FieldValues):
|
||||||
"""
|
"""
|
||||||
Valid and invalid values for `DateTimeField` when not using UTC as the timezone.
|
Valid and invalid values for `DateTimeField` when not using UTC as the timezone.
|
||||||
|
@ -1331,7 +1327,6 @@ class TestTZWithDateTimeField(FieldValues):
|
||||||
cls.field = serializers.DateTimeField(default_timezone=kolkata)
|
cls.field = serializers.DateTimeField(default_timezone=kolkata)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.skipif(pytz is None, reason='pytz not installed')
|
|
||||||
@override_settings(TIME_ZONE='UTC', USE_TZ=True)
|
@override_settings(TIME_ZONE='UTC', USE_TZ=True)
|
||||||
class TestDefaultTZDateTimeField(TestCase):
|
class TestDefaultTZDateTimeField(TestCase):
|
||||||
"""
|
"""
|
||||||
|
@ -1391,7 +1386,7 @@ class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues):
|
||||||
class MockTimezone:
|
class MockTimezone:
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def localize(value, is_dst):
|
def localize(value, is_dst):
|
||||||
raise compat.InvalidTimeError()
|
raise pytz.InvalidTimeError()
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return 'America/New_York'
|
return 'America/New_York'
|
||||||
|
@ -2183,3 +2178,91 @@ class TestSerializerMethodField:
|
||||||
"'ExampleSerializer', because it is the same as the default "
|
"'ExampleSerializer', because it is the same as the default "
|
||||||
"method name. Remove the `method_name` argument."
|
"method name. Remove the `method_name` argument."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestValidationErrorCode:
|
||||||
|
@pytest.mark.parametrize('use_list', (False, True))
|
||||||
|
def test_validationerror_code_with_msg(self, use_list):
|
||||||
|
|
||||||
|
class ExampleSerializer(serializers.Serializer):
|
||||||
|
password = serializers.CharField()
|
||||||
|
|
||||||
|
def validate_password(self, obj):
|
||||||
|
err = DjangoValidationError('exc_msg', code='exc_code')
|
||||||
|
if use_list:
|
||||||
|
err = DjangoValidationError([err])
|
||||||
|
raise err
|
||||||
|
|
||||||
|
serializer = ExampleSerializer(data={'password': 123})
|
||||||
|
serializer.is_valid()
|
||||||
|
assert serializer.errors == {'password': ['exc_msg']}
|
||||||
|
assert serializer.errors['password'][0].code == 'exc_code'
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('code', (None, 'exc_code',))
|
||||||
|
@pytest.mark.parametrize('use_list', (False, True))
|
||||||
|
def test_validationerror_code_with_dict(self, use_list, code):
|
||||||
|
|
||||||
|
class ExampleSerializer(serializers.Serializer):
|
||||||
|
|
||||||
|
def validate(self, obj):
|
||||||
|
if code is None:
|
||||||
|
err = DjangoValidationError({
|
||||||
|
'email': 'email error',
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
err = DjangoValidationError({
|
||||||
|
'email': DjangoValidationError(
|
||||||
|
'email error',
|
||||||
|
code=code),
|
||||||
|
})
|
||||||
|
if use_list:
|
||||||
|
err = DjangoValidationError([err])
|
||||||
|
raise err
|
||||||
|
|
||||||
|
serializer = ExampleSerializer(data={})
|
||||||
|
serializer.is_valid()
|
||||||
|
expected_code = code if code else 'invalid'
|
||||||
|
if use_list:
|
||||||
|
assert serializer.errors == {
|
||||||
|
'non_field_errors': [
|
||||||
|
exceptions.ErrorDetail(
|
||||||
|
string='email error',
|
||||||
|
code=expected_code
|
||||||
|
)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
assert serializer.errors == {
|
||||||
|
'email': ['email error'],
|
||||||
|
}
|
||||||
|
assert serializer.errors['email'][0].code == expected_code
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('code', (None, 'exc_code',))
|
||||||
|
def test_validationerror_code_with_dict_list_same_code(self, code):
|
||||||
|
|
||||||
|
class ExampleSerializer(serializers.Serializer):
|
||||||
|
|
||||||
|
def validate(self, obj):
|
||||||
|
if code is None:
|
||||||
|
raise DjangoValidationError({'email': ['email error 1',
|
||||||
|
'email error 2']})
|
||||||
|
raise DjangoValidationError({'email': [
|
||||||
|
DjangoValidationError('email error 1', code=code),
|
||||||
|
DjangoValidationError('email error 2', code=code),
|
||||||
|
]})
|
||||||
|
|
||||||
|
serializer = ExampleSerializer(data={})
|
||||||
|
serializer.is_valid()
|
||||||
|
expected_code = code if code else 'invalid'
|
||||||
|
assert serializer.errors == {
|
||||||
|
'email': [
|
||||||
|
exceptions.ErrorDetail(
|
||||||
|
string='email error 1',
|
||||||
|
code=expected_code
|
||||||
|
),
|
||||||
|
exceptions.ErrorDetail(
|
||||||
|
string='email error 2',
|
||||||
|
code=expected_code
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
|
@ -9,6 +9,7 @@ from __future__ import unicode_literals
|
||||||
|
|
||||||
import datetime
|
import datetime
|
||||||
import decimal
|
import decimal
|
||||||
|
import sys
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
@ -381,6 +382,10 @@ class TestDurationFieldMapping(TestCase):
|
||||||
TestSerializer():
|
TestSerializer():
|
||||||
id = IntegerField(label='ID', read_only=True)
|
id = IntegerField(label='ID', read_only=True)
|
||||||
duration_field = DurationField(max_value=datetime.timedelta(3), min_value=datetime.timedelta(1))
|
duration_field = DurationField(max_value=datetime.timedelta(3), min_value=datetime.timedelta(1))
|
||||||
|
""") if sys.version_info < (3, 7) else dedent("""
|
||||||
|
TestSerializer():
|
||||||
|
id = IntegerField(label='ID', read_only=True)
|
||||||
|
duration_field = DurationField(max_value=datetime.timedelta(days=3), min_value=datetime.timedelta(days=1))
|
||||||
""")
|
""")
|
||||||
self.assertEqual(unicode_repr(TestSerializer()), expected)
|
self.assertEqual(unicode_repr(TestSerializer()), expected)
|
||||||
|
|
||||||
|
@ -1224,3 +1229,28 @@ class TestFieldSource(TestCase):
|
||||||
""")
|
""")
|
||||||
self.maxDiff = None
|
self.maxDiff = None
|
||||||
self.assertEqual(unicode_repr(TestSerializer()), expected)
|
self.assertEqual(unicode_repr(TestSerializer()), expected)
|
||||||
|
|
||||||
|
|
||||||
|
class Issue6110TestModel(models.Model):
|
||||||
|
"""Model without .objects manager."""
|
||||||
|
|
||||||
|
name = models.CharField(max_length=64)
|
||||||
|
all_objects = models.Manager()
|
||||||
|
|
||||||
|
|
||||||
|
class Issue6110ModelSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Issue6110TestModel
|
||||||
|
fields = ('name',)
|
||||||
|
|
||||||
|
|
||||||
|
class Issue6110Test(TestCase):
|
||||||
|
|
||||||
|
def test_model_serializer_custom_manager(self):
|
||||||
|
instance = Issue6110ModelSerializer().create({'name': 'test_name'})
|
||||||
|
self.assertEqual(instance.name, 'test_name')
|
||||||
|
|
||||||
|
def test_model_serializer_custom_manager_error_message(self):
|
||||||
|
msginitial = ('Got a `TypeError` when calling `Issue6110TestModel.all_objects.create()`.')
|
||||||
|
with self.assertRaisesMessage(TypeError, msginitial):
|
||||||
|
Issue6110ModelSerializer().create({'wrong_param': 'wrong_param'})
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
|
import io
|
||||||
import math
|
import math
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
@ -10,7 +11,7 @@ from django.core.files.uploadhandler import (
|
||||||
)
|
)
|
||||||
from django.http.request import RawPostDataException
|
from django.http.request import RawPostDataException
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
from django.utils.six import BytesIO, StringIO
|
from django.utils.six import StringIO
|
||||||
|
|
||||||
from rest_framework.exceptions import ParseError
|
from rest_framework.exceptions import ParseError
|
||||||
from rest_framework.parsers import (
|
from rest_framework.parsers import (
|
||||||
|
@ -43,7 +44,7 @@ class TestFileUploadParser(TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
class MockRequest(object):
|
class MockRequest(object):
|
||||||
pass
|
pass
|
||||||
self.stream = BytesIO(
|
self.stream = io.BytesIO(
|
||||||
"Test text file".encode('utf-8')
|
"Test text file".encode('utf-8')
|
||||||
)
|
)
|
||||||
request = MockRequest()
|
request = MockRequest()
|
||||||
|
@ -62,7 +63,7 @@ class TestFileUploadParser(TestCase):
|
||||||
self.stream.seek(0)
|
self.stream.seek(0)
|
||||||
data_and_files = parser.parse(self.stream, None, self.parser_context)
|
data_and_files = parser.parse(self.stream, None, self.parser_context)
|
||||||
file_obj = data_and_files.files['file']
|
file_obj = data_and_files.files['file']
|
||||||
assert file_obj._size == 14
|
assert file_obj.size == 14
|
||||||
|
|
||||||
def test_parse_missing_filename(self):
|
def test_parse_missing_filename(self):
|
||||||
"""
|
"""
|
||||||
|
@ -131,7 +132,7 @@ class TestFileUploadParser(TestCase):
|
||||||
|
|
||||||
class TestJSONParser(TestCase):
|
class TestJSONParser(TestCase):
|
||||||
def bytes(self, value):
|
def bytes(self, value):
|
||||||
return BytesIO(value.encode('utf-8'))
|
return io.BytesIO(value.encode('utf-8'))
|
||||||
|
|
||||||
def test_float_strictness(self):
|
def test_float_strictness(self):
|
||||||
parser = JSONParser()
|
parser = JSONParser()
|
||||||
|
|
|
@ -13,7 +13,7 @@ from rest_framework import (
|
||||||
HTTP_HEADER_ENCODING, authentication, generics, permissions, serializers,
|
HTTP_HEADER_ENCODING, authentication, generics, permissions, serializers,
|
||||||
status, views
|
status, views
|
||||||
)
|
)
|
||||||
from rest_framework.compat import guardian
|
from rest_framework.compat import is_guardian_installed
|
||||||
from rest_framework.filters import DjangoObjectPermissionsFilter
|
from rest_framework.filters import DjangoObjectPermissionsFilter
|
||||||
from rest_framework.routers import DefaultRouter
|
from rest_framework.routers import DefaultRouter
|
||||||
from rest_framework.test import APIRequestFactory
|
from rest_framework.test import APIRequestFactory
|
||||||
|
@ -308,7 +308,7 @@ class GetQuerysetObjectPermissionInstanceView(generics.RetrieveUpdateDestroyAPIV
|
||||||
get_queryset_object_permissions_view = GetQuerysetObjectPermissionInstanceView.as_view()
|
get_queryset_object_permissions_view = GetQuerysetObjectPermissionInstanceView.as_view()
|
||||||
|
|
||||||
|
|
||||||
@unittest.skipUnless(guardian, 'django-guardian not installed')
|
@unittest.skipUnless(is_guardian_installed(), 'django-guardian not installed')
|
||||||
class ObjectPermissionsIntegrationTests(TestCase):
|
class ObjectPermissionsIntegrationTests(TestCase):
|
||||||
"""
|
"""
|
||||||
Integration tests for the object level permissions API.
|
Integration tests for the object level permissions API.
|
||||||
|
|
|
@ -197,6 +197,36 @@ class TestHyperlinkedRelatedField(APISimpleTestCase):
|
||||||
msg = excinfo.value.detail[0]
|
msg = excinfo.value.detail[0]
|
||||||
assert msg == 'Invalid hyperlink - Object does not exist.'
|
assert msg == 'Invalid hyperlink - Object does not exist.'
|
||||||
|
|
||||||
|
def test_hyperlinked_related_internal_type_error(self):
|
||||||
|
class Field(serializers.HyperlinkedRelatedField):
|
||||||
|
def get_object(self, incorrect, signature):
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
field = Field(view_name='example', queryset=self.queryset)
|
||||||
|
with pytest.raises(TypeError):
|
||||||
|
field.to_internal_value('http://example.org/example/doesnotexist/')
|
||||||
|
|
||||||
|
def hyperlinked_related_queryset_error(self, exc_type):
|
||||||
|
class QuerySet:
|
||||||
|
def get(self, *args, **kwargs):
|
||||||
|
raise exc_type
|
||||||
|
|
||||||
|
field = serializers.HyperlinkedRelatedField(
|
||||||
|
view_name='example',
|
||||||
|
lookup_field='name',
|
||||||
|
queryset=QuerySet(),
|
||||||
|
)
|
||||||
|
with pytest.raises(serializers.ValidationError) as excinfo:
|
||||||
|
field.to_internal_value('http://example.org/example/doesnotexist/')
|
||||||
|
msg = excinfo.value.detail[0]
|
||||||
|
assert msg == 'Invalid hyperlink - Object does not exist.'
|
||||||
|
|
||||||
|
def test_hyperlinked_related_queryset_type_error(self):
|
||||||
|
self.hyperlinked_related_queryset_error(TypeError)
|
||||||
|
|
||||||
|
def test_hyperlinked_related_queryset_value_error(self):
|
||||||
|
self.hyperlinked_related_queryset_error(ValueError)
|
||||||
|
|
||||||
|
|
||||||
class TestHyperlinkedIdentityField(APISimpleTestCase):
|
class TestHyperlinkedIdentityField(APISimpleTestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
|
|
|
@ -16,16 +16,19 @@ from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
from rest_framework import permissions, serializers, status
|
from rest_framework import permissions, serializers, status
|
||||||
from rest_framework.compat import coreapi
|
from rest_framework.compat import coreapi
|
||||||
|
from rest_framework.decorators import action
|
||||||
from rest_framework.renderers import (
|
from rest_framework.renderers import (
|
||||||
AdminRenderer, BaseRenderer, BrowsableAPIRenderer, DocumentationRenderer,
|
AdminRenderer, BaseRenderer, BrowsableAPIRenderer, DocumentationRenderer,
|
||||||
HTMLFormRenderer, JSONRenderer, SchemaJSRenderer, StaticHTMLRenderer
|
HTMLFormRenderer, JSONRenderer, SchemaJSRenderer, StaticHTMLRenderer
|
||||||
)
|
)
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.routers import SimpleRouter
|
||||||
from rest_framework.settings import api_settings
|
from rest_framework.settings import api_settings
|
||||||
from rest_framework.test import APIRequestFactory
|
from rest_framework.test import APIRequestFactory, URLPatternsTestCase
|
||||||
from rest_framework.utils import json
|
from rest_framework.utils import json
|
||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
|
from rest_framework.viewsets import ViewSet
|
||||||
|
|
||||||
DUMMYSTATUS = status.HTTP_200_OK
|
DUMMYSTATUS = status.HTTP_200_OK
|
||||||
DUMMYCONTENT = 'dummycontent'
|
DUMMYCONTENT = 'dummycontent'
|
||||||
|
@ -622,7 +625,18 @@ class StaticHTMLRendererTests(TestCase):
|
||||||
assert result == '500 Internal Server Error'
|
assert result == '500 Internal Server Error'
|
||||||
|
|
||||||
|
|
||||||
class BrowsableAPIRendererTests(TestCase):
|
class BrowsableAPIRendererTests(URLPatternsTestCase):
|
||||||
|
class ExampleViewSet(ViewSet):
|
||||||
|
def list(self, request):
|
||||||
|
return Response()
|
||||||
|
|
||||||
|
@action(detail=False, name="Extra list action")
|
||||||
|
def list_action(self, request):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
router = SimpleRouter()
|
||||||
|
router.register('examples', ExampleViewSet, base_name='example')
|
||||||
|
urlpatterns = [url(r'^api/', include(router.urls))]
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.renderer = BrowsableAPIRenderer()
|
self.renderer = BrowsableAPIRenderer()
|
||||||
|
@ -640,6 +654,12 @@ class BrowsableAPIRendererTests(TestCase):
|
||||||
view=DummyView(), request={})
|
view=DummyView(), request={})
|
||||||
assert result is None
|
assert result is None
|
||||||
|
|
||||||
|
def test_extra_actions_dropdown(self):
|
||||||
|
resp = self.client.get('/api/examples/', HTTP_ACCEPT='text/html')
|
||||||
|
assert 'id="extra-actions-menu"' in resp.content.decode('utf-8')
|
||||||
|
assert '/api/examples/list_action/' in resp.content.decode('utf-8')
|
||||||
|
assert '>Extra list action<' in resp.content.decode('utf-8')
|
||||||
|
|
||||||
|
|
||||||
class AdminRendererTests(TestCase):
|
class AdminRendererTests(TestCase):
|
||||||
|
|
||||||
|
@ -708,6 +728,75 @@ class AdminRendererTests(TestCase):
|
||||||
response.render()
|
response.render()
|
||||||
self.assertContains(response, '<tr><th>Iteritems</th><td>a string</td></tr>', html=True)
|
self.assertContains(response, '<tr><th>Iteritems</th><td>a string</td></tr>', html=True)
|
||||||
|
|
||||||
|
def test_get_result_url(self):
|
||||||
|
factory = APIRequestFactory()
|
||||||
|
|
||||||
|
class DummyGenericViewsetLike(APIView):
|
||||||
|
lookup_field = 'test'
|
||||||
|
|
||||||
|
def reverse_action(view, *args, **kwargs):
|
||||||
|
self.assertEqual(kwargs['kwargs']['test'], 1)
|
||||||
|
return '/example/'
|
||||||
|
|
||||||
|
# get the view instance instead of the view function
|
||||||
|
view = DummyGenericViewsetLike.as_view()
|
||||||
|
request = factory.get('/')
|
||||||
|
response = view(request)
|
||||||
|
view = response.renderer_context['view']
|
||||||
|
|
||||||
|
self.assertEqual(self.renderer.get_result_url({'test': 1}, view), '/example/')
|
||||||
|
self.assertIsNone(self.renderer.get_result_url({}, view))
|
||||||
|
|
||||||
|
def test_get_result_url_no_result(self):
|
||||||
|
factory = APIRequestFactory()
|
||||||
|
|
||||||
|
class DummyView(APIView):
|
||||||
|
lookup_field = 'test'
|
||||||
|
|
||||||
|
# get the view instance instead of the view function
|
||||||
|
view = DummyView.as_view()
|
||||||
|
request = factory.get('/')
|
||||||
|
response = view(request)
|
||||||
|
view = response.renderer_context['view']
|
||||||
|
|
||||||
|
self.assertIsNone(self.renderer.get_result_url({'test': 1}, view))
|
||||||
|
self.assertIsNone(self.renderer.get_result_url({}, view))
|
||||||
|
|
||||||
|
def test_get_context_result_urls(self):
|
||||||
|
factory = APIRequestFactory()
|
||||||
|
|
||||||
|
class DummyView(APIView):
|
||||||
|
lookup_field = 'test'
|
||||||
|
|
||||||
|
def reverse_action(view, url_name, args=None, kwargs=None):
|
||||||
|
return '/%s/%d' % (url_name, kwargs['test'])
|
||||||
|
|
||||||
|
# get the view instance instead of the view function
|
||||||
|
view = DummyView.as_view()
|
||||||
|
request = factory.get('/')
|
||||||
|
response = view(request)
|
||||||
|
|
||||||
|
data = [
|
||||||
|
{'test': 1},
|
||||||
|
{'url': '/example', 'test': 2},
|
||||||
|
{'url': None, 'test': 3},
|
||||||
|
{},
|
||||||
|
]
|
||||||
|
context = {
|
||||||
|
'view': DummyView(),
|
||||||
|
'request': Request(request),
|
||||||
|
'response': response
|
||||||
|
}
|
||||||
|
|
||||||
|
context = self.renderer.get_context(data, None, context)
|
||||||
|
results = context['results']
|
||||||
|
|
||||||
|
self.assertEqual(len(results), 4)
|
||||||
|
self.assertEqual(results[0]['url'], '/detail/1')
|
||||||
|
self.assertEqual(results[1]['url'], '/example')
|
||||||
|
self.assertEqual(results[2]['url'], None)
|
||||||
|
self.assertNotIn('url', results[3])
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
|
@pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
|
||||||
class TestDocumentationRenderer(TestCase):
|
class TestDocumentationRenderer(TestCase):
|
||||||
|
|
|
@ -1,5 +1,6 @@
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
|
import warnings
|
||||||
from collections import namedtuple
|
from collections import namedtuple
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
@ -7,7 +8,7 @@ from django.conf.urls import include, url
|
||||||
from django.core.exceptions import ImproperlyConfigured
|
from django.core.exceptions import ImproperlyConfigured
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.test import TestCase, override_settings
|
from django.test import TestCase, override_settings
|
||||||
from django.urls import resolve
|
from django.urls import resolve, reverse
|
||||||
|
|
||||||
from rest_framework import permissions, serializers, viewsets
|
from rest_framework import permissions, serializers, viewsets
|
||||||
from rest_framework.compat import get_regex_pattern
|
from rest_framework.compat import get_regex_pattern
|
||||||
|
@ -86,13 +87,13 @@ kwarged_notes_router = SimpleRouter()
|
||||||
kwarged_notes_router.register(r'notes', KWargedNoteViewSet)
|
kwarged_notes_router.register(r'notes', KWargedNoteViewSet)
|
||||||
|
|
||||||
namespaced_router = DefaultRouter()
|
namespaced_router = DefaultRouter()
|
||||||
namespaced_router.register(r'example', MockViewSet, base_name='example')
|
namespaced_router.register(r'example', MockViewSet, basename='example')
|
||||||
|
|
||||||
empty_prefix_router = SimpleRouter()
|
empty_prefix_router = SimpleRouter()
|
||||||
empty_prefix_router.register(r'', EmptyPrefixViewSet, base_name='empty_prefix')
|
empty_prefix_router.register(r'', EmptyPrefixViewSet, basename='empty_prefix')
|
||||||
|
|
||||||
regex_url_path_router = SimpleRouter()
|
regex_url_path_router = SimpleRouter()
|
||||||
regex_url_path_router.register(r'', RegexUrlPathViewSet, base_name='regex')
|
regex_url_path_router.register(r'', RegexUrlPathViewSet, basename='regex')
|
||||||
|
|
||||||
|
|
||||||
class BasicViewSet(viewsets.ViewSet):
|
class BasicViewSet(viewsets.ViewSet):
|
||||||
|
@ -103,44 +104,59 @@ class BasicViewSet(viewsets.ViewSet):
|
||||||
def action1(self, request, *args, **kwargs):
|
def action1(self, request, *args, **kwargs):
|
||||||
return Response({'method': 'action1'})
|
return Response({'method': 'action1'})
|
||||||
|
|
||||||
@action(methods=['post'], detail=True)
|
@action(methods=['post', 'delete'], detail=True)
|
||||||
def action2(self, request, *args, **kwargs):
|
def action2(self, request, *args, **kwargs):
|
||||||
return Response({'method': 'action2'})
|
return Response({'method': 'action2'})
|
||||||
|
|
||||||
@action(methods=['post', 'delete'], detail=True)
|
@action(methods=['post'], detail=True)
|
||||||
def action3(self, request, *args, **kwargs):
|
def action3(self, request, pk, *args, **kwargs):
|
||||||
return Response({'method': 'action2'})
|
return Response({'post': pk})
|
||||||
|
|
||||||
@action(detail=True)
|
@action3.mapping.delete
|
||||||
def link1(self, request, *args, **kwargs):
|
def action3_delete(self, request, pk, *args, **kwargs):
|
||||||
return Response({'method': 'link1'})
|
return Response({'delete': pk})
|
||||||
|
|
||||||
@action(detail=True)
|
|
||||||
def link2(self, request, *args, **kwargs):
|
|
||||||
return Response({'method': 'link2'})
|
|
||||||
|
|
||||||
|
|
||||||
class TestSimpleRouter(TestCase):
|
class TestSimpleRouter(URLPatternsTestCase, TestCase):
|
||||||
|
router = SimpleRouter()
|
||||||
|
router.register('basics', BasicViewSet, base_name='basic')
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
url(r'^api/', include(router.urls)),
|
||||||
|
]
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.router = SimpleRouter()
|
self.router = SimpleRouter()
|
||||||
|
|
||||||
def test_link_and_action_decorator(self):
|
def test_action_routes(self):
|
||||||
routes = self.router.get_routes(BasicViewSet)
|
# Get action routes (first two are list/detail)
|
||||||
decorator_routes = routes[2:]
|
routes = self.router.get_routes(BasicViewSet)[2:]
|
||||||
# Make sure all these endpoints exist and none have been clobbered
|
|
||||||
for i, endpoint in enumerate(['action1', 'action2', 'action3', 'link1', 'link2']):
|
assert routes[0].url == '^{prefix}/{lookup}/action1{trailing_slash}$'
|
||||||
route = decorator_routes[i]
|
assert routes[0].mapping == {
|
||||||
# check url listing
|
'post': 'action1',
|
||||||
assert route.url == '^{{prefix}}/{{lookup}}/{0}{{trailing_slash}}$'.format(endpoint)
|
}
|
||||||
# check method to function mapping
|
|
||||||
if endpoint == 'action3':
|
assert routes[1].url == '^{prefix}/{lookup}/action2{trailing_slash}$'
|
||||||
methods_map = ['post', 'delete']
|
assert routes[1].mapping == {
|
||||||
elif endpoint.startswith('action'):
|
'post': 'action2',
|
||||||
methods_map = ['post']
|
'delete': 'action2',
|
||||||
else:
|
}
|
||||||
methods_map = ['get']
|
|
||||||
for method in methods_map:
|
assert routes[2].url == '^{prefix}/{lookup}/action3{trailing_slash}$'
|
||||||
assert route.mapping[method] == endpoint
|
assert routes[2].mapping == {
|
||||||
|
'post': 'action3',
|
||||||
|
'delete': 'action3_delete',
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_multiple_action_handlers(self):
|
||||||
|
# Standard action
|
||||||
|
response = self.client.post(reverse('basic-action3', args=[1]))
|
||||||
|
assert response.data == {'post': '1'}
|
||||||
|
|
||||||
|
# Additional handler registered with MethodMapper
|
||||||
|
response = self.client.delete(reverse('basic-action3', args=[1]))
|
||||||
|
assert response.data == {'delete': '1'}
|
||||||
|
|
||||||
|
|
||||||
class TestRootView(URLPatternsTestCase, TestCase):
|
class TestRootView(URLPatternsTestCase, TestCase):
|
||||||
|
@ -304,7 +320,7 @@ class TestActionKeywordArgs(TestCase):
|
||||||
})
|
})
|
||||||
|
|
||||||
self.router = SimpleRouter()
|
self.router = SimpleRouter()
|
||||||
self.router.register(r'test', TestViewSet, base_name='test')
|
self.router.register(r'test', TestViewSet, basename='test')
|
||||||
self.view = self.router.urls[-1].callback
|
self.view = self.router.urls[-1].callback
|
||||||
|
|
||||||
def test_action_kwargs(self):
|
def test_action_kwargs(self):
|
||||||
|
@ -329,7 +345,7 @@ class TestActionAppliedToExistingRoute(TestCase):
|
||||||
})
|
})
|
||||||
|
|
||||||
self.router = SimpleRouter()
|
self.router = SimpleRouter()
|
||||||
self.router.register(r'test', TestViewSet, base_name='test')
|
self.router.register(r'test', TestViewSet, basename='test')
|
||||||
|
|
||||||
with pytest.raises(ImproperlyConfigured):
|
with pytest.raises(ImproperlyConfigured):
|
||||||
self.router.urls
|
self.router.urls
|
||||||
|
@ -466,3 +482,71 @@ class TestViewInitkwargs(URLPatternsTestCase, TestCase):
|
||||||
initkwargs = match.func.initkwargs
|
initkwargs = match.func.initkwargs
|
||||||
|
|
||||||
assert initkwargs['basename'] == 'routertestmodel'
|
assert initkwargs['basename'] == 'routertestmodel'
|
||||||
|
|
||||||
|
|
||||||
|
class TestBaseNameRename(TestCase):
|
||||||
|
|
||||||
|
def test_base_name_and_basename_assertion(self):
|
||||||
|
router = SimpleRouter()
|
||||||
|
|
||||||
|
msg = "Do not provide both the `basename` and `base_name` arguments."
|
||||||
|
with warnings.catch_warnings(record=True) as w, \
|
||||||
|
self.assertRaisesMessage(AssertionError, msg):
|
||||||
|
warnings.simplefilter('always')
|
||||||
|
router.register('mock', MockViewSet, 'mock', base_name='mock')
|
||||||
|
|
||||||
|
msg = "The `base_name` argument has been deprecated in favor of `basename`."
|
||||||
|
assert len(w) == 1
|
||||||
|
assert str(w[0].message) == msg
|
||||||
|
|
||||||
|
def test_base_name_argument_deprecation(self):
|
||||||
|
router = SimpleRouter()
|
||||||
|
|
||||||
|
with warnings.catch_warnings(record=True) as w:
|
||||||
|
warnings.simplefilter('always')
|
||||||
|
router.register('mock', MockViewSet, base_name='mock')
|
||||||
|
|
||||||
|
msg = "The `base_name` argument has been deprecated in favor of `basename`."
|
||||||
|
assert len(w) == 1
|
||||||
|
assert str(w[0].message) == msg
|
||||||
|
assert router.registry == [
|
||||||
|
('mock', MockViewSet, 'mock'),
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_basename_argument_no_warnings(self):
|
||||||
|
router = SimpleRouter()
|
||||||
|
|
||||||
|
with warnings.catch_warnings(record=True) as w:
|
||||||
|
warnings.simplefilter('always')
|
||||||
|
router.register('mock', MockViewSet, basename='mock')
|
||||||
|
|
||||||
|
assert len(w) == 0
|
||||||
|
assert router.registry == [
|
||||||
|
('mock', MockViewSet, 'mock'),
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_get_default_base_name_deprecation(self):
|
||||||
|
msg = "`CustomRouter.get_default_base_name` method should be renamed `get_default_basename`."
|
||||||
|
|
||||||
|
# Class definition should raise a warning
|
||||||
|
with warnings.catch_warnings(record=True) as w:
|
||||||
|
warnings.simplefilter('always')
|
||||||
|
|
||||||
|
class CustomRouter(SimpleRouter):
|
||||||
|
def get_default_base_name(self, viewset):
|
||||||
|
return 'foo'
|
||||||
|
|
||||||
|
assert len(w) == 1
|
||||||
|
assert str(w[0].message) == msg
|
||||||
|
|
||||||
|
# Deprecated method implementation should still be called
|
||||||
|
with warnings.catch_warnings(record=True) as w:
|
||||||
|
warnings.simplefilter('always')
|
||||||
|
|
||||||
|
router = CustomRouter()
|
||||||
|
router.register('mock', MockViewSet)
|
||||||
|
|
||||||
|
assert len(w) == 0
|
||||||
|
assert router.registry == [
|
||||||
|
('mock', MockViewSet, 'foo'),
|
||||||
|
]
|
||||||
|
|
|
@ -75,29 +75,39 @@ class ExampleViewSet(ModelViewSet):
|
||||||
"""
|
"""
|
||||||
A description of custom action.
|
A description of custom action.
|
||||||
"""
|
"""
|
||||||
return super(ExampleSerializer, self).retrieve(self, request)
|
raise NotImplementedError
|
||||||
|
|
||||||
@action(methods=['post'], detail=True, serializer_class=AnotherSerializerWithDictField)
|
@action(methods=['post'], detail=True, serializer_class=AnotherSerializerWithDictField)
|
||||||
def custom_action_with_dict_field(self, request, pk):
|
def custom_action_with_dict_field(self, request, pk):
|
||||||
"""
|
"""
|
||||||
A custom action using a dict field in the serializer.
|
A custom action using a dict field in the serializer.
|
||||||
"""
|
"""
|
||||||
return super(ExampleSerializer, self).retrieve(self, request)
|
raise NotImplementedError
|
||||||
|
|
||||||
@action(methods=['post'], detail=True, serializer_class=AnotherSerializerWithListFields)
|
@action(methods=['post'], detail=True, serializer_class=AnotherSerializerWithListFields)
|
||||||
def custom_action_with_list_fields(self, request, pk):
|
def custom_action_with_list_fields(self, request, pk):
|
||||||
"""
|
"""
|
||||||
A custom action using both list field and list serializer in the serializer.
|
A custom action using both list field and list serializer in the serializer.
|
||||||
"""
|
"""
|
||||||
return super(ExampleSerializer, self).retrieve(self, request)
|
raise NotImplementedError
|
||||||
|
|
||||||
@action(detail=False)
|
@action(detail=False)
|
||||||
def custom_list_action(self, request):
|
def custom_list_action(self, request):
|
||||||
return super(ExampleViewSet, self).list(self, request)
|
raise NotImplementedError
|
||||||
|
|
||||||
@action(methods=['post', 'get'], detail=False, serializer_class=EmptySerializer)
|
@action(methods=['post', 'get'], detail=False, serializer_class=EmptySerializer)
|
||||||
def custom_list_action_multiple_methods(self, request):
|
def custom_list_action_multiple_methods(self, request):
|
||||||
return super(ExampleViewSet, self).list(self, request)
|
"""Custom description."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
@custom_list_action_multiple_methods.mapping.delete
|
||||||
|
def custom_list_action_multiple_methods_delete(self, request):
|
||||||
|
"""Deletion description."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
@action(detail=False, schema=None)
|
||||||
|
def excluded_action(self, request):
|
||||||
|
pass
|
||||||
|
|
||||||
def get_serializer(self, *args, **kwargs):
|
def get_serializer(self, *args, **kwargs):
|
||||||
assert self.request
|
assert self.request
|
||||||
|
@ -123,7 +133,7 @@ else:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
router = DefaultRouter()
|
router = DefaultRouter()
|
||||||
router.register('example', ExampleViewSet, base_name='example')
|
router.register('example', ExampleViewSet, basename='example')
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
url(r'^$', schema_view),
|
url(r'^$', schema_view),
|
||||||
url(r'^', include(router.urls))
|
url(r'^', include(router.urls))
|
||||||
|
@ -158,7 +168,8 @@ class TestRouterGeneratedSchema(TestCase):
|
||||||
'custom_list_action_multiple_methods': {
|
'custom_list_action_multiple_methods': {
|
||||||
'read': coreapi.Link(
|
'read': coreapi.Link(
|
||||||
url='/example/custom_list_action_multiple_methods/',
|
url='/example/custom_list_action_multiple_methods/',
|
||||||
action='get'
|
action='get',
|
||||||
|
description='Custom description.',
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
'documented_custom_action': {
|
'documented_custom_action': {
|
||||||
|
@ -256,12 +267,19 @@ class TestRouterGeneratedSchema(TestCase):
|
||||||
'custom_list_action_multiple_methods': {
|
'custom_list_action_multiple_methods': {
|
||||||
'read': coreapi.Link(
|
'read': coreapi.Link(
|
||||||
url='/example/custom_list_action_multiple_methods/',
|
url='/example/custom_list_action_multiple_methods/',
|
||||||
action='get'
|
action='get',
|
||||||
|
description='Custom description.',
|
||||||
),
|
),
|
||||||
'create': coreapi.Link(
|
'create': coreapi.Link(
|
||||||
url='/example/custom_list_action_multiple_methods/',
|
url='/example/custom_list_action_multiple_methods/',
|
||||||
action='post'
|
action='post',
|
||||||
)
|
description='Custom description.',
|
||||||
|
),
|
||||||
|
'delete': coreapi.Link(
|
||||||
|
url='/example/custom_list_action_multiple_methods/',
|
||||||
|
action='delete',
|
||||||
|
description='Deletion description.',
|
||||||
|
),
|
||||||
},
|
},
|
||||||
'documented_custom_action': {
|
'documented_custom_action': {
|
||||||
'read': coreapi.Link(
|
'read': coreapi.Link(
|
||||||
|
@ -526,7 +544,7 @@ class TestSchemaGeneratorNotAtRoot(TestCase):
|
||||||
class TestSchemaGeneratorWithMethodLimitedViewSets(TestCase):
|
class TestSchemaGeneratorWithMethodLimitedViewSets(TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
router = DefaultRouter()
|
router = DefaultRouter()
|
||||||
router.register('example1', MethodLimitedViewSet, base_name='example1')
|
router.register('example1', MethodLimitedViewSet, basename='example1')
|
||||||
self.patterns = [
|
self.patterns = [
|
||||||
url(r'^', include(router.urls))
|
url(r'^', include(router.urls))
|
||||||
]
|
]
|
||||||
|
@ -561,7 +579,8 @@ class TestSchemaGeneratorWithMethodLimitedViewSets(TestCase):
|
||||||
'custom_list_action_multiple_methods': {
|
'custom_list_action_multiple_methods': {
|
||||||
'read': coreapi.Link(
|
'read': coreapi.Link(
|
||||||
url='/example1/custom_list_action_multiple_methods/',
|
url='/example1/custom_list_action_multiple_methods/',
|
||||||
action='get'
|
action='get',
|
||||||
|
description='Custom description.',
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
'documented_custom_action': {
|
'documented_custom_action': {
|
||||||
|
@ -589,8 +608,8 @@ class TestSchemaGeneratorWithMethodLimitedViewSets(TestCase):
|
||||||
class TestSchemaGeneratorWithRestrictedViewSets(TestCase):
|
class TestSchemaGeneratorWithRestrictedViewSets(TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
router = DefaultRouter()
|
router = DefaultRouter()
|
||||||
router.register('example1', Http404ExampleViewSet, base_name='example1')
|
router.register('example1', Http404ExampleViewSet, basename='example1')
|
||||||
router.register('example2', PermissionDeniedExampleViewSet, base_name='example2')
|
router.register('example2', PermissionDeniedExampleViewSet, basename='example2')
|
||||||
self.patterns = [
|
self.patterns = [
|
||||||
url('^example/?$', ExampleListView.as_view()),
|
url('^example/?$', ExampleListView.as_view()),
|
||||||
url(r'^', include(router.urls))
|
url(r'^', include(router.urls))
|
||||||
|
@ -762,6 +781,45 @@ class TestAutoSchema(TestCase):
|
||||||
assert len(fields) == 2
|
assert len(fields) == 2
|
||||||
assert "my_extra_field" in [f.name for f in fields]
|
assert "my_extra_field" in [f.name for f in fields]
|
||||||
|
|
||||||
|
@pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
|
||||||
|
def test_viewset_action_with_schema(self):
|
||||||
|
class CustomViewSet(GenericViewSet):
|
||||||
|
@action(detail=True, schema=AutoSchema(manual_fields=[
|
||||||
|
coreapi.Field(
|
||||||
|
"my_extra_field",
|
||||||
|
required=True,
|
||||||
|
location="path",
|
||||||
|
schema=coreschema.String()
|
||||||
|
),
|
||||||
|
]))
|
||||||
|
def extra_action(self, pk, **kwargs):
|
||||||
|
pass
|
||||||
|
|
||||||
|
router = SimpleRouter()
|
||||||
|
router.register(r'detail', CustomViewSet, basename='detail')
|
||||||
|
|
||||||
|
generator = SchemaGenerator()
|
||||||
|
view = generator.create_view(router.urls[0].callback, 'GET')
|
||||||
|
link = view.schema.get_link('/a/url/{id}/', 'GET', '')
|
||||||
|
fields = link.fields
|
||||||
|
|
||||||
|
assert len(fields) == 2
|
||||||
|
assert "my_extra_field" in [f.name for f in fields]
|
||||||
|
|
||||||
|
@pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
|
||||||
|
def test_viewset_action_with_null_schema(self):
|
||||||
|
class CustomViewSet(GenericViewSet):
|
||||||
|
@action(detail=True, schema=None)
|
||||||
|
def extra_action(self, pk, **kwargs):
|
||||||
|
pass
|
||||||
|
|
||||||
|
router = SimpleRouter()
|
||||||
|
router.register(r'detail', CustomViewSet, basename='detail')
|
||||||
|
|
||||||
|
generator = SchemaGenerator()
|
||||||
|
view = generator.create_view(router.urls[0].callback, 'GET')
|
||||||
|
assert view.schema is None
|
||||||
|
|
||||||
@pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
|
@pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
|
||||||
def test_view_with_manual_schema(self):
|
def test_view_with_manual_schema(self):
|
||||||
|
|
||||||
|
@ -1026,7 +1084,7 @@ class NamingCollisionViewSet(GenericViewSet):
|
||||||
|
|
||||||
|
|
||||||
naming_collisions_router = SimpleRouter()
|
naming_collisions_router = SimpleRouter()
|
||||||
naming_collisions_router.register(r'collision', NamingCollisionViewSet, base_name="collision")
|
naming_collisions_router.register(r'collision', NamingCollisionViewSet, basename="collision")
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
|
@pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
|
||||||
|
|
|
@ -4,6 +4,7 @@ from __future__ import unicode_literals
|
||||||
from django.conf.urls import url
|
from django.conf.urls import url
|
||||||
from django.test import TestCase, override_settings
|
from django.test import TestCase, override_settings
|
||||||
|
|
||||||
|
from rest_framework.decorators import action
|
||||||
from rest_framework.routers import SimpleRouter
|
from rest_framework.routers import SimpleRouter
|
||||||
from rest_framework.serializers import ModelSerializer
|
from rest_framework.serializers import ModelSerializer
|
||||||
from rest_framework.utils import json
|
from rest_framework.utils import json
|
||||||
|
@ -43,6 +44,14 @@ class ResourceViewSet(ModelViewSet):
|
||||||
serializer_class = ModelSerializer
|
serializer_class = ModelSerializer
|
||||||
queryset = BasicModel.objects.all()
|
queryset = BasicModel.objects.all()
|
||||||
|
|
||||||
|
@action(detail=False)
|
||||||
|
def list_action(self, request, *args, **kwargs):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
@action(detail=True)
|
||||||
|
def detail_action(self, request, *args, **kwargs):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|
||||||
router = SimpleRouter()
|
router = SimpleRouter()
|
||||||
router.register(r'resources', ResourceViewSet)
|
router.register(r'resources', ResourceViewSet)
|
||||||
|
@ -119,6 +128,23 @@ class BreadcrumbTests(TestCase):
|
||||||
('Resource Instance', '/resources/1/')
|
('Resource Instance', '/resources/1/')
|
||||||
]
|
]
|
||||||
|
|
||||||
|
def test_modelviewset_list_action_breadcrumbs(self):
|
||||||
|
url = '/resources/list_action/'
|
||||||
|
assert get_breadcrumbs(url) == [
|
||||||
|
('Root', '/'),
|
||||||
|
('Resource List', '/resources/'),
|
||||||
|
('List action', '/resources/list_action/'),
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_modelviewset_detail_action_breadcrumbs(self):
|
||||||
|
url = '/resources/1/detail_action/'
|
||||||
|
assert get_breadcrumbs(url) == [
|
||||||
|
('Root', '/'),
|
||||||
|
('Resource List', '/resources/'),
|
||||||
|
('Resource Instance', '/resources/1/'),
|
||||||
|
('Detail action', '/resources/1/detail_action/'),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
class JsonFloatTests(TestCase):
|
class JsonFloatTests(TestCase):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -1,3 +1,5 @@
|
||||||
|
from collections import OrderedDict
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from django.conf.urls import include, url
|
from django.conf.urls import include, url
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
@ -35,10 +37,10 @@ class ActionViewSet(GenericViewSet):
|
||||||
queryset = Action.objects.all()
|
queryset = Action.objects.all()
|
||||||
|
|
||||||
def list(self, request, *args, **kwargs):
|
def list(self, request, *args, **kwargs):
|
||||||
raise NotImplementedError
|
return Response()
|
||||||
|
|
||||||
def retrieve(self, request, *args, **kwargs):
|
def retrieve(self, request, *args, **kwargs):
|
||||||
raise NotImplementedError
|
return Response()
|
||||||
|
|
||||||
@action(detail=False)
|
@action(detail=False)
|
||||||
def list_action(self, request, *args, **kwargs):
|
def list_action(self, request, *args, **kwargs):
|
||||||
|
@ -56,10 +58,14 @@ class ActionViewSet(GenericViewSet):
|
||||||
def custom_detail_action(self, request, *args, **kwargs):
|
def custom_detail_action(self, request, *args, **kwargs):
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
|
|
||||||
|
@action(detail=True, url_path=r'unresolvable/(?P<arg>\w+)', url_name='unresolvable')
|
||||||
|
def unresolvable_detail_action(self, request, *args, **kwargs):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|
||||||
router = SimpleRouter()
|
router = SimpleRouter()
|
||||||
router.register(r'actions', ActionViewSet)
|
router.register(r'actions', ActionViewSet)
|
||||||
router.register(r'actions-alt', ActionViewSet, base_name='actions-alt')
|
router.register(r'actions-alt', ActionViewSet, basename='actions-alt')
|
||||||
|
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
|
@ -96,6 +102,16 @@ class InitializeViewSetsTestCase(TestCase):
|
||||||
"when calling `.as_view()` on a ViewSet. "
|
"when calling `.as_view()` on a ViewSet. "
|
||||||
"For example `.as_view({'get': 'list'})`")
|
"For example `.as_view({'get': 'list'})`")
|
||||||
|
|
||||||
|
def test_initialize_view_set_with_both_name_and_suffix(self):
|
||||||
|
with pytest.raises(TypeError) as excinfo:
|
||||||
|
BasicViewSet.as_view(name='', suffix='', actions={
|
||||||
|
'get': 'list',
|
||||||
|
})
|
||||||
|
|
||||||
|
assert str(excinfo.value) == (
|
||||||
|
"BasicViewSet() received both `name` and `suffix`, "
|
||||||
|
"which are mutually exclusive arguments.")
|
||||||
|
|
||||||
def test_args_kwargs_request_action_map_on_self(self):
|
def test_args_kwargs_request_action_map_on_self(self):
|
||||||
"""
|
"""
|
||||||
Test a view only has args, kwargs, request, action_map
|
Test a view only has args, kwargs, request, action_map
|
||||||
|
@ -111,21 +127,57 @@ class InitializeViewSetsTestCase(TestCase):
|
||||||
self.assertIn(attribute, dir(view))
|
self.assertIn(attribute, dir(view))
|
||||||
|
|
||||||
|
|
||||||
class GetExtraActionTests(TestCase):
|
class GetExtraActionsTests(TestCase):
|
||||||
|
|
||||||
def test_extra_actions(self):
|
def test_extra_actions(self):
|
||||||
view = ActionViewSet()
|
view = ActionViewSet()
|
||||||
actual = [action.__name__ for action in view.get_extra_actions()]
|
actual = [action.__name__ for action in view.get_extra_actions()]
|
||||||
expected = ['custom_detail_action', 'custom_list_action', 'detail_action', 'list_action']
|
expected = [
|
||||||
|
'custom_detail_action',
|
||||||
|
'custom_list_action',
|
||||||
|
'detail_action',
|
||||||
|
'list_action',
|
||||||
|
'unresolvable_detail_action',
|
||||||
|
]
|
||||||
|
|
||||||
self.assertEqual(actual, expected)
|
self.assertEqual(actual, expected)
|
||||||
|
|
||||||
|
|
||||||
|
@override_settings(ROOT_URLCONF='tests.test_viewsets')
|
||||||
|
class GetExtraActionUrlMapTests(TestCase):
|
||||||
|
|
||||||
|
def test_list_view(self):
|
||||||
|
response = self.client.get('/api/actions/')
|
||||||
|
view = response.renderer_context['view']
|
||||||
|
|
||||||
|
expected = OrderedDict([
|
||||||
|
('Custom list action', 'http://testserver/api/actions/custom_list_action/'),
|
||||||
|
('List action', 'http://testserver/api/actions/list_action/'),
|
||||||
|
])
|
||||||
|
|
||||||
|
self.assertEqual(view.get_extra_action_url_map(), expected)
|
||||||
|
|
||||||
|
def test_detail_view(self):
|
||||||
|
response = self.client.get('/api/actions/1/')
|
||||||
|
view = response.renderer_context['view']
|
||||||
|
|
||||||
|
expected = OrderedDict([
|
||||||
|
('Custom detail action', 'http://testserver/api/actions/1/custom_detail_action/'),
|
||||||
|
('Detail action', 'http://testserver/api/actions/1/detail_action/'),
|
||||||
|
# "Unresolvable detail action" excluded, since it's not resolvable
|
||||||
|
])
|
||||||
|
|
||||||
|
self.assertEqual(view.get_extra_action_url_map(), expected)
|
||||||
|
|
||||||
|
def test_uninitialized_view(self):
|
||||||
|
self.assertEqual(ActionViewSet().get_extra_action_url_map(), OrderedDict())
|
||||||
|
|
||||||
|
|
||||||
@override_settings(ROOT_URLCONF='tests.test_viewsets')
|
@override_settings(ROOT_URLCONF='tests.test_viewsets')
|
||||||
class ReverseActionTests(TestCase):
|
class ReverseActionTests(TestCase):
|
||||||
def test_default_basename(self):
|
def test_default_basename(self):
|
||||||
view = ActionViewSet()
|
view = ActionViewSet()
|
||||||
view.basename = router.get_default_base_name(ActionViewSet)
|
view.basename = router.get_default_basename(ActionViewSet)
|
||||||
view.request = None
|
view.request = None
|
||||||
|
|
||||||
assert view.reverse_action('list') == '/api/actions/'
|
assert view.reverse_action('list') == '/api/actions/'
|
||||||
|
@ -151,7 +203,7 @@ class ReverseActionTests(TestCase):
|
||||||
|
|
||||||
def test_request_passing(self):
|
def test_request_passing(self):
|
||||||
view = ActionViewSet()
|
view = ActionViewSet()
|
||||||
view.basename = router.get_default_base_name(ActionViewSet)
|
view.basename = router.get_default_basename(ActionViewSet)
|
||||||
view.request = factory.get('/')
|
view.request = factory.get('/')
|
||||||
|
|
||||||
# Passing the view's request object should result in an absolute URL.
|
# Passing the view's request object should result in an absolute URL.
|
||||||
|
|
15
tox.ini
15
tox.ini
|
@ -1,31 +1,28 @@
|
||||||
[tox]
|
[tox]
|
||||||
envlist =
|
envlist =
|
||||||
{py27,py34,py35}-django110,
|
|
||||||
{py27,py34,py35,py36}-django111,
|
{py27,py34,py35,py36}-django111,
|
||||||
{py34,py35,py36}-django20,
|
{py34,py35,py36,py37}-django20,
|
||||||
{py35,py36}-django21
|
{py35,py36,py37}-django21
|
||||||
{py35,py36}-djangomaster,
|
{py35,py36,py37}-djangomaster,
|
||||||
base,dist,lint,docs,
|
base,dist,lint,docs,
|
||||||
|
|
||||||
[travis:env]
|
[travis:env]
|
||||||
DJANGO =
|
DJANGO =
|
||||||
1.10: django110
|
|
||||||
1.11: django111
|
1.11: django111
|
||||||
2.0: django20
|
2.0: django20
|
||||||
2.1: django21
|
2.1: django21
|
||||||
master: djangomaster
|
master: djangomaster
|
||||||
|
|
||||||
[testenv]
|
[testenv]
|
||||||
commands = ./runtests.py --fast {posargs} --coverage -rw
|
commands = ./runtests.py --fast --coverage {posargs}
|
||||||
envdir = {toxworkdir}/venvs/{envname}
|
envdir = {toxworkdir}/venvs/{envname}
|
||||||
setenv =
|
setenv =
|
||||||
PYTHONDONTWRITEBYTECODE=1
|
PYTHONDONTWRITEBYTECODE=1
|
||||||
PYTHONWARNINGS=once
|
PYTHONWARNINGS=once
|
||||||
deps =
|
deps =
|
||||||
django110: Django>=1.10,<1.11
|
|
||||||
django111: Django>=1.11,<2.0
|
django111: Django>=1.11,<2.0
|
||||||
django20: Django>=2.0,<2.1
|
django20: Django>=2.0,<2.1
|
||||||
django21: Django>=2.1b1,<2.2
|
django21: Django>=2.1,<2.2
|
||||||
djangomaster: https://github.com/django/django/archive/master.tar.gz
|
djangomaster: https://github.com/django/django/archive/master.tar.gz
|
||||||
-rrequirements/requirements-testing.txt
|
-rrequirements/requirements-testing.txt
|
||||||
-rrequirements/requirements-optionals.txt
|
-rrequirements/requirements-optionals.txt
|
||||||
|
@ -37,7 +34,7 @@ deps =
|
||||||
-rrequirements/requirements-testing.txt
|
-rrequirements/requirements-testing.txt
|
||||||
|
|
||||||
[testenv:dist]
|
[testenv:dist]
|
||||||
commands = ./runtests.py --fast {posargs} --no-pkgroot --staticfiles -rw
|
commands = ./runtests.py --fast --no-pkgroot --staticfiles {posargs}
|
||||||
deps =
|
deps =
|
||||||
django
|
django
|
||||||
-rrequirements/requirements-testing.txt
|
-rrequirements/requirements-testing.txt
|
||||||
|
|
Loading…
Reference in New Issue
Block a user