mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-27 08:29:59 +03:00
docs: fix
- linting and style checking
This commit is contained in:
parent
d507cd851c
commit
e3bc8050c4
|
@ -247,7 +247,6 @@ And in your `urls.py`:
|
||||||
path('api-token-auth/', CustomAuthToken.as_view())
|
path('api-token-auth/', CustomAuthToken.as_view())
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
#### With Django admin
|
#### With Django admin
|
||||||
|
|
||||||
It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
||||||
|
@ -258,7 +257,6 @@ It is also possible to create Tokens manually through the admin interface. In ca
|
||||||
|
|
||||||
TokenAdmin.raw_id_fields = ['user']
|
TokenAdmin.raw_id_fields = ['user']
|
||||||
|
|
||||||
|
|
||||||
#### Using Django manage.py command
|
#### Using Django manage.py command
|
||||||
|
|
||||||
Since version 3.6.4 it's possible to generate a user token using the following command:
|
Since version 3.6.4 it's possible to generate a user token using the following command:
|
||||||
|
@ -273,7 +271,6 @@ In case you want to regenerate the token (for example if it has been compromised
|
||||||
|
|
||||||
./manage.py drf_create_token -r <username>
|
./manage.py drf_create_token -r <username>
|
||||||
|
|
||||||
|
|
||||||
## SessionAuthentication
|
## SessionAuthentication
|
||||||
|
|
||||||
This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
|
This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
|
||||||
|
@ -291,7 +288,6 @@ If you're using an AJAX-style API with SessionAuthentication, you'll need to mak
|
||||||
|
|
||||||
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.
|
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.
|
||||||
|
|
||||||
|
|
||||||
## RemoteUserAuthentication
|
## RemoteUserAuthentication
|
||||||
|
|
||||||
This authentication scheme allows you to delegate authentication to your web server, which sets the `REMOTE_USER`
|
This authentication scheme allows you to delegate authentication to your web server, which sets the `REMOTE_USER`
|
||||||
|
@ -312,7 +308,6 @@ Consult your web server's documentation for information about configuring an aut
|
||||||
* [Apache Authentication How-To](https://httpd.apache.org/docs/2.4/howto/auth.html)
|
* [Apache Authentication How-To](https://httpd.apache.org/docs/2.4/howto/auth.html)
|
||||||
* [NGINX (Restricting Access)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)
|
* [NGINX (Restricting Access)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)
|
||||||
|
|
||||||
|
|
||||||
# Custom authentication
|
# Custom authentication
|
||||||
|
|
||||||
To implement a custom authentication scheme, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
|
To implement a custom authentication scheme, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
|
||||||
|
@ -424,7 +419,6 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
|
||||||
|
|
||||||
This library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.
|
This library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.
|
||||||
|
|
||||||
|
|
||||||
There are currently two forks of this project.
|
There are currently two forks of this project.
|
||||||
|
|
||||||
* [Django-rest-auth][django-rest-auth] is the original project, [but is not currently receiving updates](https://github.com/Tivix/django-rest-auth/issues/568).
|
* [Django-rest-auth][django-rest-auth] is the original project, [but is not currently receiving updates](https://github.com/Tivix/django-rest-auth/issues/568).
|
||||||
|
@ -460,8 +454,6 @@ More information can be found in the [Documentation](https://django-rest-durin.r
|
||||||
[django-rest-framework-oauth]: https://jpadilla.github.io/django-rest-framework-oauth/
|
[django-rest-framework-oauth]: https://jpadilla.github.io/django-rest-framework-oauth/
|
||||||
[django-rest-framework-oauth-authentication]: https://jpadilla.github.io/django-rest-framework-oauth/authentication/
|
[django-rest-framework-oauth-authentication]: https://jpadilla.github.io/django-rest-framework-oauth/authentication/
|
||||||
[django-rest-framework-oauth-permissions]: https://jpadilla.github.io/django-rest-framework-oauth/permissions/
|
[django-rest-framework-oauth-permissions]: https://jpadilla.github.io/django-rest-framework-oauth/permissions/
|
||||||
[juanriaza]: https://github.com/juanriaza
|
|
||||||
[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
|
|
||||||
[oauth-1.0a]: https://oauth.net/core/1.0a/
|
[oauth-1.0a]: https://oauth.net/core/1.0a/
|
||||||
[django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
|
[django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
|
||||||
[jazzband]: https://github.com/jazzband/
|
[jazzband]: https://github.com/jazzband/
|
||||||
|
|
|
@ -82,9 +82,9 @@ The default content negotiation class may be set globally, using the `DEFAULT_CO
|
||||||
|
|
||||||
You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class-based views.
|
You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class-based views.
|
||||||
|
|
||||||
from myapp.negotiation import IgnoreClientContentNegotiation
|
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
|
from myapp.negotiation import IgnoreClientContentNegotiation
|
||||||
|
|
||||||
class NoNegotiationView(APIView):
|
class NoNegotiationView(APIView):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -171,10 +171,10 @@ Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.T
|
||||||
|
|
||||||
**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)`
|
**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)`
|
||||||
|
|
||||||
- `max_length` - Validates that the input contains no more than this number of characters.
|
* `max_length` - Validates that the input contains no more than this number of characters.
|
||||||
- `min_length` - Validates that the input contains no fewer than this number of characters.
|
* `min_length` - Validates that the input contains no fewer than this number of characters.
|
||||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||||
- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
|
* `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
|
||||||
|
|
||||||
The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.
|
The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.
|
||||||
|
|
||||||
|
@ -222,11 +222,11 @@ A field that ensures the input is a valid UUID string. The `to_internal_value` m
|
||||||
|
|
||||||
**Signature:** `UUIDField(format='hex_verbose')`
|
**Signature:** `UUIDField(format='hex_verbose')`
|
||||||
|
|
||||||
- `format`: Determines the representation format of the uuid value
|
* `format`: Determines the representation format of the uuid value
|
||||||
- `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
* `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||||
- `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
|
* `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
|
||||||
- `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
|
* `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
|
||||||
- `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
* `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||||
Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value`
|
Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value`
|
||||||
|
|
||||||
## FilePathField
|
## FilePathField
|
||||||
|
@ -237,11 +237,11 @@ Corresponds to `django.forms.fields.FilePathField`.
|
||||||
|
|
||||||
**Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)`
|
**Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)`
|
||||||
|
|
||||||
- `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
|
* `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
|
||||||
- `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
|
* `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
|
||||||
- `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
|
* `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
|
||||||
- `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
|
* `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
|
||||||
- `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
|
* `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
|
||||||
|
|
||||||
## IPAddressField
|
## IPAddressField
|
||||||
|
|
||||||
|
@ -251,8 +251,8 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen
|
||||||
|
|
||||||
**Signature**: `IPAddressField(protocol='both', unpack_ipv4=False, **options)`
|
**Signature**: `IPAddressField(protocol='both', unpack_ipv4=False, **options)`
|
||||||
|
|
||||||
- `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
|
* `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
|
||||||
- `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
|
* `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -266,8 +266,8 @@ Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.
|
||||||
|
|
||||||
**Signature**: `IntegerField(max_value=None, min_value=None)`
|
**Signature**: `IntegerField(max_value=None, min_value=None)`
|
||||||
|
|
||||||
- `max_value` Validate that the number provided is no greater than this value.
|
* `max_value` Validate that the number provided is no greater than this value.
|
||||||
- `min_value` Validate that the number provided is no less than this value.
|
* `min_value` Validate that the number provided is no less than this value.
|
||||||
|
|
||||||
## FloatField
|
## FloatField
|
||||||
|
|
||||||
|
@ -277,8 +277,8 @@ Corresponds to `django.db.models.fields.FloatField`.
|
||||||
|
|
||||||
**Signature**: `FloatField(max_value=None, min_value=None)`
|
**Signature**: `FloatField(max_value=None, min_value=None)`
|
||||||
|
|
||||||
- `max_value` Validate that the number provided is no greater than this value.
|
* `max_value` Validate that the number provided is no greater than this value.
|
||||||
- `min_value` Validate that the number provided is no less than this value.
|
* `min_value` Validate that the number provided is no less than this value.
|
||||||
|
|
||||||
## DecimalField
|
## DecimalField
|
||||||
|
|
||||||
|
@ -288,13 +288,13 @@ Corresponds to `django.db.models.fields.DecimalField`.
|
||||||
|
|
||||||
**Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)`
|
**Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)`
|
||||||
|
|
||||||
- `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
|
* `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
|
||||||
- `decimal_places` The number of decimal places to store with the number.
|
* `decimal_places` The number of decimal places to store with the number.
|
||||||
- `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
|
* `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
|
||||||
- `max_value` Validate that the number provided is no greater than this value.
|
* `max_value` Validate that the number provided is no greater than this value.
|
||||||
- `min_value` Validate that the number provided is no less than this value.
|
* `min_value` Validate that the number provided is no less than this value.
|
||||||
- `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
|
* `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
|
||||||
- `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
|
* `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
|
||||||
|
|
||||||
#### Example usage
|
#### Example usage
|
||||||
|
|
||||||
|
@ -380,8 +380,8 @@ The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu
|
||||||
|
|
||||||
**Signature:** `DurationField(max_value=None, min_value=None)`
|
**Signature:** `DurationField(max_value=None, min_value=None)`
|
||||||
|
|
||||||
- `max_value` Validate that the duration provided is no greater than this value.
|
* `max_value` Validate that the duration provided is no greater than this value.
|
||||||
- `min_value` Validate that the duration provided is no less than this value.
|
* `min_value` Validate that the duration provided is no less than this value.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -395,10 +395,10 @@ Used by `ModelSerializer` to automatically generate fields if the corresponding
|
||||||
|
|
||||||
**Signature:** `ChoiceField(choices)`
|
**Signature:** `ChoiceField(choices)`
|
||||||
|
|
||||||
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||||
|
|
||||||
Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
|
Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
|
||||||
|
|
||||||
|
@ -408,10 +408,10 @@ A field that can accept a set of zero, one or many values, chosen from a limited
|
||||||
|
|
||||||
**Signature:** `MultipleChoiceField(choices)`
|
**Signature:** `MultipleChoiceField(choices)`
|
||||||
|
|
||||||
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||||
|
|
||||||
As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
|
As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
|
||||||
|
|
||||||
|
@ -432,9 +432,9 @@ Corresponds to `django.forms.fields.FileField`.
|
||||||
|
|
||||||
**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
||||||
|
|
||||||
- `max_length` - Designates the maximum length for the file name.
|
* `max_length` - Designates the maximum length for the file name.
|
||||||
- `allow_empty_file` - Designates if empty files are allowed.
|
* `allow_empty_file` - Designates if empty files are allowed.
|
||||||
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||||
|
|
||||||
## ImageField
|
## ImageField
|
||||||
|
|
||||||
|
@ -444,9 +444,9 @@ Corresponds to `django.forms.fields.ImageField`.
|
||||||
|
|
||||||
**Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
**Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
||||||
|
|
||||||
- `max_length` - Designates the maximum length for the file name.
|
* `max_length` - Designates the maximum length for the file name.
|
||||||
- `allow_empty_file` - Designates if empty files are allowed.
|
* `allow_empty_file` - Designates if empty files are allowed.
|
||||||
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||||
|
|
||||||
Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained.
|
Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained.
|
||||||
|
|
||||||
|
@ -460,10 +460,10 @@ A field class that validates a list of objects.
|
||||||
|
|
||||||
**Signature**: `ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)`
|
**Signature**: `ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)`
|
||||||
|
|
||||||
- `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
|
* `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
|
||||||
- `allow_empty` - Designates if empty lists are allowed.
|
* `allow_empty` - Designates if empty lists are allowed.
|
||||||
- `min_length` - Validates that the list contains no fewer than this number of elements.
|
* `min_length` - Validates that the list contains no fewer than this number of elements.
|
||||||
- `max_length` - Validates that the list contains no more than this number of elements.
|
* `max_length` - Validates that the list contains no more than this number of elements.
|
||||||
|
|
||||||
For example, to validate a list of integers you might use something like the following:
|
For example, to validate a list of integers you might use something like the following:
|
||||||
|
|
||||||
|
@ -484,8 +484,8 @@ A field class that validates a dictionary of objects. The keys in `DictField` ar
|
||||||
|
|
||||||
**Signature**: `DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
**Signature**: `DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
||||||
|
|
||||||
- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
|
* `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
|
||||||
- `allow_empty` - Designates if empty dictionaries are allowed.
|
* `allow_empty` - Designates if empty dictionaries are allowed.
|
||||||
|
|
||||||
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
|
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
|
||||||
|
|
||||||
|
@ -502,8 +502,8 @@ A preconfigured `DictField` that is compatible with Django's postgres `HStoreFie
|
||||||
|
|
||||||
**Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
**Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
||||||
|
|
||||||
- `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
|
* `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
|
||||||
- `allow_empty` - Designates if empty dictionaries are allowed.
|
* `allow_empty` - Designates if empty dictionaries are allowed.
|
||||||
|
|
||||||
Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings.
|
Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings.
|
||||||
|
|
||||||
|
@ -513,8 +513,8 @@ A field class that validates that the incoming data structure consists of valid
|
||||||
|
|
||||||
**Signature**: `JSONField(binary, encoder)`
|
**Signature**: `JSONField(binary, encoder)`
|
||||||
|
|
||||||
- `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
|
* `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
|
||||||
- `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
|
* `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -565,7 +565,7 @@ This is a read-only field. It gets its value by calling a method on the serializ
|
||||||
|
|
||||||
**Signature**: `SerializerMethodField(method_name=None)`
|
**Signature**: `SerializerMethodField(method_name=None)`
|
||||||
|
|
||||||
- `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
|
* `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
|
||||||
|
|
||||||
The serializer method referred to by the `method_name` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
|
The serializer method referred to by the `method_name` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
|
||||||
|
|
||||||
|
@ -812,7 +812,6 @@ For this reason, the nested serializer approach would be the first to try. You
|
||||||
would use the custom field approach when the nested serializer becomes infeasible
|
would use the custom field approach when the nested serializer becomes infeasible
|
||||||
or overly complex.
|
or overly complex.
|
||||||
|
|
||||||
|
|
||||||
# Third party packages
|
# Third party packages
|
||||||
|
|
||||||
The following third party packages are also available.
|
The following third party packages are also available.
|
||||||
|
|
|
@ -38,7 +38,6 @@ For example:
|
||||||
user = self.request.user
|
user = self.request.user
|
||||||
return Purchase.objects.filter(purchaser=user)
|
return Purchase.objects.filter(purchaser=user)
|
||||||
|
|
||||||
|
|
||||||
## Filtering against the URL
|
## Filtering against the URL
|
||||||
|
|
||||||
Another style of filtering might involve restricting the queryset based on some part of the URL.
|
Another style of filtering might involve restricting the queryset based on some part of the URL.
|
||||||
|
@ -187,7 +186,6 @@ For more advanced filtering requirements you can specify a `FilterSet` class tha
|
||||||
You can read more about `FilterSet`s in the [django-filter documentation][django-filter-docs].
|
You can read more about `FilterSet`s in the [django-filter documentation][django-filter-docs].
|
||||||
It's also recommended that you read the section on [DRF integration][django-filter-drf-docs].
|
It's also recommended that you read the section on [DRF integration][django-filter-drf-docs].
|
||||||
|
|
||||||
|
|
||||||
## SearchFilter
|
## SearchFilter
|
||||||
|
|
||||||
The `SearchFilter` class supports simple single query parameter based searching, and is based on the [Django admin's search functionality][search-django-admin].
|
The `SearchFilter` class supports simple single query parameter based searching, and is based on the [Django admin's search functionality][search-django-admin].
|
||||||
|
|
|
@ -386,7 +386,6 @@ The following third party packages provide additional generic view implementatio
|
||||||
|
|
||||||
[Django Rest Multiple Models][django-rest-multiple-models] provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
|
[Django Rest Multiple Models][django-rest-multiple-models] provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
|
||||||
|
|
||||||
|
|
||||||
[cite]: https://docs.djangoproject.com/en/stable/ref/class-based-views/#base-vs-generic-views
|
[cite]: https://docs.djangoproject.com/en/stable/ref/class-based-views/#base-vs-generic-views
|
||||||
[GenericAPIView]: #genericapiview
|
[GenericAPIView]: #genericapiview
|
||||||
[ListModelMixin]: #listmodelmixin
|
[ListModelMixin]: #listmodelmixin
|
||||||
|
|
|
@ -59,8 +59,8 @@ methods necessary to check object permissions.
|
||||||
|
|
||||||
If you wish to use the provided permission classes in order to check object
|
If you wish to use the provided permission classes in order to check object
|
||||||
permissions, **you must** subclass them and implement the
|
permissions, **you must** subclass them and implement the
|
||||||
`has_object_permission()` method described in the [_Custom
|
`has_object_permission()` method described in the [*Custom
|
||||||
permissions_](#custom-permissions) section (below).
|
permissions*](#custom-permissions) section (below).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -118,7 +118,7 @@ Or, if you're using the `@api_view` decorator with function based views.
|
||||||
}
|
}
|
||||||
return Response(content)
|
return Response(content)
|
||||||
|
|
||||||
__Note:__ when you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in the __settings.py__ file.
|
**Note:** when you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in the **settings.py** file.
|
||||||
|
|
||||||
Provided they inherit from `rest_framework.permissions.BasePermission`, permissions can be composed using standard Python bitwise operators. For example, `IsAuthenticatedOrReadOnly` could be written:
|
Provided they inherit from `rest_framework.permissions.BasePermission`, permissions can be composed using standard Python bitwise operators. For example, `IsAuthenticatedOrReadOnly` could be written:
|
||||||
|
|
||||||
|
@ -139,7 +139,7 @@ Provided they inherit from `rest_framework.permissions.BasePermission`, permissi
|
||||||
}
|
}
|
||||||
return Response(content)
|
return Response(content)
|
||||||
|
|
||||||
__Note:__ it supports & (and), | (or) and ~ (not).
|
**Note:** it supports & (and), | (or) and ~ (not).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -284,16 +284,62 @@ REST framework offers three different methods to customize access restrictions o
|
||||||
|
|
||||||
The following table lists the access restriction methods and the level of control they offer over which actions.
|
The following table lists the access restriction methods and the level of control they offer over which actions.
|
||||||
|
|
||||||
| | `queryset` | `permission_classes` | `serializer_class` |
|
<table border=1>
|
||||||
|------------------------------------|------------|----------------------|--------------------|
|
<tr>
|
||||||
| Action: list | global | global | object-level* |
|
<th></th>
|
||||||
| Action: create | no | global | object-level |
|
<th><code>queryset</code></th>
|
||||||
| Action: retrieve | global | object-level | object-level |
|
<th><code>permission_classes</code></th>
|
||||||
| Action: update | global | object-level | object-level |
|
<th><code>serializer_class</code></th>
|
||||||
| Action: partial_update | global | object-level | object-level |
|
</tr>
|
||||||
| Action: destroy | global | object-level | no |
|
<tr>
|
||||||
| Can reference action in decision | no** | yes | no** |
|
<td>Action: list</td>
|
||||||
| Can reference request in decision | no** | yes | yes |
|
<td>global</td>
|
||||||
|
<td>global</td>
|
||||||
|
<td>object-level*</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Action: create</td>
|
||||||
|
<td>no</td>
|
||||||
|
<td>global</td>
|
||||||
|
<td>object-level</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Action: retrieve</td>
|
||||||
|
<td>global</td>
|
||||||
|
<td>object-level</td>
|
||||||
|
<td>object-level</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Action: update</td>
|
||||||
|
<td>global</td>
|
||||||
|
<td>object-level</td>
|
||||||
|
<td>object-level</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Action: partial_update</td>
|
||||||
|
<td>global</td>
|
||||||
|
<td>object-level</td>
|
||||||
|
<td>object-level</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Action: destroy</td>
|
||||||
|
<td>global</td>
|
||||||
|
<td>object-level</td>
|
||||||
|
<td>no</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Can reference action in decision</td>
|
||||||
|
<td>no**</td>
|
||||||
|
<td>yes</td>
|
||||||
|
<td>no**</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Can reference request in decision</td>
|
||||||
|
<td>no**</td>
|
||||||
|
<td>yes</td>
|
||||||
|
<td>yes</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
\* A Serializer class should not raise PermissionDenied in a list action, or the entire list would not be returned. <br>
|
\* A Serializer class should not raise PermissionDenied in a list action, or the entire list would not be returned. <br>
|
||||||
\** The `get_*()` methods have access to the current view and can return different Serializer or QuerySet instances based on the request or action.
|
\** The `get_*()` methods have access to the current view and can return different Serializer or QuerySet instances based on the request or action.
|
||||||
|
@ -326,7 +372,7 @@ The [Django Rest Framework Roles][django-rest-framework-roles] package makes it
|
||||||
|
|
||||||
## Django REST Framework API Key
|
## Django REST Framework API Key
|
||||||
|
|
||||||
The [Django REST Framework API Key][djangorestframework-api-key] package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. _machines_) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.
|
The [Django REST Framework API Key][djangorestframework-api-key] package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. *machines*) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.
|
||||||
|
|
||||||
## Django Rest Framework Role Filters
|
## Django Rest Framework Role Filters
|
||||||
|
|
||||||
|
@ -336,7 +382,6 @@ The [Django Rest Framework Role Filters][django-rest-framework-role-filters] pac
|
||||||
|
|
||||||
The [Django Rest Framework PSQ][drf-psq] package is an extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.
|
The [Django Rest Framework PSQ][drf-psq] package is an extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.
|
||||||
|
|
||||||
|
|
||||||
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
|
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
|
||||||
[authentication]: authentication.md
|
[authentication]: authentication.md
|
||||||
[throttling]: throttling.md
|
[throttling]: throttling.md
|
||||||
|
@ -344,7 +389,6 @@ The [Django Rest Framework PSQ][drf-psq] package is an extension that gives supp
|
||||||
[contribauth]: https://docs.djangoproject.com/en/stable/topics/auth/customizing/#custom-permissions
|
[contribauth]: https://docs.djangoproject.com/en/stable/topics/auth/customizing/#custom-permissions
|
||||||
[objectpermissions]: https://docs.djangoproject.com/en/stable/topics/auth/customizing/#handling-object-permissions
|
[objectpermissions]: https://docs.djangoproject.com/en/stable/topics/auth/customizing/#handling-object-permissions
|
||||||
[guardian]: https://github.com/lukaszb/django-guardian
|
[guardian]: https://github.com/lukaszb/django-guardian
|
||||||
[filtering]: filtering.md
|
|
||||||
[composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions
|
[composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions
|
||||||
[rest-condition]: https://github.com/caxap/rest_condition
|
[rest-condition]: https://github.com/caxap/rest_condition
|
||||||
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
|
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
|
||||||
|
|
|
@ -17,10 +17,10 @@ Relational fields are used to represent model relationships. They can be applie
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Note:** REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of `select_related` and `prefetch_related` since it would be too much magic. A serializer with a field spanning an orm relation through its source attribute could require an additional database hit to fetch related objects from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer.
|
**Note:** REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of `select_related` and `prefetch_related` since it would be too much magic. A serializer with a field spanning an orm relation through its source attribute could require an additional database hit to fetch related objects from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched:
|
For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched:
|
||||||
|
|
||||||
class AlbumSerializer(serializers.ModelSerializer):
|
class AlbumSerializer(serializers.ModelSerializer):
|
||||||
|
@ -150,7 +150,6 @@ By default this field is read-write, although you can change this behavior using
|
||||||
* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
|
* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
|
||||||
* `pk_field` - Set to a field to control serialization/deserialization of the primary key's value. For example, `pk_field=UUIDField(format='hex')` would serialize a UUID primary key into its compact hex representation.
|
* `pk_field` - Set to a field to control serialization/deserialization of the primary key's value. For example, `pk_field=UUIDField(format='hex')` would serialize a UUID primary key into its compact hex representation.
|
||||||
|
|
||||||
|
|
||||||
## HyperlinkedRelatedField
|
## HyperlinkedRelatedField
|
||||||
|
|
||||||
`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink.
|
`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink.
|
||||||
|
@ -468,11 +467,11 @@ Generally we recommend a flat style for API representations where possible, but
|
||||||
|
|
||||||
## The `queryset` argument
|
## The `queryset` argument
|
||||||
|
|
||||||
The `queryset` argument is only ever required for *writable* relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance.
|
The `queryset` argument is only ever required for _writable_ relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance.
|
||||||
|
|
||||||
In version 2.x a serializer class could *sometimes* automatically determine the `queryset` argument *if* a `ModelSerializer` class was being used.
|
In version 2.x a serializer class could _sometimes_ automatically determine the `queryset` argument _if_ a `ModelSerializer` class was being used.
|
||||||
|
|
||||||
This behavior is now replaced with *always* using an explicit `queryset` argument for writable relational fields.
|
This behavior is now replaced with _always_ using an explicit `queryset` argument for writable relational fields.
|
||||||
|
|
||||||
Doing so reduces the amount of hidden 'magic' that `ModelSerializer` provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the `ModelSerializer` shortcut, or using fully explicit `Serializer` classes.
|
Doing so reduces the amount of hidden 'magic' that `ModelSerializer` provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the `ModelSerializer` shortcut, or using fully explicit `Serializer` classes.
|
||||||
|
|
||||||
|
@ -494,8 +493,8 @@ This behavior is intended to prevent a template from being unable to render in a
|
||||||
|
|
||||||
There are two keyword arguments you can use to control this behavior:
|
There are two keyword arguments you can use to control this behavior:
|
||||||
|
|
||||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`.
|
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`.
|
||||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||||
|
|
||||||
You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`.
|
You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`.
|
||||||
|
|
||||||
|
|
|
@ -107,9 +107,7 @@ The TemplateHTMLRenderer will create a `RequestContext`, using the `response.dat
|
||||||
|
|
||||||
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example:
|
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example:
|
||||||
|
|
||||||
```
|
|
||||||
response.data = {'results': response.data}
|
response.data = {'results': response.data}
|
||||||
```
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -210,7 +208,6 @@ Note that views that have nested or list serializers for their input won't work
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Account
|
model = Account
|
||||||
|
|
||||||
|
|
||||||
**.media_type**: `text/html`
|
**.media_type**: `text/html`
|
||||||
|
|
||||||
**.format**: `'admin'`
|
**.format**: `'admin'`
|
||||||
|
@ -527,7 +524,6 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
||||||
|
|
||||||
[Rest Framework Latex] provides a renderer that outputs PDFs using Laulatex. It is maintained by [Pebble (S/F Software)][mypebble].
|
[Rest Framework Latex] provides a renderer that outputs PDFs using Laulatex. It is maintained by [Pebble (S/F Software)][mypebble].
|
||||||
|
|
||||||
|
|
||||||
[cite]: https://docs.djangoproject.com/en/stable/ref/template-response/#the-rendering-process
|
[cite]: https://docs.djangoproject.com/en/stable/ref/template-response/#the-rendering-process
|
||||||
[conneg]: content-negotiation.md
|
[conneg]: content-negotiation.md
|
||||||
[html-and-forms]: ../topics/html-and-forms.md
|
[html-and-forms]: ../topics/html-and-forms.md
|
||||||
|
@ -551,8 +547,6 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
||||||
[wharton]: https://github.com/wharton
|
[wharton]: https://github.com/wharton
|
||||||
[drf-excel]: https://github.com/wharton/drf-excel
|
[drf-excel]: https://github.com/wharton/drf-excel
|
||||||
[vbabiy]: https://github.com/vbabiy
|
[vbabiy]: https://github.com/vbabiy
|
||||||
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
|
|
||||||
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
|
|
||||||
[yaml]: http://www.yaml.org/
|
[yaml]: http://www.yaml.org/
|
||||||
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
|
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
|
||||||
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
|
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
|
||||||
|
|
|
@ -133,7 +133,6 @@ As REST framework's `Request` extends Django's `HttpRequest`, all the other stan
|
||||||
|
|
||||||
Note that due to implementation reasons the `Request` class does not inherit from `HttpRequest` class, but instead extends the class using composition.
|
Note that due to implementation reasons the `Request` class does not inherit from `HttpRequest` class, but instead extends the class using composition.
|
||||||
|
|
||||||
|
|
||||||
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
|
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
|
||||||
[parsers documentation]: parsers.md
|
[parsers documentation]: parsers.md
|
||||||
[JSON data]: parsers.md#jsonparser
|
[JSON data]: parsers.md#jsonparser
|
||||||
|
|
|
@ -30,9 +30,9 @@ Has the same behavior as [`django.urls.reverse`][reverse], except that it return
|
||||||
|
|
||||||
You should **include the request as a keyword argument** to the function, for example:
|
You should **include the request as a keyword argument** to the function, for example:
|
||||||
|
|
||||||
|
from django.utils.timezone import now
|
||||||
from rest_framework.reverse import reverse
|
from rest_framework.reverse import reverse
|
||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
from django.utils.timezone import now
|
|
||||||
|
|
||||||
class APIRootView(APIView):
|
class APIRootView(APIView):
|
||||||
def get(self, request):
|
def get(self, request):
|
||||||
|
|
|
@ -149,15 +149,52 @@ The above example would now generate the following URL pattern:
|
||||||
This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@action` decorator.
|
This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@action` decorator.
|
||||||
|
|
||||||
<table border=1>
|
<table border=1>
|
||||||
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
|
<tr>
|
||||||
<tr><td rowspan=2>{prefix}/</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
|
<th>URL Style</th>
|
||||||
<tr><td>POST</td><td>create</td></tr>
|
<th>HTTP Method</th>
|
||||||
<tr><td>{prefix}/{url_path}/</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=False)` decorated method</td><td>{basename}-{url_name}</td></tr>
|
<th>Action</th>
|
||||||
<tr><td rowspan=4>{prefix}/{lookup}/</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
|
<th>URL Name</th>
|
||||||
<tr><td>PUT</td><td>update</td></tr>
|
</tr>
|
||||||
<tr><td>PATCH</td><td>partial_update</td></tr>
|
<tr>
|
||||||
<tr><td>DELETE</td><td>destroy</td></tr>
|
<td rowspan=2>{prefix}/</td>
|
||||||
<tr><td>{prefix}/{lookup}/{url_path}/</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=True)` decorated method</td><td>{basename}-{url_name}</td></tr>
|
<td>GET</td>
|
||||||
|
<td>list</td>
|
||||||
|
<td rowspan=2>{basename}-list</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>POST</td>
|
||||||
|
<td>create</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>{prefix}/{url_path}/</td>
|
||||||
|
<td>GET, or as specified by `methods` argument</td>
|
||||||
|
<td><code>@action(detail=False)</code> decorated method</td>
|
||||||
|
<td>{basename}-{url_name}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan=4>{prefix}/{lookup}/</td>
|
||||||
|
<td>GET</td>
|
||||||
|
<td>retrieve</td>
|
||||||
|
<td rowspan=4>{basename}-detail</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>PUT</td>
|
||||||
|
<td>update</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>PATCH</td>
|
||||||
|
<td>partial_update</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>DELETE</td>
|
||||||
|
<td>destroy</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>{prefix}/{lookup}/{url_path}/</td>
|
||||||
|
<td>GET, or as specified by `methods` argument</td>
|
||||||
|
<td><code>@action(detail=True)</code> decorated method</td>
|
||||||
|
<td>{basename}-{url_name}</td>
|
||||||
|
</tr>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
By default the URLs created by `SimpleRouter` are appended with a trailing slash.
|
By default the URLs created by `SimpleRouter` are appended with a trailing slash.
|
||||||
|
@ -178,16 +215,59 @@ The router will match lookup values containing any characters except slashes and
|
||||||
This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes.
|
This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes.
|
||||||
|
|
||||||
<table border=1>
|
<table border=1>
|
||||||
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
|
<tr>
|
||||||
<tr><td>[.format]</td><td>GET</td><td>automatically generated root view</td><td>api-root</td></tr></tr>
|
<th>URL Style</th>
|
||||||
<tr><td rowspan=2>{prefix}/[.format]</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
|
<th>HTTP Method</th>
|
||||||
<tr><td>POST</td><td>create</td></tr>
|
<th>Action</th>
|
||||||
<tr><td>{prefix}/{url_path}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=False)` decorated method</td><td>{basename}-{url_name}</td></tr>
|
<th>URL Name</th>
|
||||||
<tr><td rowspan=4>{prefix}/{lookup}/[.format]</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
|
</tr>
|
||||||
<tr><td>PUT</td><td>update</td></tr>
|
<tr>
|
||||||
<tr><td>PATCH</td><td>partial_update</td></tr>
|
<td>[.format]</td>
|
||||||
<tr><td>DELETE</td><td>destroy</td></tr>
|
<td>GET</td>
|
||||||
<tr><td>{prefix}/{lookup}/{url_path}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=True)` decorated method</td><td>{basename}-{url_name}</td></tr>
|
<td>automatically generated root view</td>
|
||||||
|
<td>api-root</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan=2>{prefix}/[.format]</td>
|
||||||
|
<td>GET</td>
|
||||||
|
<td>list</td>
|
||||||
|
<td rowspan=2>{basename}-list</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>POST</td>
|
||||||
|
<td>create</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>{prefix}/{url_path}/[.format]</td>
|
||||||
|
<td>GET, or as specified by `methods` argument</td>
|
||||||
|
<td><code>@action(detail=False)</code> decorated method</td>
|
||||||
|
<td>{basename}-{url_name}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan=4>{prefix}/{lookup}/[.format]</td>
|
||||||
|
<td>GET</td>
|
||||||
|
<td>retrieve</td>
|
||||||
|
<td rowspan=4>{basename}-detail</td>
|
||||||
|
</tr>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>PUT</td>
|
||||||
|
<td>update</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>PATCH</td>
|
||||||
|
<td>partial_update</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>DELETE</td>
|
||||||
|
<td>destroy</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>{prefix}/{lookup}/{url_path}/[.format]</td>
|
||||||
|
<td>GET, or as specified by `methods` argument</td>
|
||||||
|
<td><code>@action(detail=True)</code> decorated method</td>
|
||||||
|
<td>{basename}-{url_name}</td>
|
||||||
|
</tr>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
As with `SimpleRouter` the trailing slashes on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router.
|
As with `SimpleRouter` the trailing slashes on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router.
|
||||||
|
@ -293,10 +373,30 @@ Let's take a look at the routes our `CustomReadOnlyRouter` would generate for a
|
||||||
The following mappings would be generated...
|
The following mappings would be generated...
|
||||||
|
|
||||||
<table border=1>
|
<table border=1>
|
||||||
<tr><th>URL</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
|
<tr>
|
||||||
<tr><td>/users</td><td>GET</td><td>list</td><td>user-list</td></tr>
|
<th>URL</th>
|
||||||
<tr><td>/users/{username}</td><td>GET</td><td>retrieve</td><td>user-detail</td></tr>
|
<th>HTTP Method</th>
|
||||||
<tr><td>/users/{username}/group_names</td><td>GET</td><td>group_names</td><td>user-group-names</td></tr>
|
<th>Action</th>
|
||||||
|
<th>URL Name</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>/users</td>
|
||||||
|
<td>GET</td>
|
||||||
|
<td>list</td>
|
||||||
|
<td>user-list</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>/users/{username}</td>
|
||||||
|
<td>GET</td>
|
||||||
|
<td>retrieve</td>
|
||||||
|
<td>user-detail</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>/users/{username}/group_names</td>
|
||||||
|
<td>GET</td>
|
||||||
|
<td>group_names</td>
|
||||||
|
<td>user-group-names</td>
|
||||||
|
</tr>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
For another example of setting the `.routes` attribute, see the source code for the `SimpleRouter` class.
|
For another example of setting the `.routes` attribute, see the source code for the `SimpleRouter` class.
|
||||||
|
|
|
@ -48,9 +48,7 @@ The following sections explain more.
|
||||||
|
|
||||||
If your schema is static, you can use the `generateschema` management command:
|
If your schema is static, you can use the `generateschema` management command:
|
||||||
|
|
||||||
```bash
|
|
||||||
./manage.py generateschema --file openapi-schema.yml
|
./manage.py generateschema --file openapi-schema.yml
|
||||||
```
|
|
||||||
|
|
||||||
Once you've generated a schema in this way you can annotate it with any
|
Once you've generated a schema in this way you can annotate it with any
|
||||||
additional information that cannot be automatically inferred by the schema
|
additional information that cannot be automatically inferred by the schema
|
||||||
|
@ -69,7 +67,6 @@ To route a `SchemaView`, use the `get_schema_view()` helper.
|
||||||
|
|
||||||
In `urls.py`:
|
In `urls.py`:
|
||||||
|
|
||||||
```python
|
|
||||||
from rest_framework.schemas import get_schema_view
|
from rest_framework.schemas import get_schema_view
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
|
@ -84,7 +81,6 @@ urlpatterns = [
|
||||||
), name='openapi-schema'),
|
), name='openapi-schema'),
|
||||||
# ...
|
# ...
|
||||||
]
|
]
|
||||||
```
|
|
||||||
|
|
||||||
#### `get_schema_view()`
|
#### `get_schema_view()`
|
||||||
|
|
||||||
|
@ -134,14 +130,11 @@ The `get_schema_view()` helper takes the following keyword arguments:
|
||||||
* `renderer_classes`: May be used to pass the set of renderer classes that can
|
* `renderer_classes`: May be used to pass the set of renderer classes that can
|
||||||
be used to render the API root endpoint.
|
be used to render the API root endpoint.
|
||||||
|
|
||||||
|
|
||||||
## SchemaGenerator
|
## SchemaGenerator
|
||||||
|
|
||||||
**Schema-level customization**
|
**Schema-level customization**
|
||||||
|
|
||||||
```python
|
|
||||||
from rest_framework.schemas.openapi import SchemaGenerator
|
from rest_framework.schemas.openapi import SchemaGenerator
|
||||||
```
|
|
||||||
|
|
||||||
`SchemaGenerator` is a class that walks a list of routed URL patterns, requests
|
`SchemaGenerator` is a class that walks a list of routed URL patterns, requests
|
||||||
the schema for each view and collates the resulting OpenAPI schema.
|
the schema for each view and collates the resulting OpenAPI schema.
|
||||||
|
@ -179,21 +172,17 @@ This is a good point to override if you want to customize the generated
|
||||||
dictionary For example you might wish to add terms of service to the [top-level
|
dictionary For example you might wish to add terms of service to the [top-level
|
||||||
`info` object][info-object]:
|
`info` object][info-object]:
|
||||||
|
|
||||||
```
|
|
||||||
class TOSSchemaGenerator(SchemaGenerator):
|
class TOSSchemaGenerator(SchemaGenerator):
|
||||||
def get_schema(self, *args, **kwargs):
|
def get_schema(self, *args, **kwargs):
|
||||||
schema = super().get_schema(*args, **kwargs)
|
schema = super().get_schema(*args, **kwargs)
|
||||||
schema["info"]["termsOfService"] = "https://example.com/tos.html"
|
schema["info"]["termsOfService"] = "https://example.com/tos.html"
|
||||||
return schema
|
return schema
|
||||||
```
|
|
||||||
|
|
||||||
## AutoSchema
|
## AutoSchema
|
||||||
|
|
||||||
**Per-View Customization**
|
**Per-View Customization**
|
||||||
|
|
||||||
```python
|
|
||||||
from rest_framework.schemas.openapi import AutoSchema
|
from rest_framework.schemas.openapi import AutoSchema
|
||||||
```
|
|
||||||
|
|
||||||
By default, view introspection is performed by an `AutoSchema` instance
|
By default, view introspection is performed by an `AutoSchema` instance
|
||||||
accessible via the `schema` attribute on `APIView`.
|
accessible via the `schema` attribute on `APIView`.
|
||||||
|
@ -209,15 +198,13 @@ and path:
|
||||||
the endpoint, including path and query parameters for pagination, filtering,
|
the endpoint, including path and query parameters for pagination, filtering,
|
||||||
and so on.
|
and so on.
|
||||||
|
|
||||||
```python
|
|
||||||
components = auto_schema.get_components(...)
|
components = auto_schema.get_components(...)
|
||||||
operation = auto_schema.get_operation(...)
|
operation = auto_schema.get_operation(...)
|
||||||
```
|
|
||||||
|
|
||||||
In compiling the schema, `SchemaGenerator` calls `get_components()` and
|
In compiling the schema, `SchemaGenerator` calls `get_components()` and
|
||||||
`get_operation()` for each view, allowed method, and path.
|
`get_operation()` for each view, allowed method, and path.
|
||||||
|
|
||||||
----
|
---
|
||||||
|
|
||||||
**Note**: The automatic introspection of components, and many operation
|
**Note**: The automatic introspection of components, and many operation
|
||||||
parameters relies on the relevant attributes and methods of
|
parameters relies on the relevant attributes and methods of
|
||||||
|
@ -225,7 +212,7 @@ parameters relies on the relevant attributes and methods of
|
||||||
etc. For basic `APIView` subclasses, default introspection is essentially limited to
|
etc. For basic `APIView` subclasses, default introspection is essentially limited to
|
||||||
the URL kwarg path parameters for this reason.
|
the URL kwarg path parameters for this reason.
|
||||||
|
|
||||||
----
|
---
|
||||||
|
|
||||||
`AutoSchema` encapsulates the view introspection needed for schema generation.
|
`AutoSchema` encapsulates the view introspection needed for schema generation.
|
||||||
Because of this all the schema generation logic is kept in a single place,
|
Because of this all the schema generation logic is kept in a single place,
|
||||||
|
@ -236,7 +223,6 @@ Keeping with this pattern, try not to let schema logic leak into your own
|
||||||
views, serializers, or fields when customizing the schema generation. You might
|
views, serializers, or fields when customizing the schema generation. You might
|
||||||
be tempted to do something like this:
|
be tempted to do something like this:
|
||||||
|
|
||||||
```python
|
|
||||||
class CustomSchema(AutoSchema):
|
class CustomSchema(AutoSchema):
|
||||||
"""
|
"""
|
||||||
AutoSchema subclass using schema_extra_info on the view.
|
AutoSchema subclass using schema_extra_info on the view.
|
||||||
|
@ -246,7 +232,6 @@ class CustomSchema(AutoSchema):
|
||||||
class CustomView(APIView):
|
class CustomView(APIView):
|
||||||
schema = CustomSchema()
|
schema = CustomSchema()
|
||||||
schema_extra_info = ... some extra info ...
|
schema_extra_info = ... some extra info ...
|
||||||
```
|
|
||||||
|
|
||||||
Here, the `AutoSchema` subclass goes looking for `schema_extra_info` on the
|
Here, the `AutoSchema` subclass goes looking for `schema_extra_info` on the
|
||||||
view. This is _OK_ (it doesn't actually hurt) but it means you'll end up with
|
view. This is _OK_ (it doesn't actually hurt) but it means you'll end up with
|
||||||
|
@ -255,7 +240,6 @@ your schema logic spread out in a number of different places.
|
||||||
Instead try to subclass `AutoSchema` such that the `extra_info` doesn't leak
|
Instead try to subclass `AutoSchema` such that the `extra_info` doesn't leak
|
||||||
out into the view:
|
out into the view:
|
||||||
|
|
||||||
```python
|
|
||||||
class BaseSchema(AutoSchema):
|
class BaseSchema(AutoSchema):
|
||||||
"""
|
"""
|
||||||
AutoSchema subclass that knows how to use extra_info.
|
AutoSchema subclass that knows how to use extra_info.
|
||||||
|
@ -267,7 +251,6 @@ class CustomSchema(BaseSchema):
|
||||||
|
|
||||||
class CustomView(APIView):
|
class CustomView(APIView):
|
||||||
schema = CustomSchema()
|
schema = CustomSchema()
|
||||||
```
|
|
||||||
|
|
||||||
This style is slightly more verbose but maintains the encapsulation of the
|
This style is slightly more verbose but maintains the encapsulation of the
|
||||||
schema related code. It's more _cohesive_ in the _parlance_. It'll keep the
|
schema related code. It's more _cohesive_ in the _parlance_. It'll keep the
|
||||||
|
@ -277,7 +260,6 @@ If an option applies to many view classes, rather than creating a specific
|
||||||
subclass per-view, you may find it more convenient to allow specifying the
|
subclass per-view, you may find it more convenient to allow specifying the
|
||||||
option as an `__init__()` kwarg to your base `AutoSchema` subclass:
|
option as an `__init__()` kwarg to your base `AutoSchema` subclass:
|
||||||
|
|
||||||
```python
|
|
||||||
class CustomSchema(BaseSchema):
|
class CustomSchema(BaseSchema):
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
# store extra_info for later
|
# store extra_info for later
|
||||||
|
@ -288,7 +270,6 @@ class CustomView(APIView):
|
||||||
schema = CustomSchema(
|
schema = CustomSchema(
|
||||||
extra_info=... some extra info ...
|
extra_info=... some extra info ...
|
||||||
)
|
)
|
||||||
```
|
|
||||||
|
|
||||||
This saves you having to create a custom subclass per-view for a commonly used option.
|
This saves you having to create a custom subclass per-view for a commonly used option.
|
||||||
|
|
||||||
|
@ -317,7 +298,6 @@ You may see warnings if your API has duplicate component names. If so you can ov
|
||||||
|
|
||||||
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
|
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
|
||||||
|
|
||||||
|
|
||||||
#### `map_serializer()`
|
#### `map_serializer()`
|
||||||
|
|
||||||
Maps serializers to their OpenAPI representations.
|
Maps serializers to their OpenAPI representations.
|
||||||
|
@ -333,7 +313,6 @@ will handle the default fields that Django REST Framework provides.
|
||||||
|
|
||||||
For `SerializerMethodField` instances, for which the schema is unknown, or custom field subclasses you should override `map_field()` to generate the correct schema:
|
For `SerializerMethodField` instances, for which the schema is unknown, or custom field subclasses you should override `map_field()` to generate the correct schema:
|
||||||
|
|
||||||
```python
|
|
||||||
class CustomSchema(AutoSchema):
|
class CustomSchema(AutoSchema):
|
||||||
"""Extension of ``AutoSchema`` to add support for custom field schemas."""
|
"""Extension of ``AutoSchema`` to add support for custom field schemas."""
|
||||||
|
|
||||||
|
@ -341,7 +320,6 @@ class CustomSchema(AutoSchema):
|
||||||
# Handle SerializerMethodFields or custom fields here...
|
# Handle SerializerMethodFields or custom fields here...
|
||||||
# ...
|
# ...
|
||||||
return super().map_field(field)
|
return super().map_field(field)
|
||||||
```
|
|
||||||
|
|
||||||
Authors of third-party packages should aim to provide an `AutoSchema` subclass,
|
Authors of third-party packages should aim to provide an `AutoSchema` subclass,
|
||||||
and a mixin, overriding `map_field()` so that users can easily generate schemas
|
and a mixin, overriding `map_field()` so that users can easily generate schemas
|
||||||
|
@ -407,7 +385,6 @@ The available kwargs are:
|
||||||
|
|
||||||
You pass the kwargs when declaring the `AutoSchema` instance on your view:
|
You pass the kwargs when declaring the `AutoSchema` instance on your view:
|
||||||
|
|
||||||
```
|
|
||||||
class PetDetailView(generics.RetrieveUpdateDestroyAPIView):
|
class PetDetailView(generics.RetrieveUpdateDestroyAPIView):
|
||||||
schema = AutoSchema(
|
schema = AutoSchema(
|
||||||
tags=['Pets'],
|
tags=['Pets'],
|
||||||
|
@ -415,7 +392,6 @@ class PetDetailView(generics.RetrieveUpdateDestroyAPIView):
|
||||||
operation_id_base='Pet',
|
operation_id_base='Pet',
|
||||||
)
|
)
|
||||||
...
|
...
|
||||||
```
|
|
||||||
|
|
||||||
Assuming a `Pet` model and `PetSerializer` serializer, the kwargs in this
|
Assuming a `Pet` model and `PetSerializer` serializer, the kwargs in this
|
||||||
example are probably not needed. Often, though, you'll need to pass the kwargs
|
example are probably not needed. Often, though, you'll need to pass the kwargs
|
||||||
|
@ -428,12 +404,6 @@ create a base `AutoSchema` subclass for your project that takes additional
|
||||||
|
|
||||||
[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api
|
[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api
|
||||||
[openapi]: https://github.com/OAI/OpenAPI-Specification
|
[openapi]: https://github.com/OAI/OpenAPI-Specification
|
||||||
[openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions
|
|
||||||
[openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject
|
[openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject
|
||||||
[openapi-tags]: https://swagger.io/specification/#tagObject
|
|
||||||
[openapi-operationid]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#fixed-fields-17
|
|
||||||
[openapi-components]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#componentsObject
|
[openapi-components]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#componentsObject
|
||||||
[openapi-reference]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#referenceObject
|
|
||||||
[openapi-generator]: https://github.com/OpenAPITools/openapi-generator
|
|
||||||
[swagger-codegen]: https://github.com/swagger-api/swagger-codegen
|
|
||||||
[info-object]: https://swagger.io/specification/#infoObject
|
[info-object]: https://swagger.io/specification/#infoObject
|
||||||
|
|
|
@ -556,7 +556,6 @@ Please review the [Validators Documentation](/api-guide/validators/) for details
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
||||||
## Additional keyword arguments
|
## Additional keyword arguments
|
||||||
|
|
||||||
There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the `extra_kwargs` option. As in the case of `read_only_fields`, this means you do not need to explicitly declare the field on the serializer.
|
There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the `extra_kwargs` option. As in the case of `read_only_fields`, this means you do not need to explicitly declare the field on the serializer.
|
||||||
|
@ -1191,7 +1190,6 @@ The [drf-writable-nested][drf-writable-nested] package provides writable nested
|
||||||
|
|
||||||
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
|
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
|
||||||
|
|
||||||
|
|
||||||
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
|
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
|
||||||
[relations]: relations.md
|
[relations]: relations.md
|
||||||
[model-managers]: https://docs.djangoproject.com/en/stable/topics/db/managers/
|
[model-managers]: https://docs.djangoproject.com/en/stable/topics/db/managers/
|
||||||
|
|
|
@ -31,7 +31,6 @@ The module also includes a set of helper functions for testing if a status code
|
||||||
response = self.client.get(url)
|
response = self.client.get(url)
|
||||||
self.assertTrue(status.is_success(response.status_code))
|
self.assertTrue(status.is_success(response.status_code))
|
||||||
|
|
||||||
|
|
||||||
For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616]
|
For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616]
|
||||||
and [RFC 6585][rfc6585].
|
and [RFC 6585][rfc6585].
|
||||||
|
|
||||||
|
|
|
@ -13,7 +13,7 @@ Most of the time you're dealing with validation in REST framework you'll simply
|
||||||
|
|
||||||
However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.
|
However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.
|
||||||
|
|
||||||
## Validation in REST framework
|
## Validation in REST framework
|
||||||
|
|
||||||
Validation in Django REST framework serializers is handled a little differently to how validation works in Django's `ModelForm` class.
|
Validation in Django REST framework serializers is handled a little differently to how validation works in Django's `ModelForm` class.
|
||||||
|
|
||||||
|
@ -75,7 +75,7 @@ This validator should be applied to *serializer fields*, like so:
|
||||||
validators=[UniqueValidator(queryset=BlogPost.objects.all())]
|
validators=[UniqueValidator(queryset=BlogPost.objects.all())]
|
||||||
)
|
)
|
||||||
|
|
||||||
## UniqueTogetherValidator
|
## UniqueTogetherValidator
|
||||||
|
|
||||||
This validator can be used to enforce `unique_together` constraints on model instances.
|
This validator can be used to enforce `unique_together` constraints on model instances.
|
||||||
It has two required arguments, and a single optional `messages` argument:
|
It has two required arguments, and a single optional `messages` argument:
|
||||||
|
@ -183,7 +183,7 @@ A default class that can be used to represent the current user. In order to use
|
||||||
default=serializers.CurrentUserDefault()
|
default=serializers.CurrentUserDefault()
|
||||||
)
|
)
|
||||||
|
|
||||||
#### CreateOnlyDefault
|
#### CreateOnlyDefault
|
||||||
|
|
||||||
A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted.
|
A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted.
|
||||||
|
|
||||||
|
|
|
@ -94,7 +94,7 @@ You can also set your versioning class plus those three values on a per-view or
|
||||||
|
|
||||||
# API Reference
|
# API Reference
|
||||||
|
|
||||||
## AcceptHeaderVersioning
|
## AcceptHeaderVersioning
|
||||||
|
|
||||||
This scheme requires the client to specify the version as part of the media type in the `Accept` header. The version is included as a media type parameter, that supplements the main media type.
|
This scheme requires the client to specify the version as part of the media type in the `Accept` header. The version is included as a media type parameter, that supplements the main media type.
|
||||||
|
|
||||||
|
|
|
@ -51,7 +51,6 @@ For example:
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
||||||
## API policy attributes
|
## API policy attributes
|
||||||
|
|
||||||
The following attributes control the pluggable aspects of API views.
|
The following attributes control the pluggable aspects of API views.
|
||||||
|
@ -161,7 +160,6 @@ By default only `GET` methods will be accepted. Other methods will respond with
|
||||||
return Response({"message": "Got some data!", "data": request.data})
|
return Response({"message": "Got some data!", "data": request.data})
|
||||||
return Response({"message": "Hello, world!"})
|
return Response({"message": "Hello, world!"})
|
||||||
|
|
||||||
|
|
||||||
## API policy decorators
|
## API policy decorators
|
||||||
|
|
||||||
To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle][throttling] to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
|
To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle][throttling] to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
|
||||||
|
@ -189,7 +187,6 @@ The available decorators are:
|
||||||
|
|
||||||
Each of these decorators takes a single argument which must be a list or tuple of classes.
|
Each of these decorators takes a single argument which must be a list or tuple of classes.
|
||||||
|
|
||||||
|
|
||||||
## View schema decorator
|
## View schema decorator
|
||||||
|
|
||||||
To override the default schema generation for function based views you may use
|
To override the default schema generation for function based views you may use
|
||||||
|
@ -217,11 +214,9 @@ You may pass `None` in order to exclude the view from schema generation.
|
||||||
def view(request):
|
def view(request):
|
||||||
return Response({"message": "Will not appear in schema!"})
|
return Response({"message": "Will not appear in schema!"})
|
||||||
|
|
||||||
|
|
||||||
[cite]: https://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
|
[cite]: https://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
|
||||||
[cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html
|
[cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html
|
||||||
[settings]: settings.md
|
[settings]: settings.md
|
||||||
[throttling]: throttling.md
|
[throttling]: throttling.md
|
||||||
[schemas]: schemas.md
|
[schemas]: schemas.md
|
||||||
[classy-drf]: http://www.cdrf.co
|
[classy-drf]: http://www.cdrf.co
|
||||||
|
|
||||||
|
|
|
@ -9,7 +9,6 @@ source:
|
||||||
>
|
>
|
||||||
> — [Ruby on Rails Documentation][cite]
|
> — [Ruby on Rails Documentation][cite]
|
||||||
|
|
||||||
|
|
||||||
Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
|
Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
|
||||||
|
|
||||||
A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`.
|
A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`.
|
||||||
|
@ -73,7 +72,6 @@ There are two main advantages of using a `ViewSet` class over using a `View` cla
|
||||||
|
|
||||||
Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.
|
Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.
|
||||||
|
|
||||||
|
|
||||||
## ViewSet actions
|
## ViewSet actions
|
||||||
|
|
||||||
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:
|
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:
|
||||||
|
@ -171,14 +169,12 @@ A more complete example of extra actions:
|
||||||
serializer = self.get_serializer(recent_users, many=True)
|
serializer = self.get_serializer(recent_users, many=True)
|
||||||
return Response(serializer.data)
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
|
||||||
The `action` decorator will route `GET` requests by default, but may also accept other HTTP methods by setting the `methods` argument. For example:
|
The `action` decorator will route `GET` requests by default, but may also accept other HTTP methods by setting the `methods` argument. For example:
|
||||||
|
|
||||||
@action(detail=True, methods=['post', 'delete'])
|
@action(detail=True, methods=['post', 'delete'])
|
||||||
def unset_password(self, request, pk=None):
|
def unset_password(self, request, pk=None):
|
||||||
...
|
...
|
||||||
|
|
||||||
|
|
||||||
The decorator allows you to override any viewset-level configuration such as `permission_classes`, `serializer_class`, `filter_backends`...:
|
The decorator allows you to override any viewset-level configuration such as `permission_classes`, `serializer_class`, `filter_backends`...:
|
||||||
|
|
||||||
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])
|
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])
|
||||||
|
@ -193,7 +189,6 @@ To view all extra actions, call the `.get_extra_actions()` method.
|
||||||
|
|
||||||
Extra actions can map additional HTTP methods to separate `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.
|
Extra actions can map additional HTTP methods to separate `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')
|
@action(detail=True, methods=['put'], name='Change Password')
|
||||||
def password(self, request, pk=None):
|
def password(self, request, pk=None):
|
||||||
"""Update the user's password."""
|
"""Update the user's password."""
|
||||||
|
@ -203,7 +198,6 @@ Extra actions can map additional HTTP methods to separate `ViewSet` methods. For
|
||||||
def delete_password(self, request, pk=None):
|
def delete_password(self, request, pk=None):
|
||||||
"""Delete the user's password."""
|
"""Delete the user's password."""
|
||||||
...
|
...
|
||||||
```
|
|
||||||
|
|
||||||
## Reversing action URLs
|
## Reversing action URLs
|
||||||
|
|
||||||
|
@ -213,17 +207,13 @@ Note that the `basename` is provided by the router during `ViewSet` registration
|
||||||
|
|
||||||
Using the example from the previous section:
|
Using the example from the previous section:
|
||||||
|
|
||||||
```python
|
|
||||||
>>> view.reverse_action('set-password', args=['1'])
|
>>> view.reverse_action('set-password', args=['1'])
|
||||||
'http://localhost:8000/api/users/1/set_password'
|
'http://localhost:8000/api/users/1/set_password'
|
||||||
```
|
|
||||||
|
|
||||||
Alternatively, you can use the `url_name` attribute set by the `@action` decorator.
|
Alternatively, you can use the `url_name` attribute set by the `@action` decorator.
|
||||||
|
|
||||||
```python
|
|
||||||
>>> view.reverse_action(view.set_password.url_name, args=['1'])
|
>>> view.reverse_action(view.set_password.url_name, args=['1'])
|
||||||
'http://localhost:8000/api/users/1/set_password'
|
'http://localhost:8000/api/users/1/set_password'
|
||||||
```
|
|
||||||
|
|
||||||
The `url_name` argument for `.reverse_action()` should match the same argument to the `@action` decorator. Additionally, this method can be used to reverse the default actions, such as `list` and `create`.
|
The `url_name` argument for `.reverse_action()` should match the same argument to the `@action` decorator. Additionally, this method can be used to reverse the default actions, such as `list` and `create`.
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user