mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-27 00:19:53 +03:00
Merge branch 'encode:master' into fix_instance_check
This commit is contained in:
commit
c9b6b020ec
1
.github/workflows/main.yml
vendored
1
.github/workflows/main.yml
vendored
|
@ -19,6 +19,7 @@ jobs:
|
||||||
- '3.8'
|
- '3.8'
|
||||||
- '3.9'
|
- '3.9'
|
||||||
- '3.10'
|
- '3.10'
|
||||||
|
- '3.11'
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
|
|
|
@ -54,8 +54,8 @@ There is a live example API for testing purposes, [available here][sandbox].
|
||||||
|
|
||||||
# Requirements
|
# Requirements
|
||||||
|
|
||||||
* Python (3.6, 3.7, 3.8, 3.9, 3.10)
|
* Python 3.6+
|
||||||
* Django (2.2, 3.0, 3.1, 3.2, 4.0, 4.1)
|
* Django 4.1, 4.0, 3.2, 3.1, 3.0
|
||||||
|
|
||||||
We **highly recommend** and only officially support the latest patch release of
|
We **highly recommend** and only officially support the latest patch release of
|
||||||
each Python and Django series.
|
each Python and Django series.
|
||||||
|
|
|
@ -173,9 +173,9 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
#### Generating Tokens
|
### Generating Tokens
|
||||||
|
|
||||||
##### By using signals
|
#### By using signals
|
||||||
|
|
||||||
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
|
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
|
||||||
|
|
||||||
|
@ -199,9 +199,9 @@ If you've already created some users, you can generate tokens for all existing u
|
||||||
for user in User.objects.all():
|
for user in User.objects.all():
|
||||||
Token.objects.get_or_create(user=user)
|
Token.objects.get_or_create(user=user)
|
||||||
|
|
||||||
##### By exposing an api endpoint
|
#### By exposing an api endpoint
|
||||||
|
|
||||||
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behaviour. To use it, add the `obtain_auth_token` view to your URLconf:
|
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
|
||||||
|
|
||||||
from rest_framework.authtoken import views
|
from rest_framework.authtoken import views
|
||||||
urlpatterns += [
|
urlpatterns += [
|
||||||
|
@ -216,7 +216,7 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
|
||||||
|
|
||||||
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.
|
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.
|
||||||
|
|
||||||
By default, there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply to throttle you'll need to override the view class,
|
By default, there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
|
||||||
and include them using the `throttle_classes` attribute.
|
and include them using the `throttle_classes` attribute.
|
||||||
|
|
||||||
If you need a customized version of the `obtain_auth_token` view, you can do so by subclassing the `ObtainAuthToken` view class, and using that in your url conf instead.
|
If you need a customized version of the `obtain_auth_token` view, you can do so by subclassing the `ObtainAuthToken` view class, and using that in your url conf instead.
|
||||||
|
@ -248,9 +248,9 @@ And in your `urls.py`:
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
##### 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 to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
||||||
|
|
||||||
`your_app/admin.py`:
|
`your_app/admin.py`:
|
||||||
|
|
||||||
|
@ -289,7 +289,7 @@ If you're using an AJAX-style API with SessionAuthentication, you'll need to mak
|
||||||
|
|
||||||
**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
|
**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
|
||||||
|
|
||||||
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 behavior is not suitable for login views, which should always have CSRF validation applied.
|
||||||
|
|
||||||
|
|
||||||
## RemoteUserAuthentication
|
## RemoteUserAuthentication
|
||||||
|
@ -299,7 +299,7 @@ environment variable.
|
||||||
|
|
||||||
To use it, you must have `django.contrib.auth.backends.RemoteUserBackend` (or a subclass) in your
|
To use it, you must have `django.contrib.auth.backends.RemoteUserBackend` (or a subclass) in your
|
||||||
`AUTHENTICATION_BACKENDS` setting. By default, `RemoteUserBackend` creates `User` objects for usernames that don't
|
`AUTHENTICATION_BACKENDS` setting. By default, `RemoteUserBackend` creates `User` objects for usernames that don't
|
||||||
already exist. To change this and other behaviour, consult the
|
already exist. To change this and other behavior, consult the
|
||||||
[Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/).
|
[Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/).
|
||||||
|
|
||||||
If successfully authenticated, `RemoteUserAuthentication` provides the following credentials:
|
If successfully authenticated, `RemoteUserAuthentication` provides the following credentials:
|
||||||
|
@ -307,7 +307,7 @@ If successfully authenticated, `RemoteUserAuthentication` provides the following
|
||||||
* `request.user` will be a Django `User` instance.
|
* `request.user` will be a Django `User` instance.
|
||||||
* `request.auth` will be `None`.
|
* `request.auth` will be `None`.
|
||||||
|
|
||||||
Consult your web server's documentation for information about configuring an authentication method, e.g.:
|
Consult your web server's documentation for information about configuring an authentication method, for example:
|
||||||
|
|
||||||
* [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/)
|
||||||
|
@ -338,7 +338,7 @@ If the `.authenticate_header()` method is not overridden, the authentication sch
|
||||||
|
|
||||||
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'.
|
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'.
|
||||||
|
|
||||||
from django.contrib.auth.models import User
|
from django.contrib.auth.models import User
|
||||||
from rest_framework import authentication
|
from rest_framework import authentication
|
||||||
from rest_framework import exceptions
|
from rest_framework import exceptions
|
||||||
|
|
||||||
|
@ -369,7 +369,7 @@ The following third-party packages are also available.
|
||||||
|
|
||||||
The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by [jazzband][jazzband] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
|
The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by [jazzband][jazzband] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
|
||||||
|
|
||||||
#### Installation & configuration
|
### Installation & configuration
|
||||||
|
|
||||||
Install using `pip`.
|
Install using `pip`.
|
||||||
|
|
||||||
|
@ -396,7 +396,7 @@ The [Django REST framework OAuth][django-rest-framework-oauth] package provides
|
||||||
|
|
||||||
This package was previously included directly in the REST framework but is now supported and maintained as a third-party package.
|
This package was previously included directly in the REST framework but is now supported and maintained as a third-party package.
|
||||||
|
|
||||||
#### Installation & configuration
|
### Installation & configuration
|
||||||
|
|
||||||
Install the package using `pip`.
|
Install the package using `pip`.
|
||||||
|
|
||||||
|
@ -418,7 +418,7 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
|
||||||
|
|
||||||
## Djoser
|
## Djoser
|
||||||
|
|
||||||
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is ready to use REST implementation of the Django authentication system.
|
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.
|
||||||
|
|
||||||
## django-rest-auth / dj-rest-auth
|
## django-rest-auth / dj-rest-auth
|
||||||
|
|
||||||
|
|
|
@ -82,7 +82,7 @@ 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 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
|
||||||
|
|
||||||
|
|
|
@ -46,7 +46,7 @@ Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-f
|
||||||
|
|
||||||
### `default`
|
### `default`
|
||||||
|
|
||||||
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
|
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.
|
||||||
|
|
||||||
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
|
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
|
||||||
|
|
||||||
|
@ -85,7 +85,7 @@ When serializing fields with dotted notation, it may be necessary to provide a `
|
||||||
class CommentSerializer(serializers.Serializer):
|
class CommentSerializer(serializers.Serializer):
|
||||||
email = serializers.EmailField(source="user.email")
|
email = serializers.EmailField(source="user.email")
|
||||||
|
|
||||||
would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related].
|
This case would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related].
|
||||||
|
|
||||||
The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
|
The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
|
||||||
|
|
||||||
|
@ -151,7 +151,7 @@ Prior to Django 2.1 `models.BooleanField` fields were always `blank=True`. Thus
|
||||||
since Django 2.1 default `serializers.BooleanField` instances will be generated
|
since Django 2.1 default `serializers.BooleanField` instances will be generated
|
||||||
without the `required` kwarg (i.e. equivalent to `required=True`) whereas with
|
without the `required` kwarg (i.e. equivalent to `required=True`) whereas with
|
||||||
previous versions of Django, default `BooleanField` instances will be generated
|
previous versions of Django, default `BooleanField` instances will be generated
|
||||||
with a `required=False` option. If you want to control this behaviour manually,
|
with a `required=False` option. If you want to control this behavior manually,
|
||||||
explicitly declare the `BooleanField` on the serializer class, or use the
|
explicitly declare the `BooleanField` on the serializer class, or use the
|
||||||
`extra_kwargs` option to set the `required` flag.
|
`extra_kwargs` option to set the `required` flag.
|
||||||
|
|
||||||
|
@ -159,14 +159,6 @@ Corresponds to `django.db.models.fields.BooleanField`.
|
||||||
|
|
||||||
**Signature:** `BooleanField()`
|
**Signature:** `BooleanField()`
|
||||||
|
|
||||||
## NullBooleanField
|
|
||||||
|
|
||||||
A boolean representation that also accepts `None` as a valid value.
|
|
||||||
|
|
||||||
Corresponds to `django.db.models.fields.NullBooleanField`.
|
|
||||||
|
|
||||||
**Signature:** `NullBooleanField()`
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
# String fields
|
# String fields
|
||||||
|
@ -179,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.
|
||||||
|
|
||||||
|
@ -230,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
|
||||||
|
@ -245,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
|
||||||
|
|
||||||
|
@ -259,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'.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -274,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
|
||||||
|
|
||||||
|
@ -285,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
|
||||||
|
|
||||||
|
@ -296,13 +288,14 @@ 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`.
|
||||||
|
* `normalize_output` Will normalize the decimal value when serialized. This will strip all trailing zeroes and change the value's precision to the minimum required precision to be able to represent the value without loosing data. Defaults to `False`.
|
||||||
|
|
||||||
#### Example usage
|
#### Example usage
|
||||||
|
|
||||||
|
@ -314,10 +307,6 @@ And to validate numbers up to anything less than one billion with a resolution o
|
||||||
|
|
||||||
serializers.DecimalField(max_digits=19, decimal_places=10)
|
serializers.DecimalField(max_digits=19, decimal_places=10)
|
||||||
|
|
||||||
This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer.
|
|
||||||
|
|
||||||
If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
# Date and time fields
|
# Date and time fields
|
||||||
|
@ -392,8 +381,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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -407,10 +396,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.
|
||||||
|
|
||||||
|
@ -420,10 +409,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.
|
||||||
|
|
||||||
|
@ -444,9 +433,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
|
||||||
|
|
||||||
|
@ -456,9 +445,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.
|
||||||
|
|
||||||
|
@ -472,10 +461,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:
|
||||||
|
|
||||||
|
@ -496,8 +485,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:
|
||||||
|
|
||||||
|
@ -514,8 +503,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.
|
||||||
|
|
||||||
|
@ -525,8 +514,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`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -577,7 +566,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:
|
||||||
|
|
||||||
|
@ -783,7 +772,7 @@ Here the mapping between the target and source attribute pairs (`x` and
|
||||||
`x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField`
|
`x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField`
|
||||||
declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`.
|
declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`.
|
||||||
|
|
||||||
Our new `DataPointSerializer` exhibits the same behaviour as the custom field
|
Our new `DataPointSerializer` exhibits the same behavior as the custom field
|
||||||
approach.
|
approach.
|
||||||
|
|
||||||
Serializing:
|
Serializing:
|
||||||
|
@ -843,7 +832,7 @@ the [djangorestframework-recursive][djangorestframework-recursive] package provi
|
||||||
|
|
||||||
## django-rest-framework-gis
|
## django-rest-framework-gis
|
||||||
|
|
||||||
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
|
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
|
||||||
|
|
||||||
## django-rest-framework-hstore
|
## django-rest-framework-hstore
|
||||||
|
|
||||||
|
|
|
@ -23,8 +23,8 @@ Returns a URL pattern list which includes format suffix patterns appended to eac
|
||||||
Arguments:
|
Arguments:
|
||||||
|
|
||||||
* **urlpatterns**: Required. A URL pattern list.
|
* **urlpatterns**: Required. A URL pattern list.
|
||||||
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
|
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
|
||||||
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
|
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
|
|
|
@ -98,7 +98,7 @@ For example:
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Note:** If the serializer_class used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related].
|
**Note:** If the `serializer_class` used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related].
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
@ -227,7 +227,7 @@ Note that the `paginate_queryset` method may set state on the pagination instanc
|
||||||
|
|
||||||
## Example
|
## Example
|
||||||
|
|
||||||
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
|
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
|
||||||
|
|
||||||
class CustomPagination(pagination.PageNumberPagination):
|
class CustomPagination(pagination.PageNumberPagination):
|
||||||
def get_paginated_response(self, data):
|
def get_paginated_response(self, data):
|
||||||
|
|
|
@ -15,7 +15,7 @@ REST framework includes a number of built in Parser classes, that allow you to a
|
||||||
|
|
||||||
## How the parser is determined
|
## How the parser is determined
|
||||||
|
|
||||||
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
|
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -87,7 +87,7 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
|
||||||
|
|
||||||
## MultiPartParser
|
## MultiPartParser
|
||||||
|
|
||||||
Parses multipart HTML form content, which supports file uploads. Both `request.data` will be populated with a `QueryDict`.
|
Parses multipart HTML form content, which supports file uploads. `request.data` and `request.FILES` will be populated with a `QueryDict` and `MultiValueDict` respectively.
|
||||||
|
|
||||||
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
|
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
|
||||||
|
|
||||||
|
|
|
@ -177,7 +177,7 @@ This permission class ties into Django's standard `django.contrib.auth` [model p
|
||||||
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
|
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
|
||||||
* `DELETE` requests require the user to have the `delete` permission on the model.
|
* `DELETE` requests require the user to have the `delete` permission on the model.
|
||||||
|
|
||||||
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
|
The default behavior can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
|
||||||
|
|
||||||
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
|
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
|
||||||
|
|
||||||
|
@ -324,6 +324,10 @@ The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to
|
||||||
|
|
||||||
The [Django Rest Framework Roles][django-rest-framework-roles] package makes it easier to parameterize your API over multiple types of users.
|
The [Django Rest Framework Roles][django-rest-framework-roles] package makes it easier to parameterize your API over multiple types of users.
|
||||||
|
|
||||||
|
## Rest Framework Roles
|
||||||
|
|
||||||
|
The [Rest Framework Roles][rest-framework-roles] makes it super easy to protect views based on roles. Most importantly allows you to decouple accessibility logic from models and views in a clean human-readable way.
|
||||||
|
|
||||||
## 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.
|
||||||
|
@ -349,6 +353,7 @@ The [Django Rest Framework PSQ][drf-psq] package is an extension that gives supp
|
||||||
[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
|
||||||
[django-rest-framework-roles]: https://github.com/computer-lab/django-rest-framework-roles
|
[django-rest-framework-roles]: https://github.com/computer-lab/django-rest-framework-roles
|
||||||
|
[rest-framework-roles]: https://github.com/Pithikos/rest-framework-roles
|
||||||
[djangorestframework-api-key]: https://florimondmanca.github.io/djangorestframework-api-key/
|
[djangorestframework-api-key]: https://florimondmanca.github.io/djangorestframework-api-key/
|
||||||
[django-rest-framework-role-filters]: https://github.com/allisson/django-rest-framework-role-filters
|
[django-rest-framework-role-filters]: https://github.com/allisson/django-rest-framework-role-filters
|
||||||
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
|
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
|
||||||
|
|
|
@ -246,7 +246,7 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e
|
||||||
|
|
||||||
## HyperlinkedIdentityField
|
## HyperlinkedIdentityField
|
||||||
|
|
||||||
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
|
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
|
||||||
|
|
||||||
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
|
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
|
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
|
||||||
|
@ -494,8 +494,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`.
|
||||||
|
|
||||||
|
|
|
@ -105,7 +105,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}
|
||||||
|
@ -192,7 +192,7 @@ By default the response content will be rendered with the highest priority rende
|
||||||
def get_default_renderer(self, view):
|
def get_default_renderer(self, view):
|
||||||
return JSONRenderer()
|
return JSONRenderer()
|
||||||
|
|
||||||
## AdminRenderer
|
## AdminRenderer
|
||||||
|
|
||||||
Renders data into HTML for an admin-like display:
|
Renders data into HTML for an admin-like display:
|
||||||
|
|
||||||
|
@ -332,7 +332,7 @@ You can do some pretty flexible things using REST framework's renderers. Some e
|
||||||
* Specify multiple types of HTML representation for API clients to use.
|
* Specify multiple types of HTML representation for API clients to use.
|
||||||
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
|
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
|
||||||
|
|
||||||
## Varying behaviour by media type
|
## Varying behavior by media type
|
||||||
|
|
||||||
In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
|
In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
|
||||||
|
|
||||||
|
|
|
@ -49,7 +49,7 @@ If a client sends a request with a content-type that cannot be parsed then a `Un
|
||||||
|
|
||||||
# Content negotiation
|
# Content negotiation
|
||||||
|
|
||||||
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialization schemes for different media types.
|
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behavior such as selecting a different serialization schemes for different media types.
|
||||||
|
|
||||||
## .accepted_renderer
|
## .accepted_renderer
|
||||||
|
|
||||||
|
|
|
@ -32,16 +32,16 @@ You should **include the request as a keyword argument** to the function, for ex
|
||||||
|
|
||||||
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
|
from django.utils.timezone import now
|
||||||
|
|
||||||
class APIRootView(APIView):
|
class APIRootView(APIView):
|
||||||
def get(self, request):
|
def get(self, request):
|
||||||
year = now().year
|
year = now().year
|
||||||
data = {
|
data = {
|
||||||
...
|
...
|
||||||
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
||||||
}
|
}
|
||||||
return Response(data)
|
return Response(data)
|
||||||
|
|
||||||
## reverse_lazy
|
## reverse_lazy
|
||||||
|
|
||||||
|
|
|
@ -122,6 +122,7 @@ The `get_schema_view()` helper takes the following keyword arguments:
|
||||||
url='https://www.example.org/api/',
|
url='https://www.example.org/api/',
|
||||||
patterns=schema_url_patterns,
|
patterns=schema_url_patterns,
|
||||||
)
|
)
|
||||||
|
* `public`: May be used to specify if schema should bypass views permissions. Default to False
|
||||||
|
|
||||||
* `generator_class`: May be used to specify a `SchemaGenerator` subclass to be
|
* `generator_class`: May be used to specify a `SchemaGenerator` subclass to be
|
||||||
passed to the `SchemaView`.
|
passed to the `SchemaView`.
|
||||||
|
@ -292,7 +293,7 @@ class CustomView(APIView):
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for
|
Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for
|
||||||
the more commonly needed options do.
|
the more commonly needed options do.
|
||||||
|
|
||||||
### `AutoSchema` methods
|
### `AutoSchema` methods
|
||||||
|
@ -300,7 +301,7 @@ the more commonly needed options do.
|
||||||
#### `get_components()`
|
#### `get_components()`
|
||||||
|
|
||||||
Generates the OpenAPI components that describe request and response bodies,
|
Generates the OpenAPI components that describe request and response bodies,
|
||||||
deriving their properties from the serializer.
|
deriving their properties from the serializer.
|
||||||
|
|
||||||
Returns a dictionary mapping the component name to the generated
|
Returns a dictionary mapping the component name to the generated
|
||||||
representation. By default this has just a single pair but you may override
|
representation. By default this has just a single pair but you may override
|
||||||
|
|
|
@ -594,11 +594,11 @@ The ModelSerializer class also exposes an API that you can override in order to
|
||||||
|
|
||||||
Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.
|
Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.
|
||||||
|
|
||||||
### `.serializer_field_mapping`
|
### `serializer_field_mapping`
|
||||||
|
|
||||||
A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
|
A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
|
||||||
|
|
||||||
### `.serializer_related_field`
|
### `serializer_related_field`
|
||||||
|
|
||||||
This property should be the serializer field class, that is used for relational fields by default.
|
This property should be the serializer field class, that is used for relational fields by default.
|
||||||
|
|
||||||
|
@ -606,13 +606,13 @@ For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`.
|
||||||
|
|
||||||
For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`.
|
For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`.
|
||||||
|
|
||||||
### `.serializer_url_field`
|
### `serializer_url_field`
|
||||||
|
|
||||||
The serializer field class that should be used for any `url` field on the serializer.
|
The serializer field class that should be used for any `url` field on the serializer.
|
||||||
|
|
||||||
Defaults to `serializers.HyperlinkedIdentityField`
|
Defaults to `serializers.HyperlinkedIdentityField`
|
||||||
|
|
||||||
### `.serializer_choice_field`
|
### `serializer_choice_field`
|
||||||
|
|
||||||
The serializer field class that should be used for any choice fields on the serializer.
|
The serializer field class that should be used for any choice fields on the serializer.
|
||||||
|
|
||||||
|
@ -622,13 +622,13 @@ Defaults to `serializers.ChoiceField`
|
||||||
|
|
||||||
The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`.
|
The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`.
|
||||||
|
|
||||||
### `.build_standard_field(self, field_name, model_field)`
|
### `build_standard_field(self, field_name, model_field)`
|
||||||
|
|
||||||
Called to generate a serializer field that maps to a standard model field.
|
Called to generate a serializer field that maps to a standard model field.
|
||||||
|
|
||||||
The default implementation returns a serializer class based on the `serializer_field_mapping` attribute.
|
The default implementation returns a serializer class based on the `serializer_field_mapping` attribute.
|
||||||
|
|
||||||
### `.build_relational_field(self, field_name, relation_info)`
|
### `build_relational_field(self, field_name, relation_info)`
|
||||||
|
|
||||||
Called to generate a serializer field that maps to a relational model field.
|
Called to generate a serializer field that maps to a relational model field.
|
||||||
|
|
||||||
|
@ -636,7 +636,7 @@ The default implementation returns a serializer class based on the `serializer_r
|
||||||
|
|
||||||
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
||||||
|
|
||||||
### `.build_nested_field(self, field_name, relation_info, nested_depth)`
|
### `build_nested_field(self, field_name, relation_info, nested_depth)`
|
||||||
|
|
||||||
Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set.
|
Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set.
|
||||||
|
|
||||||
|
@ -646,17 +646,17 @@ The `nested_depth` will be the value of the `depth` option, minus one.
|
||||||
|
|
||||||
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
||||||
|
|
||||||
### `.build_property_field(self, field_name, model_class)`
|
### `build_property_field(self, field_name, model_class)`
|
||||||
|
|
||||||
Called to generate a serializer field that maps to a property or zero-argument method on the model class.
|
Called to generate a serializer field that maps to a property or zero-argument method on the model class.
|
||||||
|
|
||||||
The default implementation returns a `ReadOnlyField` class.
|
The default implementation returns a `ReadOnlyField` class.
|
||||||
|
|
||||||
### `.build_url_field(self, field_name, model_class)`
|
### `build_url_field(self, field_name, model_class)`
|
||||||
|
|
||||||
Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class.
|
Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class.
|
||||||
|
|
||||||
### `.build_unknown_field(self, field_name, model_class)`
|
### `build_unknown_field(self, field_name, model_class)`
|
||||||
|
|
||||||
Called when the field name did not map to any model field or model property.
|
Called when the field name did not map to any model field or model property.
|
||||||
The default implementation raises an error, although subclasses may customize this behavior.
|
The default implementation raises an error, although subclasses may customize this behavior.
|
||||||
|
@ -910,7 +910,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:
|
||||||
|
|
||||||
|
@ -918,7 +918,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
|
||||||
|
|
||||||
|
@ -949,8 +949,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
|
||||||
|
@ -1021,7 +1021,7 @@ Some reasons this might be useful include...
|
||||||
|
|
||||||
The signatures for these methods are as follows:
|
The signatures for these methods are as follows:
|
||||||
|
|
||||||
#### `.to_representation(self, instance)`
|
#### `to_representation(self, instance)`
|
||||||
|
|
||||||
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
|
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
|
||||||
|
|
||||||
|
@ -1033,7 +1033,7 @@ May be overridden in order to modify the representation style. For example:
|
||||||
ret['username'] = ret['username'].lower()
|
ret['username'] = ret['username'].lower()
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
#### ``.to_internal_value(self, data)``
|
#### ``to_internal_value(self, data)``
|
||||||
|
|
||||||
Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
|
Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
|
||||||
|
|
||||||
|
|
|
@ -41,6 +41,8 @@ This class of status code indicates a provisional response. There are no 1xx st
|
||||||
|
|
||||||
HTTP_100_CONTINUE
|
HTTP_100_CONTINUE
|
||||||
HTTP_101_SWITCHING_PROTOCOLS
|
HTTP_101_SWITCHING_PROTOCOLS
|
||||||
|
HTTP_102_PROCESSING
|
||||||
|
HTTP_103_EARLY_HINTS
|
||||||
|
|
||||||
## Successful - 2xx
|
## Successful - 2xx
|
||||||
|
|
||||||
|
@ -93,9 +95,11 @@ The 4xx class of status code is intended for cases in which the client seems to
|
||||||
HTTP_415_UNSUPPORTED_MEDIA_TYPE
|
HTTP_415_UNSUPPORTED_MEDIA_TYPE
|
||||||
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
|
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
|
||||||
HTTP_417_EXPECTATION_FAILED
|
HTTP_417_EXPECTATION_FAILED
|
||||||
|
HTTP_421_MISDIRECTED_REQUEST
|
||||||
HTTP_422_UNPROCESSABLE_ENTITY
|
HTTP_422_UNPROCESSABLE_ENTITY
|
||||||
HTTP_423_LOCKED
|
HTTP_423_LOCKED
|
||||||
HTTP_424_FAILED_DEPENDENCY
|
HTTP_424_FAILED_DEPENDENCY
|
||||||
|
HTTP_425_TOO_EARLY
|
||||||
HTTP_426_UPGRADE_REQUIRED
|
HTTP_426_UPGRADE_REQUIRED
|
||||||
HTTP_428_PRECONDITION_REQUIRED
|
HTTP_428_PRECONDITION_REQUIRED
|
||||||
HTTP_429_TOO_MANY_REQUESTS
|
HTTP_429_TOO_MANY_REQUESTS
|
||||||
|
|
|
@ -50,9 +50,9 @@ The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `mi
|
||||||
You can also set the throttling policy on a per-view or per-viewset basis,
|
You can also set the throttling policy on a per-view or per-viewset basis,
|
||||||
using the `APIView` class-based views.
|
using the `APIView` class-based views.
|
||||||
|
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.throttling import UserRateThrottle
|
from rest_framework.throttling import UserRateThrottle
|
||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
class ExampleView(APIView):
|
class ExampleView(APIView):
|
||||||
throttle_classes = [UserRateThrottle]
|
throttle_classes = [UserRateThrottle]
|
||||||
|
|
|
@ -20,7 +20,7 @@ Validation in Django REST framework serializers is handled a little differently
|
||||||
With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
|
With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
|
||||||
|
|
||||||
* It introduces a proper separation of concerns, making your code behavior more obvious.
|
* It introduces a proper separation of concerns, making your code behavior more obvious.
|
||||||
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
|
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
|
||||||
* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.
|
* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.
|
||||||
|
|
||||||
When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using `Serializer` classes instead, then you need to define the validation rules explicitly.
|
When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using `Serializer` classes instead, then you need to define the validation rules explicitly.
|
||||||
|
@ -208,7 +208,7 @@ by specifying an empty list for the serializer `Meta.validators` attribute.
|
||||||
|
|
||||||
By default "unique together" validation enforces that all fields be
|
By default "unique together" validation enforces that all fields be
|
||||||
`required=True`. In some cases, you might want to explicit apply
|
`required=True`. In some cases, you might want to explicit apply
|
||||||
`required=False` to one of the fields, in which case the desired behaviour
|
`required=False` to one of the fields, in which case the desired behavior
|
||||||
of the validation is ambiguous.
|
of the validation is ambiguous.
|
||||||
|
|
||||||
In this case you will typically need to exclude the validator from the
|
In this case you will typically need to exclude the validator from the
|
||||||
|
|
|
@ -153,7 +153,7 @@ The core of this functionality is the `api_view` decorator, which takes a list o
|
||||||
|
|
||||||
This view will use the default renderers, parsers, authentication classes etc specified in the [settings].
|
This view will use the default renderers, parsers, authentication classes etc specified in the [settings].
|
||||||
|
|
||||||
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behaviour, specify which methods the view allows, like so:
|
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so:
|
||||||
|
|
||||||
@api_view(['GET', 'POST'])
|
@api_view(['GET', 'POST'])
|
||||||
def hello_world(request):
|
def hello_world(request):
|
||||||
|
|
|
@ -116,7 +116,7 @@ During dispatch, the following attributes are available on the `ViewSet`.
|
||||||
* `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`.
|
* `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.
|
* `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 behavior based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
||||||
|
|
||||||
def get_permissions(self):
|
def get_permissions(self):
|
||||||
"""
|
"""
|
||||||
|
@ -247,7 +247,7 @@ In order to use a `GenericViewSet` class you'll override the class and either mi
|
||||||
|
|
||||||
The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
|
The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
|
||||||
|
|
||||||
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
|
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
|
||||||
|
|
||||||
#### Example
|
#### Example
|
||||||
|
|
||||||
|
|
|
@ -24,7 +24,7 @@ Notable features of this new release include:
|
||||||
* Support for overriding how validation errors are handled by your API.
|
* Support for overriding how validation errors are handled by your API.
|
||||||
* A metadata API that allows you to customize how `OPTIONS` requests are handled by your API.
|
* A metadata API that allows you to customize how `OPTIONS` requests are handled by your API.
|
||||||
* A more compact JSON output with unicode style encoding turned on by default.
|
* A more compact JSON output with unicode style encoding turned on by default.
|
||||||
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
|
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
|
||||||
|
|
||||||
Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two [Kickstarter stretch goals](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.
|
Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two [Kickstarter stretch goals](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.
|
||||||
|
|
||||||
|
@ -632,7 +632,7 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel
|
||||||
|
|
||||||
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
|
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
|
||||||
|
|
||||||
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...
|
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behavior in a way that did not simply lookup the field value from the object. For example...
|
||||||
|
|
||||||
def field_to_native(self, obj, field_name):
|
def field_to_native(self, obj, field_name):
|
||||||
"""A custom read-only field that returns the class name."""
|
"""A custom read-only field that returns the class name."""
|
||||||
|
|
|
@ -30,12 +30,12 @@ in the URL path.
|
||||||
|
|
||||||
For example...
|
For example...
|
||||||
|
|
||||||
Method | Path | Tags
|
Method | Path | Tags
|
||||||
--------------------------------|-----------------|-------------
|
--------------------------------|-----------------|-------------
|
||||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']`
|
`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']`
|
||||||
`GET`, `POST` | `/users/` | `['users']`
|
`GET`, `POST` | `/users/` | `['users']`
|
||||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']`
|
`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']`
|
||||||
`GET`, `POST` | `/orders/` | `['orders']`
|
`GET`, `POST` | `/orders/` | `['orders']`
|
||||||
|
|
||||||
The tags used for a particular view may also be overridden...
|
The tags used for a particular view may also be overridden...
|
||||||
|
|
||||||
|
|
62
docs/community/3.14-announcement.md
Normal file
62
docs/community/3.14-announcement.md
Normal file
|
@ -0,0 +1,62 @@
|
||||||
|
<style>
|
||||||
|
.promo li a {
|
||||||
|
float: left;
|
||||||
|
width: 130px;
|
||||||
|
height: 20px;
|
||||||
|
text-align: center;
|
||||||
|
margin: 10px 30px;
|
||||||
|
padding: 150px 0 0 0;
|
||||||
|
background-position: 0 50%;
|
||||||
|
background-size: 130px auto;
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
font-size: 120%;
|
||||||
|
color: black;
|
||||||
|
}
|
||||||
|
.promo li {
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
# Django REST framework 3.14
|
||||||
|
|
||||||
|
## Django 4.1 support
|
||||||
|
|
||||||
|
The latest release now fully supports Django 4.1, and drops support for Django 2.2.
|
||||||
|
|
||||||
|
Our requirements are now:
|
||||||
|
|
||||||
|
* Python 3.6+
|
||||||
|
* Django 4.1, 4.0, 3.2, 3.1, 3.0
|
||||||
|
|
||||||
|
## `raise_exceptions` argument for `is_valid` is now keyword-only.
|
||||||
|
|
||||||
|
Calling `serializer_instance.is_valid(True)` is no longer acceptable syntax.
|
||||||
|
If you'd like to use the `raise_exceptions` argument, you must use it as a
|
||||||
|
keyword argument.
|
||||||
|
|
||||||
|
See Pull Request [#7952](https://github.com/encode/django-rest-framework/pull/7952) for more details.
|
||||||
|
|
||||||
|
## `ManyRelatedField` supports returning the default when the source attribute doesn't exist.
|
||||||
|
|
||||||
|
Previously, if you used a serializer field with `many=True` with a dot notated source field
|
||||||
|
that didn't exist, it would raise an `AttributeError`. Now it will return the default or be
|
||||||
|
skipped depending on the other arguments.
|
||||||
|
|
||||||
|
See Pull Request [#7574](https://github.com/encode/django-rest-framework/pull/7574) for more details.
|
||||||
|
|
||||||
|
|
||||||
|
## Make Open API `get_reference` public.
|
||||||
|
|
||||||
|
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
|
||||||
|
|
||||||
|
## Change semantic of OR of two permission classes.
|
||||||
|
|
||||||
|
When OR-ing two permissions, the request has to pass either class's `has_permission() and has_object_permission()`.
|
||||||
|
|
||||||
|
Previously, both class's `has_permission()` was ignored when OR-ing two permissions together.
|
||||||
|
|
||||||
|
See Pull Request [#7522](https://github.com/encode/django-rest-framework/pull/7522) for more details.
|
||||||
|
|
||||||
|
## Minor fixes and improvements
|
||||||
|
|
||||||
|
There are a number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing.
|
|
@ -64,7 +64,7 @@ These are a little subtle and probably won't affect most users, but are worth un
|
||||||
|
|
||||||
### ManyToMany fields and blank=True
|
### ManyToMany fields and blank=True
|
||||||
|
|
||||||
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
||||||
|
|
||||||
As a follow-up to this we are now able to properly mirror the behavior of Django's `ModelForm` with respect to how many-to-many fields are validated.
|
As a follow-up to this we are now able to properly mirror the behavior of Django's `ModelForm` with respect to how many-to-many fields are validated.
|
||||||
|
|
||||||
|
|
|
@ -38,7 +38,7 @@ The AJAX based support for the browsable API means that there are a number of in
|
||||||
|
|
||||||
* 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][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][method-override].
|
* 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.
|
||||||
|
|
||||||
|
|
|
@ -89,7 +89,7 @@ Name | Support | PyPI pa
|
||||||
---------------------------------|-------------------------------------|--------------------------------
|
---------------------------------|-------------------------------------|--------------------------------
|
||||||
[Core JSON][core-json] | Schema generation & client support. | Built-in support in `coreapi`.
|
[Core JSON][core-json] | Schema generation & client support. | Built-in support in `coreapi`.
|
||||||
[Swagger / OpenAPI][swagger] | Schema generation & client support. | The `openapi-codec` package.
|
[Swagger / OpenAPI][swagger] | Schema generation & client support. | The `openapi-codec` package.
|
||||||
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
|
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
|
||||||
[API Blueprint][api-blueprint] | Not yet available. | Not yet available.
|
[API Blueprint][api-blueprint] | Not yet available. | Not yet available.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
|
@ -89,7 +89,7 @@ for a complete listing.
|
||||||
|
|
||||||
We're currently working towards moving to using [OpenAPI][openapi] as our default schema output. We'll also be revisiting our API documentation generation and client libraries.
|
We're currently working towards moving to using [OpenAPI][openapi] as our default schema output. We'll also be revisiting our API documentation generation and client libraries.
|
||||||
|
|
||||||
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
|
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
|
||||||
|
|
||||||
[funding]: funding.md
|
[funding]: funding.md
|
||||||
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886
|
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886
|
||||||
|
|
|
@ -80,7 +80,7 @@ To run the tests, clone the repository, and then:
|
||||||
# Setup the virtual environment
|
# Setup the virtual environment
|
||||||
python3 -m venv env
|
python3 -m venv env
|
||||||
source env/bin/activate
|
source env/bin/activate
|
||||||
pip install django
|
pip install -e .
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
|
|
||||||
# Run the tests
|
# Run the tests
|
||||||
|
|
|
@ -124,7 +124,7 @@ REST framework continues to be open-source and permissively licensed, but we fir
|
||||||
## What funding has enabled so far
|
## What funding has enabled so far
|
||||||
|
|
||||||
* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
|
* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
|
||||||
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
|
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
|
||||||
* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
|
* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
|
||||||
* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/).
|
* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/).
|
||||||
* Tom Christie, the creator of Django REST framework, working on the project full-time.
|
* Tom Christie, the creator of Django REST framework, working on the project full-time.
|
||||||
|
@ -154,13 +154,13 @@ Sign up for a paid plan today, and help ensure that REST framework becomes a sus
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
|
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
|
||||||
>
|
>
|
||||||
> — Filipe Ximenes, Vinta Software
|
> — Filipe Ximenes, Vinta Software
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
|
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
|
||||||
DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.
|
DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.
|
||||||
>
|
>
|
||||||
> — Andrew Conti, Django REST framework user
|
> — Andrew Conti, Django REST framework user
|
||||||
|
|
|
@ -14,8 +14,9 @@ Looking for a new Django REST Framework related role? On this site we provide a
|
||||||
* [https://stackoverflow.com/jobs/companies?tl=django][stackoverflow-com]
|
* [https://stackoverflow.com/jobs/companies?tl=django][stackoverflow-com]
|
||||||
* [https://www.upwork.com/o/jobs/browse/skill/django-framework/][upwork-com]
|
* [https://www.upwork.com/o/jobs/browse/skill/django-framework/][upwork-com]
|
||||||
* [https://www.technojobs.co.uk/django-jobs][technobjobs-co-uk]
|
* [https://www.technojobs.co.uk/django-jobs][technobjobs-co-uk]
|
||||||
* [https://remoteok.io/remote-django-jobs][remoteok-io]
|
* [https://remoteok.com/remote-django-jobs][remoteok-com]
|
||||||
* [https://www.remotepython.com/jobs/][remotepython-com]
|
* [https://www.remotepython.com/jobs/][remotepython-com]
|
||||||
|
* [https://www.pyjobs.com/][pyjobs-com]
|
||||||
|
|
||||||
|
|
||||||
Know of any other great resources for Django REST Framework jobs that are missing in our list? Please [submit a pull request][submit-pr] or [email us][anna-email].
|
Know of any other great resources for Django REST Framework jobs that are missing in our list? Please [submit a pull request][submit-pr] or [email us][anna-email].
|
||||||
|
@ -32,8 +33,9 @@ Wonder how else you can help? One of the best ways you can help Django REST Fram
|
||||||
[stackoverflow-com]: https://stackoverflow.com/jobs/companies?tl=django
|
[stackoverflow-com]: https://stackoverflow.com/jobs/companies?tl=django
|
||||||
[upwork-com]: https://www.upwork.com/o/jobs/browse/skill/django-framework/
|
[upwork-com]: https://www.upwork.com/o/jobs/browse/skill/django-framework/
|
||||||
[technobjobs-co-uk]: https://www.technojobs.co.uk/django-jobs
|
[technobjobs-co-uk]: https://www.technojobs.co.uk/django-jobs
|
||||||
[remoteok-io]: https://remoteok.io/remote-django-jobs
|
[remoteok-com]: https://remoteok.com/remote-django-jobs
|
||||||
[remotepython-com]: https://www.remotepython.com/jobs/
|
[remotepython-com]: https://www.remotepython.com/jobs/
|
||||||
|
[pyjobs-com]: https://www.pyjobs.com/
|
||||||
[drf-funding]: https://fund.django-rest-framework.org/topics/funding/
|
[drf-funding]: https://fund.django-rest-framework.org/topics/funding/
|
||||||
[submit-pr]: https://github.com/encode/django-rest-framework
|
[submit-pr]: https://github.com/encode/django-rest-framework
|
||||||
[anna-email]: mailto:anna@django-rest-framework.org
|
[anna-email]: mailto:anna@django-rest-framework.org
|
||||||
|
|
|
@ -34,6 +34,25 @@ You can determine your currently installed version using `pip show`:
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 3.14.x series
|
||||||
|
|
||||||
|
### 3.14.0
|
||||||
|
|
||||||
|
Date: 22nd September 2022
|
||||||
|
|
||||||
|
* Django 2.2 is no longer supported. [[#8662](https://github.com/encode/django-rest-framework/pull/8662)]
|
||||||
|
* Django 4.1 compatibility. [[#8591](https://github.com/encode/django-rest-framework/pull/8591)]
|
||||||
|
* Add `--api-version` CLI option to `generateschema` management command. [[#8663](https://github.com/encode/django-rest-framework/pull/8663)]
|
||||||
|
* Enforce `is_valid(raise_exception=False)` as a keyword-only argument. [[#7952](https://github.com/encode/django-rest-framework/pull/7952)]
|
||||||
|
* Stop calling `set_context` on Validators. [[#8589](https://github.com/encode/django-rest-framework/pull/8589)]
|
||||||
|
* Return `NotImplemented` from `ErrorDetails.__ne__`. [[#8538](https://github.com/encode/django-rest-framework/pull/8538)]
|
||||||
|
* Don't evaluate `DateTimeField.default_timezone` when a custom timezone is set. [[#8531](https://github.com/encode/django-rest-framework/pull/8531)]
|
||||||
|
* Make relative URLs clickable in Browseable API. [[#8464](https://github.com/encode/django-rest-framework/pull/8464)]
|
||||||
|
* Support `ManyRelatedField` falling back to the default value when the attribute specified by dot notation doesn't exist. Matches `ManyRelatedField.get_attribute` to `Field.get_attribute`. [[#7574](https://github.com/encode/django-rest-framework/pull/7574)]
|
||||||
|
* Make `schemas.openapi.get_reference` public. [[#7515](https://github.com/encode/django-rest-framework/pull/7515)]
|
||||||
|
* Make `ReturnDict` support `dict` union operators on Python 3.9 and later. [[#8302](https://github.com/encode/django-rest-framework/pull/8302)]
|
||||||
|
* Update throttling to check if `request.user` is set before checking if the user is authenticated. [[#8370](https://github.com/encode/django-rest-framework/pull/8370)]
|
||||||
|
|
||||||
## 3.13.x series
|
## 3.13.x series
|
||||||
|
|
||||||
### 3.13.1
|
### 3.13.1
|
||||||
|
|
|
@ -205,7 +205,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
||||||
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
|
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
|
||||||
[django-url-filter]: https://github.com/miki725/django-url-filter
|
[django-url-filter]: https://github.com/miki725/django-url-filter
|
||||||
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
|
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
|
||||||
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
|
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
|
||||||
[drf-haystack]: https://drf-haystack.readthedocs.io/en/latest/
|
[drf-haystack]: https://drf-haystack.readthedocs.io/en/latest/
|
||||||
[django-rest-framework-version-transforms]: https://github.com/mrhwick/django-rest-framework-version-transforms
|
[django-rest-framework-version-transforms]: https://github.com/mrhwick/django-rest-framework-version-transforms
|
||||||
[djangorestframework-jsonapi]: https://github.com/django-json-api/django-rest-framework-json-api
|
[djangorestframework-jsonapi]: https://github.com/django-json-api/django-rest-framework-json-api
|
||||||
|
|
|
@ -43,7 +43,7 @@ This will include two different views:
|
||||||
**Note**: By default `include_docs_urls` configures the underlying `SchemaView` to generate _public_ schemas.
|
**Note**: By default `include_docs_urls` configures the underlying `SchemaView` to generate _public_ schemas.
|
||||||
This means that views will not be instantiated with a `request` instance. i.e. Inside the view `self.request` will be `None`.
|
This means that views will not be instantiated with a `request` instance. i.e. Inside the view `self.request` will be `None`.
|
||||||
|
|
||||||
To be compatible with this behaviour, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
|
To be compatible with this behavior, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
|
||||||
|
|
||||||
You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:
|
You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:
|
||||||
|
|
||||||
|
|
|
@ -398,7 +398,7 @@ then you can use the `SchemaGenerator` class directly to auto-generate the
|
||||||
`Document` instance, and to return that from a view.
|
`Document` instance, and to return that from a view.
|
||||||
|
|
||||||
This option gives you the flexibility of setting up the schema endpoint
|
This option gives you the flexibility of setting up the schema endpoint
|
||||||
with whatever behaviour you want. For example, you can apply different
|
with whatever behavior you want. For example, you can apply different
|
||||||
permission, throttling, or authentication policies to the schema endpoint.
|
permission, throttling, or authentication policies to the schema endpoint.
|
||||||
|
|
||||||
Here's an example of using `SchemaGenerator` together with a view to
|
Here's an example of using `SchemaGenerator` together with a view to
|
||||||
|
@ -572,7 +572,7 @@ A class that deals with introspection of individual views for schema generation.
|
||||||
|
|
||||||
`AutoSchema` is attached to `APIView` via the `schema` attribute.
|
`AutoSchema` is attached to `APIView` via the `schema` attribute.
|
||||||
|
|
||||||
The `AutoSchema` constructor takes a single keyword argument `manual_fields`.
|
The `AutoSchema` constructor takes a single keyword argument `manual_fields`.
|
||||||
|
|
||||||
**`manual_fields`**: a `list` of `coreapi.Field` instances that will be added to
|
**`manual_fields`**: a `list` of `coreapi.Field` instances that will be added to
|
||||||
the generated fields. Generated fields with a matching `name` will be overwritten.
|
the generated fields. Generated fields with a matching `name` will be overwritten.
|
||||||
|
@ -649,10 +649,10 @@ def get_manual_fields(self, path, method):
|
||||||
"""Example adding per-method fields."""
|
"""Example adding per-method fields."""
|
||||||
|
|
||||||
extra_fields = []
|
extra_fields = []
|
||||||
if method=='GET':
|
if method == 'GET':
|
||||||
extra_fields = # ... list of extra fields for GET ...
|
extra_fields = ... # list of extra fields for GET
|
||||||
if method=='POST':
|
if method == 'POST':
|
||||||
extra_fields = # ... list of extra fields for POST ...
|
extra_fields = ... # list of extra fields for POST
|
||||||
|
|
||||||
manual_fields = super().get_manual_fields(path, method)
|
manual_fields = super().get_manual_fields(path, method)
|
||||||
return manual_fields + extra_fields
|
return manual_fields + extra_fields
|
||||||
|
|
|
@ -85,7 +85,7 @@ continued development by **[signing up for a paid plan][funding]**.
|
||||||
|
|
||||||
REST framework requires the following:
|
REST framework requires the following:
|
||||||
|
|
||||||
* Python (3.6, 3.7, 3.8, 3.9, 3.10)
|
* Python (3.6, 3.7, 3.8, 3.9, 3.10, 3.11)
|
||||||
* Django (2.2, 3.0, 3.1, 3.2, 4.0, 4.1)
|
* Django (2.2, 3.0, 3.1, 3.2, 4.0, 4.1)
|
||||||
|
|
||||||
We **highly recommend** and only officially support the latest patch release of
|
We **highly recommend** and only officially support the latest patch release of
|
||||||
|
@ -188,7 +188,7 @@ Framework.
|
||||||
|
|
||||||
## Support
|
## Support
|
||||||
|
|
||||||
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.libera.chat`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
|
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.libera.chat`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
|
||||||
|
|
||||||
For priority support please sign up for a [professional or premium sponsorship plan](https://fund.django-rest-framework.org/topics/funding/).
|
For priority support please sign up for a [professional or premium sponsorship plan](https://fund.django-rest-framework.org/topics/funding/).
|
||||||
|
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
|
> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
|
||||||
>
|
>
|
||||||
> — [Jeff Atwood][cite]
|
> — [Jeff Atwood][cite]
|
||||||
|
|
||||||
## Javascript clients
|
## Javascript clients
|
||||||
|
|
||||||
|
|
|
@ -230,7 +230,7 @@ started.
|
||||||
In order to start working with an API, we first need a `Client` instance. The
|
In order to start working with an API, we first need a `Client` instance. The
|
||||||
client holds any configuration around which codecs and transports are supported
|
client holds any configuration around which codecs and transports are supported
|
||||||
when interacting with an API, which allows you to provide for more advanced
|
when interacting with an API, which allows you to provide for more advanced
|
||||||
kinds of behaviour.
|
kinds of behavior.
|
||||||
|
|
||||||
import coreapi
|
import coreapi
|
||||||
client = coreapi.Client()
|
client = coreapi.Client()
|
||||||
|
|
|
@ -17,7 +17,7 @@ By default, the API will return the format specified by the headers, which in th
|
||||||
|
|
||||||
## Customizing
|
## Customizing
|
||||||
|
|
||||||
The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.3.5), making it easy to customize the look-and-feel.
|
The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.4.1), making it easy to customize the look-and-feel.
|
||||||
|
|
||||||
To customize the default style, create a template called `rest_framework/api.html` that extends from `rest_framework/base.html`. For example:
|
To customize the default style, create a template called `rest_framework/api.html` that extends from `rest_framework/base.html`. For example:
|
||||||
|
|
||||||
|
@ -35,7 +35,7 @@ To replace the default theme, add a `bootstrap_theme` block to your `api.html` a
|
||||||
<link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css">
|
<link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css">
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above.
|
Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above. Make sure that the Bootstrap version of the new theme matches that of the default theme.
|
||||||
|
|
||||||
You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style.
|
You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style.
|
||||||
|
|
||||||
|
@ -44,7 +44,7 @@ Full example:
|
||||||
{% extends "rest_framework/base.html" %}
|
{% extends "rest_framework/base.html" %}
|
||||||
|
|
||||||
{% block bootstrap_theme %}
|
{% block bootstrap_theme %}
|
||||||
<link rel="stylesheet" href="https://bootswatch.com/flatly/bootstrap.min.css" type="text/css">
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch@3.4.1/flatly/bootstrap.min.css" type="text/css">
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block bootstrap_navbar_variant %}{% endblock %}
|
{% block bootstrap_navbar_variant %}{% endblock %}
|
||||||
|
|
|
@ -207,14 +207,14 @@ Field templates can also use additional style properties, depending on their typ
|
||||||
|
|
||||||
The complete list of `base_template` options and their associated style options is listed below.
|
The complete list of `base_template` options and their associated style options is listed below.
|
||||||
|
|
||||||
base_template | Valid field types | Additional style options
|
base_template | Valid field types | Additional style options
|
||||||
----|----|----
|
-----------------------|-------------------------------------------------------------|-----------------------------------------------
|
||||||
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
|
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
|
||||||
textarea.html | `CharField` | rows, placeholder, hide_label
|
textarea.html | `CharField` | rows, placeholder, hide_label
|
||||||
select.html | `ChoiceField` or relational field types | hide_label
|
select.html | `ChoiceField` or relational field types | hide_label
|
||||||
radio.html | `ChoiceField` or relational field types | inline, hide_label
|
radio.html | `ChoiceField` or relational field types | inline, hide_label
|
||||||
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
|
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
|
||||||
checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
|
checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
|
||||||
checkbox.html | `BooleanField` | hide_label
|
checkbox.html | `BooleanField` | hide_label
|
||||||
fieldset.html | Nested serializer | hide_label
|
fieldset.html | Nested serializer | hide_label
|
||||||
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label
|
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label
|
||||||
|
|
|
@ -4,7 +4,7 @@
|
||||||
>
|
>
|
||||||
> — Mike Amundsen, [REST fest 2012 keynote][cite].
|
> — Mike Amundsen, [REST fest 2012 keynote][cite].
|
||||||
|
|
||||||
First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
|
First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to ensure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
|
||||||
|
|
||||||
If you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices.
|
If you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices.
|
||||||
|
|
||||||
|
|
|
@ -179,7 +179,7 @@ We can also serialize querysets instead of model instances. To do so we simply
|
||||||
|
|
||||||
## Using ModelSerializers
|
## Using ModelSerializers
|
||||||
|
|
||||||
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
|
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
|
||||||
|
|
||||||
In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes.
|
In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes.
|
||||||
|
|
||||||
|
@ -307,7 +307,7 @@ Quit out of the shell...
|
||||||
Validating models...
|
Validating models...
|
||||||
|
|
||||||
0 errors found
|
0 errors found
|
||||||
Django version 4.0,1 using settings 'tutorial.settings'
|
Django version 4.0, using settings 'tutorial.settings'
|
||||||
Starting Development server at http://127.0.0.1:8000/
|
Starting Development server at http://127.0.0.1:8000/
|
||||||
Quit the server with CONTROL-C.
|
Quit the server with CONTROL-C.
|
||||||
|
|
||||||
|
|
|
@ -29,7 +29,7 @@ REST framework provides two wrappers you can use to write API views.
|
||||||
|
|
||||||
These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
|
These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
|
||||||
|
|
||||||
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
|
The wrappers also provide behavior such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
|
||||||
|
|
||||||
## Pulling it all together
|
## Pulling it all together
|
||||||
|
|
||||||
|
|
|
@ -79,9 +79,9 @@ Okay, we're done. If you run the development server everything should be workin
|
||||||
|
|
||||||
## Using mixins
|
## Using mixins
|
||||||
|
|
||||||
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behaviour.
|
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behavior.
|
||||||
|
|
||||||
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.
|
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behavior are implemented in REST framework's mixin classes.
|
||||||
|
|
||||||
Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again.
|
Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again.
|
||||||
|
|
||||||
|
|
|
@ -112,8 +112,8 @@ Here's our re-wired `snippets/urls.py` file.
|
||||||
|
|
||||||
# Create a router and register our viewsets with it.
|
# Create a router and register our viewsets with it.
|
||||||
router = DefaultRouter()
|
router = DefaultRouter()
|
||||||
router.register(r'snippets', views.SnippetViewSet,basename="snippet")
|
router.register(r'snippets', views.SnippetViewSet, basename='snippet')
|
||||||
router.register(r'users', views.UserViewSet,basename="user")
|
router.register(r'users', views.UserViewSet, basename='user')
|
||||||
|
|
||||||
# The API URLs are now determined automatically by the router.
|
# The API URLs are now determined automatically by the router.
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
|
|
|
@ -30,22 +30,24 @@ The project layout should look like:
|
||||||
<some path>/tutorial
|
<some path>/tutorial
|
||||||
$ find .
|
$ find .
|
||||||
.
|
.
|
||||||
./manage.py
|
|
||||||
./tutorial
|
./tutorial
|
||||||
|
./tutorial/asgi.py
|
||||||
./tutorial/__init__.py
|
./tutorial/__init__.py
|
||||||
./tutorial/quickstart
|
./tutorial/quickstart
|
||||||
./tutorial/quickstart/__init__.py
|
|
||||||
./tutorial/quickstart/admin.py
|
|
||||||
./tutorial/quickstart/apps.py
|
|
||||||
./tutorial/quickstart/migrations
|
./tutorial/quickstart/migrations
|
||||||
./tutorial/quickstart/migrations/__init__.py
|
./tutorial/quickstart/migrations/__init__.py
|
||||||
./tutorial/quickstart/models.py
|
./tutorial/quickstart/models.py
|
||||||
|
./tutorial/quickstart/__init__.py
|
||||||
|
./tutorial/quickstart/apps.py
|
||||||
|
./tutorial/quickstart/admin.py
|
||||||
./tutorial/quickstart/tests.py
|
./tutorial/quickstart/tests.py
|
||||||
./tutorial/quickstart/views.py
|
./tutorial/quickstart/views.py
|
||||||
./tutorial/asgi.py
|
|
||||||
./tutorial/settings.py
|
./tutorial/settings.py
|
||||||
./tutorial/urls.py
|
./tutorial/urls.py
|
||||||
./tutorial/wsgi.py
|
./tutorial/wsgi.py
|
||||||
|
./env
|
||||||
|
./env/...
|
||||||
|
./manage.py
|
||||||
|
|
||||||
It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart).
|
It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart).
|
||||||
|
|
||||||
|
@ -53,9 +55,9 @@ Now sync your database for the first time:
|
||||||
|
|
||||||
python manage.py migrate
|
python manage.py migrate
|
||||||
|
|
||||||
We'll also create an initial user named `admin` with a password of `password123`. We'll authenticate as that user later in our example.
|
We'll also create an initial user named `admin` with a password. We'll authenticate as that user later in our example.
|
||||||
|
|
||||||
python manage.py createsuperuser --email admin@example.com --username admin
|
python manage.py createsuperuser --username admin --email admin@example.com
|
||||||
|
|
||||||
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...
|
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...
|
||||||
|
|
||||||
|
@ -63,7 +65,7 @@ Once you've set up a database and the initial user is created and ready to go, o
|
||||||
|
|
||||||
First up we're going to define some serializers. Let's create a new module named `tutorial/quickstart/serializers.py` that we'll use for our data representations.
|
First up we're going to define some serializers. Let's create a new module named `tutorial/quickstart/serializers.py` that we'll use for our data representations.
|
||||||
|
|
||||||
from django.contrib.auth.models import User, Group
|
from django.contrib.auth.models import Group, User
|
||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
|
||||||
|
@ -84,10 +86,10 @@ Notice that we're using hyperlinked relations in this case with `HyperlinkedMode
|
||||||
|
|
||||||
Right, we'd better write some views then. Open `tutorial/quickstart/views.py` and get typing.
|
Right, we'd better write some views then. Open `tutorial/quickstart/views.py` and get typing.
|
||||||
|
|
||||||
from django.contrib.auth.models import User, Group
|
from django.contrib.auth.models import Group, User
|
||||||
from rest_framework import viewsets
|
from rest_framework import permissions, viewsets
|
||||||
from rest_framework import permissions
|
|
||||||
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
|
from tutorial.quickstart.serializers import GroupSerializer, UserSerializer
|
||||||
|
|
||||||
|
|
||||||
class UserViewSet(viewsets.ModelViewSet):
|
class UserViewSet(viewsets.ModelViewSet):
|
||||||
|
@ -117,6 +119,7 @@ Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
|
||||||
|
|
||||||
from django.urls import include, path
|
from django.urls import include, path
|
||||||
from rest_framework import routers
|
from rest_framework import routers
|
||||||
|
|
||||||
from tutorial.quickstart import views
|
from tutorial.quickstart import views
|
||||||
|
|
||||||
router = routers.DefaultRouter()
|
router = routers.DefaultRouter()
|
||||||
|
@ -165,9 +168,30 @@ We're now ready to test the API we've built. Let's fire up the server from the
|
||||||
|
|
||||||
We can now access our API, both from the command-line, using tools like `curl`...
|
We can now access our API, both from the command-line, using tools like `curl`...
|
||||||
|
|
||||||
bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
|
bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/
|
||||||
|
Enter host password for user 'admin':
|
||||||
{
|
{
|
||||||
"count": 2,
|
"count": 1,
|
||||||
|
"next": null,
|
||||||
|
"previous": null,
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"url": "http://127.0.0.1:8000/users/1/",
|
||||||
|
"username": "admin",
|
||||||
|
"email": "admin@example.com",
|
||||||
|
"groups": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
Or using the [httpie][httpie], command line tool...
|
||||||
|
|
||||||
|
bash: http -a admin http://127.0.0.1:8000/users/
|
||||||
|
http: password for admin@127.0.0.1:8000::
|
||||||
|
$HTTP/1.1 200 OK
|
||||||
|
...
|
||||||
|
{
|
||||||
|
"count": 1,
|
||||||
"next": null,
|
"next": null,
|
||||||
"previous": null,
|
"previous": null,
|
||||||
"results": [
|
"results": [
|
||||||
|
@ -176,27 +200,7 @@ We can now access our API, both from the command-line, using tools like `curl`..
|
||||||
"groups": [],
|
"groups": [],
|
||||||
"url": "http://127.0.0.1:8000/users/1/",
|
"url": "http://127.0.0.1:8000/users/1/",
|
||||||
"username": "admin"
|
"username": "admin"
|
||||||
},
|
}
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
Or using the [httpie][httpie], command line tool...
|
|
||||||
|
|
||||||
bash: http -a admin:password123 http://127.0.0.1:8000/users/
|
|
||||||
|
|
||||||
HTTP/1.1 200 OK
|
|
||||||
...
|
|
||||||
{
|
|
||||||
"count": 2,
|
|
||||||
"next": null,
|
|
||||||
"previous": null,
|
|
||||||
"results": [
|
|
||||||
{
|
|
||||||
"email": "admin@example.com",
|
|
||||||
"groups": [],
|
|
||||||
"url": "http://localhost:8000/users/1/",
|
|
||||||
"username": "paul"
|
|
||||||
},
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -66,6 +66,7 @@ nav:
|
||||||
- 'Contributing to REST framework': 'community/contributing.md'
|
- 'Contributing to REST framework': 'community/contributing.md'
|
||||||
- 'Project management': 'community/project-management.md'
|
- 'Project management': 'community/project-management.md'
|
||||||
- 'Release Notes': 'community/release-notes.md'
|
- 'Release Notes': 'community/release-notes.md'
|
||||||
|
- '3.14 Announcement': 'community/3.14-announcement.md'
|
||||||
- '3.13 Announcement': 'community/3.13-announcement.md'
|
- '3.13 Announcement': 'community/3.13-announcement.md'
|
||||||
- '3.12 Announcement': 'community/3.12-announcement.md'
|
- '3.12 Announcement': 'community/3.12-announcement.md'
|
||||||
- '3.11 Announcement': 'community/3.11-announcement.md'
|
- '3.11 Announcement': 'community/3.11-announcement.md'
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
# The base set of requirements for REST framework is actually
|
# The base set of requirements for REST framework is actually
|
||||||
# just Django, but for the purposes of development and testing
|
# just Django and pytz, but for the purposes of development
|
||||||
# there are a number of packages that are useful to install.
|
# and testing there are a number of packages that are useful
|
||||||
|
# to install.
|
||||||
|
|
||||||
# Laying these out as separate requirements files, allows us to
|
# Laying these out as separate requirements files, allows us to
|
||||||
# only included the relevant sets when running tox, and ensures
|
# only included the relevant sets when running tox, and ensures
|
||||||
|
|
|
@ -4,6 +4,6 @@ coreschema==0.0.4
|
||||||
django-filter>=2.4.0,<3.0
|
django-filter>=2.4.0,<3.0
|
||||||
django-guardian>=2.4.0,<2.5
|
django-guardian>=2.4.0,<2.5
|
||||||
markdown==3.3
|
markdown==3.3
|
||||||
psycopg2-binary>=2.8.5,<2.9
|
psycopg2-binary>=2.9.5,<2.10
|
||||||
pygments==2.12
|
pygments==2.12
|
||||||
pyyaml>=5.3.1,<5.4
|
pyyaml>=5.3.1,<5.4
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
# Pytest for running the tests.
|
# Pytest for running the tests.
|
||||||
pytest>=6.1,<7.0
|
pytest>=6.2.0,<8.0
|
||||||
pytest-cov>=2.10.1,<3.0
|
pytest-cov>=4.0.0,<5.0
|
||||||
pytest-django>=4.1.0,<5.0
|
pytest-django>=4.5.2,<5.0
|
||||||
|
importlib-metadata<5.0
|
||||||
|
|
|
@ -10,7 +10,7 @@ ______ _____ _____ _____ __
|
||||||
import django
|
import django
|
||||||
|
|
||||||
__title__ = 'Django REST framework'
|
__title__ = 'Django REST framework'
|
||||||
__version__ = '3.13.1'
|
__version__ = '3.14.0'
|
||||||
__author__ = 'Tom Christie'
|
__author__ = 'Tom Christie'
|
||||||
__license__ = 'BSD 3-Clause'
|
__license__ = 'BSD 3-Clause'
|
||||||
__copyright__ = 'Copyright 2011-2019 Encode OSS Ltd'
|
__copyright__ = 'Copyright 2011-2019 Encode OSS Ltd'
|
||||||
|
@ -29,9 +29,5 @@ if django.VERSION < (3, 2):
|
||||||
default_app_config = 'rest_framework.apps.RestFrameworkConfig'
|
default_app_config = 'rest_framework.apps.RestFrameworkConfig'
|
||||||
|
|
||||||
|
|
||||||
class RemovedInDRF313Warning(DeprecationWarning):
|
class RemovedInDRF315Warning(DeprecationWarning):
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class RemovedInDRF314Warning(PendingDeprecationWarning):
|
|
||||||
pass
|
pass
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
import contextlib
|
||||||
import copy
|
import copy
|
||||||
import datetime
|
import datetime
|
||||||
import decimal
|
import decimal
|
||||||
|
@ -5,7 +6,6 @@ import functools
|
||||||
import inspect
|
import inspect
|
||||||
import re
|
import re
|
||||||
import uuid
|
import uuid
|
||||||
import warnings
|
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
from collections.abc import Mapping
|
from collections.abc import Mapping
|
||||||
|
|
||||||
|
@ -30,7 +30,7 @@ from django.utils.ipv6 import clean_ipv6_address
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
from pytz.exceptions import InvalidTimeError
|
from pytz.exceptions import InvalidTimeError
|
||||||
|
|
||||||
from rest_framework import ISO_8601, RemovedInDRF314Warning
|
from rest_framework import ISO_8601
|
||||||
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
|
||||||
from rest_framework.utils import html, humanize_datetime, json, representation
|
from rest_framework.utils import html, humanize_datetime, json, representation
|
||||||
|
@ -691,15 +691,13 @@ class BooleanField(Field):
|
||||||
NULL_VALUES = {'null', 'Null', 'NULL', '', None}
|
NULL_VALUES = {'null', 'Null', 'NULL', '', None}
|
||||||
|
|
||||||
def to_internal_value(self, data):
|
def to_internal_value(self, data):
|
||||||
try:
|
with contextlib.suppress(TypeError):
|
||||||
if data in self.TRUE_VALUES:
|
if data in self.TRUE_VALUES:
|
||||||
return True
|
return True
|
||||||
elif data in self.FALSE_VALUES:
|
elif data in self.FALSE_VALUES:
|
||||||
return False
|
return False
|
||||||
elif data in self.NULL_VALUES and self.allow_null:
|
elif data in self.NULL_VALUES and self.allow_null:
|
||||||
return None
|
return None
|
||||||
except TypeError: # Input is an unhashable type
|
|
||||||
pass
|
|
||||||
self.fail('invalid', input=data)
|
self.fail('invalid', input=data)
|
||||||
|
|
||||||
def to_representation(self, value):
|
def to_representation(self, value):
|
||||||
|
@ -712,23 +710,6 @@ class BooleanField(Field):
|
||||||
return bool(value)
|
return bool(value)
|
||||||
|
|
||||||
|
|
||||||
class NullBooleanField(BooleanField):
|
|
||||||
initial = None
|
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
|
||||||
warnings.warn(
|
|
||||||
"The `NullBooleanField` is deprecated and will be removed starting "
|
|
||||||
"with 3.14. Instead use the `BooleanField` field and set "
|
|
||||||
"`allow_null=True` which does the same thing.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
|
|
||||||
assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.'
|
|
||||||
kwargs['allow_null'] = True
|
|
||||||
|
|
||||||
super().__init__(**kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
# String types...
|
# String types...
|
||||||
|
|
||||||
class CharField(Field):
|
class CharField(Field):
|
||||||
|
@ -982,10 +963,11 @@ class DecimalField(Field):
|
||||||
MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
|
MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
|
||||||
|
|
||||||
def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None,
|
def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None,
|
||||||
localize=False, rounding=None, **kwargs):
|
localize=False, rounding=None, normalize_output=False, **kwargs):
|
||||||
self.max_digits = max_digits
|
self.max_digits = max_digits
|
||||||
self.decimal_places = decimal_places
|
self.decimal_places = decimal_places
|
||||||
self.localize = localize
|
self.localize = localize
|
||||||
|
self.normalize_output = normalize_output
|
||||||
if coerce_to_string is not None:
|
if coerce_to_string is not None:
|
||||||
self.coerce_to_string = coerce_to_string
|
self.coerce_to_string = coerce_to_string
|
||||||
if self.localize:
|
if self.localize:
|
||||||
|
@ -1098,6 +1080,9 @@ class DecimalField(Field):
|
||||||
|
|
||||||
quantized = self.quantize(value)
|
quantized = self.quantize(value)
|
||||||
|
|
||||||
|
if self.normalize_output:
|
||||||
|
quantized = quantized.normalize()
|
||||||
|
|
||||||
if not coerce_to_string:
|
if not coerce_to_string:
|
||||||
return quantized
|
return quantized
|
||||||
if self.localize:
|
if self.localize:
|
||||||
|
@ -1176,19 +1161,14 @@ class DateTimeField(Field):
|
||||||
return self.enforce_timezone(value)
|
return self.enforce_timezone(value)
|
||||||
|
|
||||||
for input_format in input_formats:
|
for input_format in input_formats:
|
||||||
if input_format.lower() == ISO_8601:
|
with contextlib.suppress(ValueError, TypeError):
|
||||||
try:
|
if input_format.lower() == ISO_8601:
|
||||||
parsed = parse_datetime(value)
|
parsed = parse_datetime(value)
|
||||||
if parsed is not None:
|
if parsed is not None:
|
||||||
return self.enforce_timezone(parsed)
|
return self.enforce_timezone(parsed)
|
||||||
except (ValueError, TypeError):
|
|
||||||
pass
|
parsed = self.datetime_parser(value, input_format)
|
||||||
else:
|
return self.enforce_timezone(parsed)
|
||||||
try:
|
|
||||||
parsed = self.datetime_parser(value, input_format)
|
|
||||||
return self.enforce_timezone(parsed)
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
humanized_format = humanize_datetime.datetime_formats(input_formats)
|
humanized_format = humanize_datetime.datetime_formats(input_formats)
|
||||||
self.fail('invalid', format=humanized_format)
|
self.fail('invalid', format=humanized_format)
|
||||||
|
@ -1832,7 +1812,7 @@ class SerializerMethodField(Field):
|
||||||
|
|
||||||
For example:
|
For example:
|
||||||
|
|
||||||
class ExampleSerializer(self):
|
class ExampleSerializer(Serializer):
|
||||||
extra_info = SerializerMethodField()
|
extra_info = SerializerMethodField()
|
||||||
|
|
||||||
def get_extra_info(self, obj):
|
def get_extra_info(self, obj):
|
||||||
|
|
|
@ -26,6 +26,7 @@ class Command(BaseCommand):
|
||||||
parser.add_argument('--urlconf', dest="urlconf", default=None, type=str)
|
parser.add_argument('--urlconf', dest="urlconf", default=None, type=str)
|
||||||
parser.add_argument('--generator_class', dest="generator_class", default=None, type=str)
|
parser.add_argument('--generator_class', dest="generator_class", default=None, type=str)
|
||||||
parser.add_argument('--file', dest="file", default=None, type=str)
|
parser.add_argument('--file', dest="file", default=None, type=str)
|
||||||
|
parser.add_argument('--api_version', dest="api_version", default='', type=str)
|
||||||
|
|
||||||
def handle(self, *args, **options):
|
def handle(self, *args, **options):
|
||||||
if options['generator_class']:
|
if options['generator_class']:
|
||||||
|
@ -37,6 +38,7 @@ class Command(BaseCommand):
|
||||||
title=options['title'],
|
title=options['title'],
|
||||||
description=options['description'],
|
description=options['description'],
|
||||||
urlconf=options['urlconf'],
|
urlconf=options['urlconf'],
|
||||||
|
version=options['api_version'],
|
||||||
)
|
)
|
||||||
schema = generator.get_schema(request=None, public=True)
|
schema = generator.get_schema(request=None, public=True)
|
||||||
renderer = self.get_renderer(options['format'])
|
renderer = self.get_renderer(options['format'])
|
||||||
|
|
|
@ -36,7 +36,6 @@ class SimpleMetadata(BaseMetadata):
|
||||||
label_lookup = ClassLookupDict({
|
label_lookup = ClassLookupDict({
|
||||||
serializers.Field: 'field',
|
serializers.Field: 'field',
|
||||||
serializers.BooleanField: 'boolean',
|
serializers.BooleanField: 'boolean',
|
||||||
serializers.NullBooleanField: 'boolean',
|
|
||||||
serializers.CharField: 'string',
|
serializers.CharField: 'string',
|
||||||
serializers.UUIDField: 'string',
|
serializers.UUIDField: 'string',
|
||||||
serializers.URLField: 'url',
|
serializers.URLField: 'url',
|
||||||
|
@ -49,6 +48,7 @@ class SimpleMetadata(BaseMetadata):
|
||||||
serializers.DateField: 'date',
|
serializers.DateField: 'date',
|
||||||
serializers.DateTimeField: 'datetime',
|
serializers.DateTimeField: 'datetime',
|
||||||
serializers.TimeField: 'time',
|
serializers.TimeField: 'time',
|
||||||
|
serializers.DurationField: 'duration',
|
||||||
serializers.ChoiceField: 'choice',
|
serializers.ChoiceField: 'choice',
|
||||||
serializers.MultipleChoiceField: 'multiple choice',
|
serializers.MultipleChoiceField: 'multiple choice',
|
||||||
serializers.FileField: 'file upload',
|
serializers.FileField: 'file upload',
|
||||||
|
|
|
@ -2,6 +2,8 @@
|
||||||
Pagination serializers determine the structure of the output that should
|
Pagination serializers determine the structure of the output that should
|
||||||
be used for paginated responses.
|
be used for paginated responses.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import contextlib
|
||||||
from base64 import b64decode, b64encode
|
from base64 import b64decode, b64encode
|
||||||
from collections import OrderedDict, namedtuple
|
from collections import OrderedDict, namedtuple
|
||||||
from urllib import parse
|
from urllib import parse
|
||||||
|
@ -193,6 +195,7 @@ class PageNumberPagination(BasePagination):
|
||||||
Paginate a queryset if required, either returning a
|
Paginate a queryset if required, either returning a
|
||||||
page object, or `None` if pagination is not configured for this view.
|
page object, or `None` if pagination is not configured for this view.
|
||||||
"""
|
"""
|
||||||
|
self.request = request
|
||||||
page_size = self.get_page_size(request)
|
page_size = self.get_page_size(request)
|
||||||
if not page_size:
|
if not page_size:
|
||||||
return None
|
return None
|
||||||
|
@ -212,7 +215,6 @@ class PageNumberPagination(BasePagination):
|
||||||
# The browsable API should display pagination controls.
|
# The browsable API should display pagination controls.
|
||||||
self.display_page_controls = True
|
self.display_page_controls = True
|
||||||
|
|
||||||
self.request = request
|
|
||||||
return list(self.page)
|
return list(self.page)
|
||||||
|
|
||||||
def get_page_number(self, request, paginator):
|
def get_page_number(self, request, paginator):
|
||||||
|
@ -257,15 +259,12 @@ class PageNumberPagination(BasePagination):
|
||||||
|
|
||||||
def get_page_size(self, request):
|
def get_page_size(self, request):
|
||||||
if self.page_size_query_param:
|
if self.page_size_query_param:
|
||||||
try:
|
with contextlib.suppress(KeyError, ValueError):
|
||||||
return _positive_int(
|
return _positive_int(
|
||||||
request.query_params[self.page_size_query_param],
|
request.query_params[self.page_size_query_param],
|
||||||
strict=True,
|
strict=True,
|
||||||
cutoff=self.max_page_size
|
cutoff=self.max_page_size
|
||||||
)
|
)
|
||||||
except (KeyError, ValueError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
return self.page_size
|
return self.page_size
|
||||||
|
|
||||||
def get_next_link(self):
|
def get_next_link(self):
|
||||||
|
@ -380,13 +379,13 @@ class LimitOffsetPagination(BasePagination):
|
||||||
template = 'rest_framework/pagination/numbers.html'
|
template = 'rest_framework/pagination/numbers.html'
|
||||||
|
|
||||||
def paginate_queryset(self, queryset, request, view=None):
|
def paginate_queryset(self, queryset, request, view=None):
|
||||||
|
self.request = request
|
||||||
self.limit = self.get_limit(request)
|
self.limit = self.get_limit(request)
|
||||||
if self.limit is None:
|
if self.limit is None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
self.count = self.get_count(queryset)
|
self.count = self.get_count(queryset)
|
||||||
self.offset = self.get_offset(request)
|
self.offset = self.get_offset(request)
|
||||||
self.request = request
|
|
||||||
if self.count > self.limit and self.template is not None:
|
if self.count > self.limit and self.template is not None:
|
||||||
self.display_page_controls = True
|
self.display_page_controls = True
|
||||||
|
|
||||||
|
@ -430,15 +429,12 @@ class LimitOffsetPagination(BasePagination):
|
||||||
|
|
||||||
def get_limit(self, request):
|
def get_limit(self, request):
|
||||||
if self.limit_query_param:
|
if self.limit_query_param:
|
||||||
try:
|
with contextlib.suppress(KeyError, ValueError):
|
||||||
return _positive_int(
|
return _positive_int(
|
||||||
request.query_params[self.limit_query_param],
|
request.query_params[self.limit_query_param],
|
||||||
strict=True,
|
strict=True,
|
||||||
cutoff=self.max_limit
|
cutoff=self.max_limit
|
||||||
)
|
)
|
||||||
except (KeyError, ValueError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
return self.default_limit
|
return self.default_limit
|
||||||
|
|
||||||
def get_offset(self, request):
|
def get_offset(self, request):
|
||||||
|
@ -603,6 +599,7 @@ class CursorPagination(BasePagination):
|
||||||
offset_cutoff = 1000
|
offset_cutoff = 1000
|
||||||
|
|
||||||
def paginate_queryset(self, queryset, request, view=None):
|
def paginate_queryset(self, queryset, request, view=None):
|
||||||
|
self.request = request
|
||||||
self.page_size = self.get_page_size(request)
|
self.page_size = self.get_page_size(request)
|
||||||
if not self.page_size:
|
if not self.page_size:
|
||||||
return None
|
return None
|
||||||
|
@ -680,15 +677,12 @@ class CursorPagination(BasePagination):
|
||||||
|
|
||||||
def get_page_size(self, request):
|
def get_page_size(self, request):
|
||||||
if self.page_size_query_param:
|
if self.page_size_query_param:
|
||||||
try:
|
with contextlib.suppress(KeyError, ValueError):
|
||||||
return _positive_int(
|
return _positive_int(
|
||||||
request.query_params[self.page_size_query_param],
|
request.query_params[self.page_size_query_param],
|
||||||
strict=True,
|
strict=True,
|
||||||
cutoff=self.max_page_size
|
cutoff=self.max_page_size
|
||||||
)
|
)
|
||||||
except (KeyError, ValueError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
return self.page_size
|
return self.page_size
|
||||||
|
|
||||||
def get_next_link(self):
|
def get_next_link(self):
|
||||||
|
@ -905,10 +899,16 @@ class CursorPagination(BasePagination):
|
||||||
'next': {
|
'next': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'nullable': True,
|
'nullable': True,
|
||||||
|
'format': 'uri',
|
||||||
|
'example': 'http://api.example.org/accounts/?{cursor_query_param}=cD00ODY%3D"'.format(
|
||||||
|
cursor_query_param=self.cursor_query_param)
|
||||||
},
|
},
|
||||||
'previous': {
|
'previous': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'nullable': True,
|
'nullable': True,
|
||||||
|
'format': 'uri',
|
||||||
|
'example': 'http://api.example.org/accounts/?{cursor_query_param}=cj0xJnA9NDg3'.format(
|
||||||
|
cursor_query_param=self.cursor_query_param)
|
||||||
},
|
},
|
||||||
'results': schema,
|
'results': schema,
|
||||||
},
|
},
|
||||||
|
|
|
@ -4,7 +4,9 @@ Parsers are used to parse the content of incoming HTTP requests.
|
||||||
They give us a generic way of being able to handle various media types
|
They give us a generic way of being able to handle various media types
|
||||||
on the request, such as form content or json encoded data.
|
on the request, such as form content or json encoded data.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import codecs
|
import codecs
|
||||||
|
import contextlib
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core.files.uploadhandler import StopFutureHandlers
|
from django.core.files.uploadhandler import StopFutureHandlers
|
||||||
|
@ -193,17 +195,12 @@ class FileUploadParser(BaseParser):
|
||||||
Detects the uploaded file name. First searches a 'filename' url kwarg.
|
Detects the uploaded file name. First searches a 'filename' url kwarg.
|
||||||
Then tries to parse Content-Disposition header.
|
Then tries to parse Content-Disposition header.
|
||||||
"""
|
"""
|
||||||
try:
|
with contextlib.suppress(KeyError):
|
||||||
return parser_context['kwargs']['filename']
|
return parser_context['kwargs']['filename']
|
||||||
except KeyError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
try:
|
with contextlib.suppress(AttributeError, KeyError, ValueError):
|
||||||
meta = parser_context['request'].META
|
meta = parser_context['request'].META
|
||||||
disposition, params = parse_header_parameters(meta['HTTP_CONTENT_DISPOSITION'])
|
disposition, params = parse_header_parameters(meta['HTTP_CONTENT_DISPOSITION'])
|
||||||
if 'filename*' in params:
|
if 'filename*' in params:
|
||||||
return params['filename*']
|
return params['filename*']
|
||||||
else:
|
return params['filename']
|
||||||
return params['filename']
|
|
||||||
except (AttributeError, KeyError, ValueError):
|
|
||||||
pass
|
|
||||||
|
|
|
@ -46,6 +46,14 @@ class OperandHolder(OperationHolderMixin):
|
||||||
op2 = self.op2_class(*args, **kwargs)
|
op2 = self.op2_class(*args, **kwargs)
|
||||||
return self.operator_class(op1, op2)
|
return self.operator_class(op1, op2)
|
||||||
|
|
||||||
|
def __eq__(self, other):
|
||||||
|
return (
|
||||||
|
isinstance(other, OperandHolder) and
|
||||||
|
self.operator_class == other.operator_class and
|
||||||
|
self.op1_class == other.op1_class and
|
||||||
|
self.op2_class == other.op2_class
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class AND:
|
class AND:
|
||||||
def __init__(self, op1, op2):
|
def __init__(self, op1, op2):
|
||||||
|
@ -78,8 +86,11 @@ class OR:
|
||||||
|
|
||||||
def has_object_permission(self, request, view, obj):
|
def has_object_permission(self, request, view, obj):
|
||||||
return (
|
return (
|
||||||
self.op1.has_object_permission(request, view, obj) or
|
self.op1.has_permission(request, view)
|
||||||
self.op2.has_object_permission(request, view, obj)
|
and self.op1.has_object_permission(request, view, obj)
|
||||||
|
) or (
|
||||||
|
self.op2.has_permission(request, view)
|
||||||
|
and self.op2.has_object_permission(request, view, obj)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
import contextlib
|
||||||
import sys
|
import sys
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
from urllib import parse
|
from urllib import parse
|
||||||
|
@ -170,7 +171,7 @@ class RelatedField(Field):
|
||||||
def get_attribute(self, instance):
|
def get_attribute(self, instance):
|
||||||
if self.use_pk_only_optimization() and self.source_attrs:
|
if self.use_pk_only_optimization() and self.source_attrs:
|
||||||
# Optimized case, return a mock object only containing the pk attribute.
|
# Optimized case, return a mock object only containing the pk attribute.
|
||||||
try:
|
with contextlib.suppress(AttributeError):
|
||||||
attribute_instance = get_attribute(instance, self.source_attrs[:-1])
|
attribute_instance = get_attribute(instance, self.source_attrs[:-1])
|
||||||
value = attribute_instance.serializable_value(self.source_attrs[-1])
|
value = attribute_instance.serializable_value(self.source_attrs[-1])
|
||||||
if is_simple_callable(value):
|
if is_simple_callable(value):
|
||||||
|
@ -183,9 +184,6 @@ class RelatedField(Field):
|
||||||
value = getattr(value, 'pk', value)
|
value = getattr(value, 'pk', value)
|
||||||
|
|
||||||
return PKOnlyObject(pk=value)
|
return PKOnlyObject(pk=value)
|
||||||
except AttributeError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Standard case, return the object instance.
|
# Standard case, return the object instance.
|
||||||
return super().get_attribute(instance)
|
return super().get_attribute(instance)
|
||||||
|
|
||||||
|
|
|
@ -6,7 +6,9 @@ on the response, such as JSON encoded data or HTML output.
|
||||||
|
|
||||||
REST framework also provides an HTML renderer that renders the browsable API.
|
REST framework also provides an HTML renderer that renders the browsable API.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
|
import contextlib
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
from urllib import parse
|
from urllib import parse
|
||||||
|
|
||||||
|
@ -72,11 +74,8 @@ class JSONRenderer(BaseRenderer):
|
||||||
# then pretty print the result.
|
# then pretty print the result.
|
||||||
# Note that we coerce `indent=0` into `indent=None`.
|
# Note that we coerce `indent=0` into `indent=None`.
|
||||||
base_media_type, params = parse_header_parameters(accepted_media_type)
|
base_media_type, params = parse_header_parameters(accepted_media_type)
|
||||||
try:
|
with contextlib.suppress(KeyError, ValueError, TypeError):
|
||||||
return zero_as_none(max(min(int(params['indent']), 8), 0))
|
return zero_as_none(max(min(int(params['indent']), 8), 0))
|
||||||
except (KeyError, ValueError, TypeError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
# If 'indent' is provided in the context, then pretty print the result.
|
# If 'indent' is provided in the context, then pretty print the result.
|
||||||
# E.g. If we're being called by the BrowsableAPIRenderer.
|
# E.g. If we're being called by the BrowsableAPIRenderer.
|
||||||
return renderer_context.get('indent', None)
|
return renderer_context.get('indent', None)
|
||||||
|
@ -488,11 +487,8 @@ class BrowsableAPIRenderer(BaseRenderer):
|
||||||
return
|
return
|
||||||
|
|
||||||
if existing_serializer is not None:
|
if existing_serializer is not None:
|
||||||
try:
|
with contextlib.suppress(TypeError):
|
||||||
return self.render_form_for_serializer(existing_serializer)
|
return self.render_form_for_serializer(existing_serializer)
|
||||||
except TypeError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
if has_serializer:
|
if has_serializer:
|
||||||
if method in ('PUT', 'PATCH'):
|
if method in ('PUT', 'PATCH'):
|
||||||
serializer = view.get_serializer(instance=instance, **kwargs)
|
serializer = view.get_serializer(instance=instance, **kwargs)
|
||||||
|
|
|
@ -413,7 +413,8 @@ class Request:
|
||||||
to proxy it to the underlying HttpRequest object.
|
to proxy it to the underlying HttpRequest object.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
return getattr(self._request, attr)
|
_request = self.__getattribute__("_request")
|
||||||
|
return getattr(_request, attr)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
return self.__getattribute__(attr)
|
return self.__getattribute__(attr)
|
||||||
|
|
||||||
|
|
|
@ -88,7 +88,7 @@ class ViewInspector:
|
||||||
view.get_view_description())
|
view.get_view_description())
|
||||||
|
|
||||||
def _get_description_section(self, view, header, description):
|
def _get_description_section(self, view, header, description):
|
||||||
lines = [line for line in description.splitlines()]
|
lines = description.splitlines()
|
||||||
current_section = ''
|
current_section = ''
|
||||||
sections = {'': ''}
|
sections = {'': ''}
|
||||||
|
|
||||||
|
|
|
@ -13,7 +13,7 @@ from django.db import models
|
||||||
from django.utils.encoding import force_str
|
from django.utils.encoding import force_str
|
||||||
|
|
||||||
from rest_framework import (
|
from rest_framework import (
|
||||||
RemovedInDRF314Warning, exceptions, renderers, serializers
|
RemovedInDRF315Warning, exceptions, renderers, serializers
|
||||||
)
|
)
|
||||||
from rest_framework.compat import uritemplate
|
from rest_framework.compat import uritemplate
|
||||||
from rest_framework.fields import _UnvalidatedField, empty
|
from rest_framework.fields import _UnvalidatedField, empty
|
||||||
|
@ -523,7 +523,7 @@ class AutoSchema(ViewInspector):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if field.required:
|
if field.required:
|
||||||
required.append(field.field_name)
|
required.append(self.get_field_name(field))
|
||||||
|
|
||||||
schema = self.map_field(field)
|
schema = self.map_field(field)
|
||||||
if field.read_only:
|
if field.read_only:
|
||||||
|
@ -538,7 +538,7 @@ class AutoSchema(ViewInspector):
|
||||||
schema['description'] = str(field.help_text)
|
schema['description'] = str(field.help_text)
|
||||||
self.map_field_validators(field, schema)
|
self.map_field_validators(field, schema)
|
||||||
|
|
||||||
properties[field.field_name] = schema
|
properties[self.get_field_name(field)] = schema
|
||||||
|
|
||||||
result = {
|
result = {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
|
@ -589,6 +589,13 @@ class AutoSchema(ViewInspector):
|
||||||
schema['maximum'] = int(digits * '9') + 1
|
schema['maximum'] = int(digits * '9') + 1
|
||||||
schema['minimum'] = -schema['maximum']
|
schema['minimum'] = -schema['maximum']
|
||||||
|
|
||||||
|
def get_field_name(self, field):
|
||||||
|
"""
|
||||||
|
Override this method if you want to change schema field name.
|
||||||
|
For example, convert snake_case field name to camelCase.
|
||||||
|
"""
|
||||||
|
return field.field_name
|
||||||
|
|
||||||
def get_paginator(self):
|
def get_paginator(self):
|
||||||
pagination_class = getattr(self.view, 'pagination_class', None)
|
pagination_class = getattr(self.view, 'pagination_class', None)
|
||||||
if pagination_class:
|
if pagination_class:
|
||||||
|
@ -713,106 +720,10 @@ class AutoSchema(ViewInspector):
|
||||||
|
|
||||||
return [path.split('/')[0].replace('_', '-')]
|
return [path.split('/')[0].replace('_', '-')]
|
||||||
|
|
||||||
def _get_path_parameters(self, path, method):
|
|
||||||
warnings.warn(
|
|
||||||
"Method `_get_path_parameters()` has been renamed to `get_path_parameters()`. "
|
|
||||||
"The old name will be removed in DRF v3.14.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
return self.get_path_parameters(path, method)
|
|
||||||
|
|
||||||
def _get_filter_parameters(self, path, method):
|
|
||||||
warnings.warn(
|
|
||||||
"Method `_get_filter_parameters()` has been renamed to `get_filter_parameters()`. "
|
|
||||||
"The old name will be removed in DRF v3.14.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
return self.get_filter_parameters(path, method)
|
|
||||||
|
|
||||||
def _get_responses(self, path, method):
|
|
||||||
warnings.warn(
|
|
||||||
"Method `_get_responses()` has been renamed to `get_responses()`. "
|
|
||||||
"The old name will be removed in DRF v3.14.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
return self.get_responses(path, method)
|
|
||||||
|
|
||||||
def _get_request_body(self, path, method):
|
|
||||||
warnings.warn(
|
|
||||||
"Method `_get_request_body()` has been renamed to `get_request_body()`. "
|
|
||||||
"The old name will be removed in DRF v3.14.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
return self.get_request_body(path, method)
|
|
||||||
|
|
||||||
def _get_serializer(self, path, method):
|
|
||||||
warnings.warn(
|
|
||||||
"Method `_get_serializer()` has been renamed to `get_serializer()`. "
|
|
||||||
"The old name will be removed in DRF v3.14.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
return self.get_serializer(path, method)
|
|
||||||
|
|
||||||
def _get_paginator(self):
|
|
||||||
warnings.warn(
|
|
||||||
"Method `_get_paginator()` has been renamed to `get_paginator()`. "
|
|
||||||
"The old name will be removed in DRF v3.14.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
return self.get_paginator()
|
|
||||||
|
|
||||||
def _map_field_validators(self, field, schema):
|
|
||||||
warnings.warn(
|
|
||||||
"Method `_map_field_validators()` has been renamed to `map_field_validators()`. "
|
|
||||||
"The old name will be removed in DRF v3.14.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
return self.map_field_validators(field, schema)
|
|
||||||
|
|
||||||
def _map_serializer(self, serializer):
|
|
||||||
warnings.warn(
|
|
||||||
"Method `_map_serializer()` has been renamed to `map_serializer()`. "
|
|
||||||
"The old name will be removed in DRF v3.14.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
return self.map_serializer(serializer)
|
|
||||||
|
|
||||||
def _map_field(self, field):
|
|
||||||
warnings.warn(
|
|
||||||
"Method `_map_field()` has been renamed to `map_field()`. "
|
|
||||||
"The old name will be removed in DRF v3.14.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
return self.map_field(field)
|
|
||||||
|
|
||||||
def _map_choicefield(self, field):
|
|
||||||
warnings.warn(
|
|
||||||
"Method `_map_choicefield()` has been renamed to `map_choicefield()`. "
|
|
||||||
"The old name will be removed in DRF v3.14.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
return self.map_choicefield(field)
|
|
||||||
|
|
||||||
def _get_pagination_parameters(self, path, method):
|
|
||||||
warnings.warn(
|
|
||||||
"Method `_get_pagination_parameters()` has been renamed to `get_pagination_parameters()`. "
|
|
||||||
"The old name will be removed in DRF v3.14.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
return self.get_pagination_parameters(path, method)
|
|
||||||
|
|
||||||
def _allows_filters(self, path, method):
|
|
||||||
warnings.warn(
|
|
||||||
"Method `_allows_filters()` has been renamed to `allows_filters()`. "
|
|
||||||
"The old name will be removed in DRF v3.14.",
|
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
|
||||||
)
|
|
||||||
return self.allows_filters(path, method)
|
|
||||||
|
|
||||||
def _get_reference(self, serializer):
|
def _get_reference(self, serializer):
|
||||||
warnings.warn(
|
warnings.warn(
|
||||||
"Method `_get_reference()` has been renamed to `get_reference()`. "
|
"Method `_get_reference()` has been renamed to `get_reference()`. "
|
||||||
"The old name will be removed in DRF v3.14.",
|
"The old name will be removed in DRF v3.15.",
|
||||||
RemovedInDRF314Warning, stacklevel=2
|
RemovedInDRF315Warning, stacklevel=2
|
||||||
)
|
)
|
||||||
return self.get_reference(serializer)
|
return self.get_reference(serializer)
|
||||||
|
|
|
@ -10,6 +10,8 @@ python primitives.
|
||||||
2. The process of marshalling between python primitives and request and
|
2. The process of marshalling between python primitives and request and
|
||||||
response content is handled by parsers and renderers.
|
response content is handled by parsers and renderers.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import contextlib
|
||||||
import copy
|
import copy
|
||||||
import inspect
|
import inspect
|
||||||
import traceback
|
import traceback
|
||||||
|
@ -52,7 +54,7 @@ from rest_framework.fields import ( # NOQA # isort:skip
|
||||||
BooleanField, CharField, ChoiceField, DateField, DateTimeField, DecimalField,
|
BooleanField, CharField, ChoiceField, DateField, DateTimeField, DecimalField,
|
||||||
DictField, DurationField, EmailField, Field, FileField, FilePathField, FloatField,
|
DictField, DurationField, EmailField, Field, FileField, FilePathField, FloatField,
|
||||||
HiddenField, HStoreField, IPAddressField, ImageField, IntegerField, JSONField,
|
HiddenField, HStoreField, IPAddressField, ImageField, IntegerField, JSONField,
|
||||||
ListField, ModelField, MultipleChoiceField, NullBooleanField, ReadOnlyField,
|
ListField, ModelField, MultipleChoiceField, ReadOnlyField,
|
||||||
RegexField, SerializerMethodField, SlugField, TimeField, URLField, UUIDField,
|
RegexField, SerializerMethodField, SlugField, TimeField, URLField, UUIDField,
|
||||||
)
|
)
|
||||||
from rest_framework.relations import ( # NOQA # isort:skip
|
from rest_framework.relations import ( # NOQA # isort:skip
|
||||||
|
@ -1496,12 +1498,10 @@ class ModelSerializer(Serializer):
|
||||||
# they can't be nested attribute lookups.
|
# they can't be nested attribute lookups.
|
||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
with contextlib.suppress(FieldDoesNotExist):
|
||||||
field = model._meta.get_field(source)
|
field = model._meta.get_field(source)
|
||||||
if isinstance(field, DjangoModelField):
|
if isinstance(field, DjangoModelField):
|
||||||
model_fields[source] = field
|
model_fields[source] = field
|
||||||
except FieldDoesNotExist:
|
|
||||||
pass
|
|
||||||
|
|
||||||
return model_fields
|
return model_fields
|
||||||
|
|
||||||
|
|
|
@ -19,7 +19,9 @@ REST framework settings, checking for user settings first, then falling
|
||||||
back to the defaults.
|
back to the defaults.
|
||||||
"""
|
"""
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.test.signals import setting_changed
|
# Import from `django.core.signals` instead of the official location
|
||||||
|
# `django.test.signals` to avoid importing the test module unnecessarily.
|
||||||
|
from django.core.signals import setting_changed
|
||||||
from django.utils.module_loading import import_string
|
from django.utils.module_loading import import_string
|
||||||
|
|
||||||
from rest_framework import ISO_8601
|
from rest_framework import ISO_8601
|
||||||
|
|
|
@ -131,13 +131,7 @@ $(function () {
|
||||||
if (value !== undefined) {
|
if (value !== undefined) {
|
||||||
params[paramKey] = value
|
params[paramKey] = value
|
||||||
}
|
}
|
||||||
} else if (dataType === 'array' && paramValue) {
|
} else if ((dataType === 'array' && paramValue) || (dataType === 'object' && paramValue)) {
|
||||||
try {
|
|
||||||
params[paramKey] = JSON.parse(paramValue)
|
|
||||||
} catch (err) {
|
|
||||||
// Ignore malformed JSON
|
|
||||||
}
|
|
||||||
} else if (dataType === 'object' && paramValue) {
|
|
||||||
try {
|
try {
|
||||||
params[paramKey] = JSON.parse(paramValue)
|
params[paramKey] = JSON.parse(paramValue)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|
|
@ -277,7 +277,7 @@ class APIClient(APIRequestFactory, DjangoClient):
|
||||||
"""
|
"""
|
||||||
self.handler._force_user = user
|
self.handler._force_user = user
|
||||||
self.handler._force_token = token
|
self.handler._force_token = token
|
||||||
if user is None:
|
if user is None and token is None:
|
||||||
self.logout() # Also clear any possible session info if required
|
self.logout() # Also clear any possible session info if required
|
||||||
|
|
||||||
def request(self, **kwargs):
|
def request(self, **kwargs):
|
||||||
|
|
|
@ -1,6 +1,8 @@
|
||||||
"""
|
"""
|
||||||
Helper classes for parsers.
|
Helper classes for parsers.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import contextlib
|
||||||
import datetime
|
import datetime
|
||||||
import decimal
|
import decimal
|
||||||
import json # noqa
|
import json # noqa
|
||||||
|
@ -58,10 +60,8 @@ class JSONEncoder(json.JSONEncoder):
|
||||||
)
|
)
|
||||||
elif hasattr(obj, '__getitem__'):
|
elif hasattr(obj, '__getitem__'):
|
||||||
cls = (list if isinstance(obj, (list, tuple)) else dict)
|
cls = (list if isinstance(obj, (list, tuple)) else dict)
|
||||||
try:
|
with contextlib.suppress(Exception):
|
||||||
return cls(obj)
|
return cls(obj)
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
elif hasattr(obj, '__iter__'):
|
elif hasattr(obj, '__iter__'):
|
||||||
return tuple(item for item in obj)
|
return tuple(item for item in obj)
|
||||||
return super().default(obj)
|
return super().default(obj)
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
import contextlib
|
||||||
import sys
|
import sys
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
from collections.abc import Mapping, MutableMapping
|
from collections.abc import Mapping, MutableMapping
|
||||||
|
@ -103,15 +104,13 @@ class JSONBoundField(BoundField):
|
||||||
# When HTML form input is used and the input is not valid
|
# When HTML form input is used and the input is not valid
|
||||||
# value will be a JSONString, rather than a JSON primitive.
|
# value will be a JSONString, rather than a JSON primitive.
|
||||||
if not getattr(value, 'is_json_string', False):
|
if not getattr(value, 'is_json_string', False):
|
||||||
try:
|
with contextlib.suppress(TypeError, ValueError):
|
||||||
value = json.dumps(
|
value = json.dumps(
|
||||||
self.value,
|
self.value,
|
||||||
sort_keys=True,
|
sort_keys=True,
|
||||||
indent=4,
|
indent=4,
|
||||||
separators=(',', ': '),
|
separators=(',', ': '),
|
||||||
)
|
)
|
||||||
except (TypeError, ValueError):
|
|
||||||
pass
|
|
||||||
return self.__class__(self._field, value, self.errors, self._prefix)
|
return self.__class__(self._field, value, self.errors, self._prefix)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -79,9 +79,9 @@ def exception_handler(exc, context):
|
||||||
to be raised.
|
to be raised.
|
||||||
"""
|
"""
|
||||||
if isinstance(exc, Http404):
|
if isinstance(exc, Http404):
|
||||||
exc = exceptions.NotFound()
|
exc = exceptions.NotFound(*(exc.args))
|
||||||
elif isinstance(exc, PermissionDenied):
|
elif isinstance(exc, PermissionDenied):
|
||||||
exc = exceptions.PermissionDenied()
|
exc = exceptions.PermissionDenied(*(exc.args))
|
||||||
|
|
||||||
if isinstance(exc, exceptions.APIException):
|
if isinstance(exc, exceptions.APIException):
|
||||||
headers = {}
|
headers = {}
|
||||||
|
|
|
@ -5,7 +5,7 @@ license_files = LICENSE.md
|
||||||
addopts=--tb=short --strict-markers -ra
|
addopts=--tb=short --strict-markers -ra
|
||||||
|
|
||||||
[flake8]
|
[flake8]
|
||||||
ignore = E501,W504
|
ignore = E501,W503,W504
|
||||||
banned-modules = json = use from rest_framework.utils import json!
|
banned-modules = json = use from rest_framework.utils import json!
|
||||||
|
|
||||||
[isort]
|
[isort]
|
||||||
|
|
4
setup.py
4
setup.py
|
@ -82,14 +82,13 @@ setup(
|
||||||
author_email='tom@tomchristie.com', # SEE NOTE BELOW (*)
|
author_email='tom@tomchristie.com', # SEE NOTE BELOW (*)
|
||||||
packages=find_packages(exclude=['tests*']),
|
packages=find_packages(exclude=['tests*']),
|
||||||
include_package_data=True,
|
include_package_data=True,
|
||||||
install_requires=["django>=2.2", "pytz"],
|
install_requires=["django>=3.0", "pytz"],
|
||||||
python_requires=">=3.6",
|
python_requires=">=3.6",
|
||||||
zip_safe=False,
|
zip_safe=False,
|
||||||
classifiers=[
|
classifiers=[
|
||||||
'Development Status :: 5 - Production/Stable',
|
'Development Status :: 5 - Production/Stable',
|
||||||
'Environment :: Web Environment',
|
'Environment :: Web Environment',
|
||||||
'Framework :: Django',
|
'Framework :: Django',
|
||||||
'Framework :: Django :: 2.2',
|
|
||||||
'Framework :: Django :: 3.0',
|
'Framework :: Django :: 3.0',
|
||||||
'Framework :: Django :: 3.1',
|
'Framework :: Django :: 3.1',
|
||||||
'Framework :: Django :: 3.2',
|
'Framework :: Django :: 3.2',
|
||||||
|
@ -105,6 +104,7 @@ setup(
|
||||||
'Programming Language :: Python :: 3.8',
|
'Programming Language :: Python :: 3.8',
|
||||||
'Programming Language :: Python :: 3.9',
|
'Programming Language :: Python :: 3.9',
|
||||||
'Programming Language :: Python :: 3.10',
|
'Programming Language :: Python :: 3.10',
|
||||||
|
'Programming Language :: Python :: 3.11',
|
||||||
'Programming Language :: Python :: 3 :: Only',
|
'Programming Language :: Python :: 3 :: Only',
|
||||||
'Topic :: Internet :: WWW/HTTP',
|
'Topic :: Internet :: WWW/HTTP',
|
||||||
],
|
],
|
||||||
|
|
|
@ -219,8 +219,8 @@ class SessionAuthTests(TestCase):
|
||||||
Ensure POSTing form over session authentication with CSRF token succeeds.
|
Ensure POSTing form over session authentication with CSRF token succeeds.
|
||||||
Regression test for #6088
|
Regression test for #6088
|
||||||
"""
|
"""
|
||||||
# Remove this shim when dropping support for Django 2.2.
|
# Remove this shim when dropping support for Django 3.0.
|
||||||
if django.VERSION < (3, 0):
|
if django.VERSION < (3, 1):
|
||||||
from django.middleware.csrf import _get_new_csrf_token
|
from django.middleware.csrf import _get_new_csrf_token
|
||||||
else:
|
else:
|
||||||
from django.middleware.csrf import (
|
from django.middleware.csrf import (
|
||||||
|
|
|
@ -111,6 +111,20 @@ class TestFieldMapping(TestCase):
|
||||||
assert data['properties']['default_false']['default'] is False, "default must be false"
|
assert data['properties']['default_false']['default'] is False, "default must be false"
|
||||||
assert 'default' not in data['properties']['without_default'], "default must not be defined"
|
assert 'default' not in data['properties']['without_default'], "default must not be defined"
|
||||||
|
|
||||||
|
def test_custom_field_name(self):
|
||||||
|
class CustomSchema(AutoSchema):
|
||||||
|
def get_field_name(self, field):
|
||||||
|
return 'custom_' + field.field_name
|
||||||
|
|
||||||
|
class Serializer(serializers.Serializer):
|
||||||
|
text_field = serializers.CharField()
|
||||||
|
|
||||||
|
inspector = CustomSchema()
|
||||||
|
|
||||||
|
data = inspector.map_serializer(Serializer())
|
||||||
|
assert 'custom_text_field' in data['properties']
|
||||||
|
assert 'text_field' not in data['properties']
|
||||||
|
|
||||||
def test_nullable_fields(self):
|
def test_nullable_fields(self):
|
||||||
class Model(models.Model):
|
class Model(models.Model):
|
||||||
rw_field = models.CharField(null=True)
|
rw_field = models.CharField(null=True)
|
||||||
|
|
|
@ -239,7 +239,7 @@ class TestSource:
|
||||||
|
|
||||||
|
|
||||||
class TestReadOnly:
|
class TestReadOnly:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class TestSerializer(serializers.Serializer):
|
class TestSerializer(serializers.Serializer):
|
||||||
read_only = serializers.ReadOnlyField(default="789")
|
read_only = serializers.ReadOnlyField(default="789")
|
||||||
writable = serializers.IntegerField()
|
writable = serializers.IntegerField()
|
||||||
|
@ -271,7 +271,7 @@ class TestReadOnly:
|
||||||
|
|
||||||
|
|
||||||
class TestWriteOnly:
|
class TestWriteOnly:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class TestSerializer(serializers.Serializer):
|
class TestSerializer(serializers.Serializer):
|
||||||
write_only = serializers.IntegerField(write_only=True)
|
write_only = serializers.IntegerField(write_only=True)
|
||||||
readable = serializers.IntegerField()
|
readable = serializers.IntegerField()
|
||||||
|
@ -296,7 +296,7 @@ class TestWriteOnly:
|
||||||
|
|
||||||
|
|
||||||
class TestInitial:
|
class TestInitial:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class TestSerializer(serializers.Serializer):
|
class TestSerializer(serializers.Serializer):
|
||||||
initial_field = serializers.IntegerField(initial=123)
|
initial_field = serializers.IntegerField(initial=123)
|
||||||
blank_field = serializers.IntegerField()
|
blank_field = serializers.IntegerField()
|
||||||
|
@ -313,7 +313,7 @@ class TestInitial:
|
||||||
|
|
||||||
|
|
||||||
class TestInitialWithCallable:
|
class TestInitialWithCallable:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
def initial_value():
|
def initial_value():
|
||||||
return 123
|
return 123
|
||||||
|
|
||||||
|
@ -331,7 +331,7 @@ class TestInitialWithCallable:
|
||||||
|
|
||||||
|
|
||||||
class TestLabel:
|
class TestLabel:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class TestSerializer(serializers.Serializer):
|
class TestSerializer(serializers.Serializer):
|
||||||
labeled = serializers.IntegerField(label='My label')
|
labeled = serializers.IntegerField(label='My label')
|
||||||
self.serializer = TestSerializer()
|
self.serializer = TestSerializer()
|
||||||
|
@ -345,7 +345,7 @@ class TestLabel:
|
||||||
|
|
||||||
|
|
||||||
class TestInvalidErrorKey:
|
class TestInvalidErrorKey:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class ExampleField(serializers.Field):
|
class ExampleField(serializers.Field):
|
||||||
def to_native(self, data):
|
def to_native(self, data):
|
||||||
self.fail('incorrect')
|
self.fail('incorrect')
|
||||||
|
@ -539,7 +539,7 @@ class TestHTMLInput:
|
||||||
|
|
||||||
|
|
||||||
class TestCreateOnlyDefault:
|
class TestCreateOnlyDefault:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
default = serializers.CreateOnlyDefault('2001-01-01')
|
default = serializers.CreateOnlyDefault('2001-01-01')
|
||||||
|
|
||||||
class TestSerializer(serializers.Serializer):
|
class TestSerializer(serializers.Serializer):
|
||||||
|
@ -679,9 +679,9 @@ class TestBooleanField(FieldValues):
|
||||||
assert exc_info.value.detail == expected
|
assert exc_info.value.detail == expected
|
||||||
|
|
||||||
|
|
||||||
class TestNullBooleanField(TestBooleanField):
|
class TestNullableBooleanField(TestBooleanField):
|
||||||
"""
|
"""
|
||||||
Valid and invalid values for `NullBooleanField`.
|
Valid and invalid values for `BooleanField` when `allow_null=True`.
|
||||||
"""
|
"""
|
||||||
valid_inputs = {
|
valid_inputs = {
|
||||||
'true': True,
|
'true': True,
|
||||||
|
@ -706,16 +706,6 @@ class TestNullBooleanField(TestBooleanField):
|
||||||
field = serializers.BooleanField(allow_null=True)
|
field = serializers.BooleanField(allow_null=True)
|
||||||
|
|
||||||
|
|
||||||
class TestNullableBooleanField(TestNullBooleanField):
|
|
||||||
"""
|
|
||||||
Valid and invalid values for `BooleanField` when `allow_null=True`.
|
|
||||||
"""
|
|
||||||
|
|
||||||
@property
|
|
||||||
def field(self):
|
|
||||||
return serializers.BooleanField(allow_null=True)
|
|
||||||
|
|
||||||
|
|
||||||
# String types...
|
# String types...
|
||||||
|
|
||||||
class TestCharField(FieldValues):
|
class TestCharField(FieldValues):
|
||||||
|
@ -1261,6 +1251,27 @@ class TestQuantizedValueForDecimal(TestCase):
|
||||||
assert value == expected_digit_tuple
|
assert value == expected_digit_tuple
|
||||||
|
|
||||||
|
|
||||||
|
class TestNormalizedOutputValueDecimalField(TestCase):
|
||||||
|
"""
|
||||||
|
Test that we get the expected behavior of on DecimalField when normalize=True
|
||||||
|
"""
|
||||||
|
|
||||||
|
def test_normalize_output(self):
|
||||||
|
field = serializers.DecimalField(max_digits=4, decimal_places=3, normalize_output=True)
|
||||||
|
output = field.to_representation(Decimal('1.000'))
|
||||||
|
assert output == '1'
|
||||||
|
|
||||||
|
def test_non_normalize_output(self):
|
||||||
|
field = serializers.DecimalField(max_digits=4, decimal_places=3, normalize_output=False)
|
||||||
|
output = field.to_representation(Decimal('1.000'))
|
||||||
|
assert output == '1.000'
|
||||||
|
|
||||||
|
def test_normalize_coeherce_to_string(self):
|
||||||
|
field = serializers.DecimalField(max_digits=4, decimal_places=3, normalize_output=True, coerce_to_string=False)
|
||||||
|
output = field.to_representation(Decimal('1.000'))
|
||||||
|
assert output == Decimal('1')
|
||||||
|
|
||||||
|
|
||||||
class TestNoDecimalPlaces(FieldValues):
|
class TestNoDecimalPlaces(FieldValues):
|
||||||
valid_inputs = {
|
valid_inputs = {
|
||||||
'0.12345': Decimal('0.12345'),
|
'0.12345': Decimal('0.12345'),
|
||||||
|
|
|
@ -5,6 +5,7 @@ from django.shortcuts import get_object_or_404
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
|
|
||||||
from rest_framework import generics, renderers, serializers, status
|
from rest_framework import generics, renderers, serializers, status
|
||||||
|
from rest_framework.exceptions import ErrorDetail
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.test import APIRequestFactory
|
from rest_framework.test import APIRequestFactory
|
||||||
from tests.models import (
|
from tests.models import (
|
||||||
|
@ -519,7 +520,12 @@ class TestFilterBackendAppliedToViews(TestCase):
|
||||||
request = factory.get('/1')
|
request = factory.get('/1')
|
||||||
response = instance_view(request, pk=1).render()
|
response = instance_view(request, pk=1).render()
|
||||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||||
assert response.data == {'detail': 'Not found.'}
|
assert response.data == {
|
||||||
|
'detail': ErrorDetail(
|
||||||
|
string='No BasicModel matches the given query.',
|
||||||
|
code='not_found'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
def test_get_instance_view_will_return_single_object_when_filter_does_not_exclude_it(self):
|
def test_get_instance_view_will_return_single_object_when_filter_does_not_exclude_it(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -18,7 +18,7 @@ class TestPaginationIntegration:
|
||||||
Integration tests.
|
Integration tests.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class PassThroughSerializer(serializers.BaseSerializer):
|
class PassThroughSerializer(serializers.BaseSerializer):
|
||||||
def to_representation(self, item):
|
def to_representation(self, item):
|
||||||
return item
|
return item
|
||||||
|
@ -140,7 +140,7 @@ class TestPaginationDisabledIntegration:
|
||||||
Integration tests for disabled pagination.
|
Integration tests for disabled pagination.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class PassThroughSerializer(serializers.BaseSerializer):
|
class PassThroughSerializer(serializers.BaseSerializer):
|
||||||
def to_representation(self, item):
|
def to_representation(self, item):
|
||||||
return item
|
return item
|
||||||
|
@ -163,7 +163,7 @@ class TestPageNumberPagination:
|
||||||
Unit tests for `pagination.PageNumberPagination`.
|
Unit tests for `pagination.PageNumberPagination`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class ExamplePagination(pagination.PageNumberPagination):
|
class ExamplePagination(pagination.PageNumberPagination):
|
||||||
page_size = 5
|
page_size = 5
|
||||||
|
|
||||||
|
@ -302,7 +302,7 @@ class TestPageNumberPaginationOverride:
|
||||||
the Django Paginator Class is overridden.
|
the Django Paginator Class is overridden.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class OverriddenDjangoPaginator(DjangoPaginator):
|
class OverriddenDjangoPaginator(DjangoPaginator):
|
||||||
# override the count in our overridden Django Paginator
|
# override the count in our overridden Django Paginator
|
||||||
# we will only return one page, with one item
|
# we will only return one page, with one item
|
||||||
|
@ -358,7 +358,7 @@ class TestLimitOffset:
|
||||||
Unit tests for `pagination.LimitOffsetPagination`.
|
Unit tests for `pagination.LimitOffsetPagination`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class ExamplePagination(pagination.LimitOffsetPagination):
|
class ExamplePagination(pagination.LimitOffsetPagination):
|
||||||
default_limit = 10
|
default_limit = 10
|
||||||
max_limit = 15
|
max_limit = 15
|
||||||
|
@ -922,10 +922,14 @@ class CursorPaginationTestsMixin:
|
||||||
'next': {
|
'next': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'nullable': True,
|
'nullable': True,
|
||||||
|
'format': 'uri',
|
||||||
|
'example': 'http://api.example.org/accounts/?cursor=cD00ODY%3D"'
|
||||||
},
|
},
|
||||||
'previous': {
|
'previous': {
|
||||||
'type': 'string',
|
'type': 'string',
|
||||||
'nullable': True,
|
'nullable': True,
|
||||||
|
'format': 'uri',
|
||||||
|
'example': 'http://api.example.org/accounts/?cursor=cj0xJnA9NDg3'
|
||||||
},
|
},
|
||||||
'results': unpaginated_schema,
|
'results': unpaginated_schema,
|
||||||
},
|
},
|
||||||
|
@ -937,7 +941,7 @@ class TestCursorPagination(CursorPaginationTestsMixin):
|
||||||
Unit tests for `pagination.CursorPagination`.
|
Unit tests for `pagination.CursorPagination`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class MockObject:
|
class MockObject:
|
||||||
def __init__(self, idx):
|
def __init__(self, idx):
|
||||||
self.created = idx
|
self.created = idx
|
||||||
|
|
|
@ -635,7 +635,7 @@ class PermissionsCompositionTests(TestCase):
|
||||||
composed_perm = (permissions.IsAuthenticated | permissions.AllowAny)
|
composed_perm = (permissions.IsAuthenticated | permissions.AllowAny)
|
||||||
hasperm = composed_perm().has_object_permission(request, None, None)
|
hasperm = composed_perm().has_object_permission(request, None, None)
|
||||||
assert hasperm is True
|
assert hasperm is True
|
||||||
assert mock_deny.call_count == 1
|
assert mock_deny.call_count == 0
|
||||||
assert mock_allow.call_count == 1
|
assert mock_allow.call_count == 1
|
||||||
|
|
||||||
def test_and_lazyness(self):
|
def test_and_lazyness(self):
|
||||||
|
@ -677,3 +677,16 @@ class PermissionsCompositionTests(TestCase):
|
||||||
assert hasperm is False
|
assert hasperm is False
|
||||||
assert mock_deny.call_count == 1
|
assert mock_deny.call_count == 1
|
||||||
mock_allow.assert_not_called()
|
mock_allow.assert_not_called()
|
||||||
|
|
||||||
|
def test_unimplemented_has_object_permission(self):
|
||||||
|
"test for issue 6402 https://github.com/encode/django-rest-framework/issues/6402"
|
||||||
|
request = factory.get('/1', format='json')
|
||||||
|
request.user = AnonymousUser()
|
||||||
|
|
||||||
|
class IsAuthenticatedUserOwner(permissions.IsAuthenticated):
|
||||||
|
def has_object_permission(self, request, view, obj):
|
||||||
|
return True
|
||||||
|
|
||||||
|
composed_perm = (IsAuthenticatedUserOwner | permissions.IsAdminUser)
|
||||||
|
hasperm = composed_perm().has_object_permission(request, None, None)
|
||||||
|
assert hasperm is False
|
||||||
|
|
|
@ -374,7 +374,7 @@ class TestManyRelatedField(APISimpleTestCase):
|
||||||
|
|
||||||
|
|
||||||
class TestHyperlink:
|
class TestHyperlink:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
self.default_hyperlink = serializers.Hyperlink('http://example.com', 'test')
|
self.default_hyperlink = serializers.Hyperlink('http://example.com', 'test')
|
||||||
|
|
||||||
def test_can_be_pickled(self):
|
def test_can_be_pickled(self):
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
"""
|
"""
|
||||||
Tests for content parsing, and form-overloaded content parsing.
|
Tests for content parsing, and form-overloaded content parsing.
|
||||||
"""
|
"""
|
||||||
|
import copy
|
||||||
import os.path
|
import os.path
|
||||||
import tempfile
|
import tempfile
|
||||||
|
|
||||||
|
@ -344,3 +345,10 @@ class TestHttpRequest(TestCase):
|
||||||
# ensure that request stream was consumed by form parser
|
# ensure that request stream was consumed by form parser
|
||||||
assert request.content_type.startswith('multipart/form-data')
|
assert request.content_type.startswith('multipart/form-data')
|
||||||
assert response.data == {'a': ['b']}
|
assert response.data == {'a': ['b']}
|
||||||
|
|
||||||
|
|
||||||
|
class TestDeepcopy(TestCase):
|
||||||
|
|
||||||
|
def test_deepcopy_works(self):
|
||||||
|
request = Request(factory.get('/', secure=False))
|
||||||
|
copy.deepcopy(request)
|
||||||
|
|
|
@ -61,7 +61,7 @@ class TestFieldImports:
|
||||||
# -----------------------------
|
# -----------------------------
|
||||||
|
|
||||||
class TestSerializer:
|
class TestSerializer:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class ExampleSerializer(serializers.Serializer):
|
class ExampleSerializer(serializers.Serializer):
|
||||||
char = serializers.CharField()
|
char = serializers.CharField()
|
||||||
integer = serializers.IntegerField()
|
integer = serializers.IntegerField()
|
||||||
|
@ -240,7 +240,7 @@ class TestValidateMethod:
|
||||||
|
|
||||||
|
|
||||||
class TestBaseSerializer:
|
class TestBaseSerializer:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class ExampleSerializer(serializers.BaseSerializer):
|
class ExampleSerializer(serializers.BaseSerializer):
|
||||||
def to_representation(self, obj):
|
def to_representation(self, obj):
|
||||||
return {
|
return {
|
||||||
|
@ -337,7 +337,7 @@ class TestStarredSource:
|
||||||
'nested2': {'c': 3, 'd': 4}
|
'nested2': {'c': 3, 'd': 4}
|
||||||
}
|
}
|
||||||
|
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class NestedSerializer1(serializers.Serializer):
|
class NestedSerializer1(serializers.Serializer):
|
||||||
a = serializers.IntegerField()
|
a = serializers.IntegerField()
|
||||||
b = serializers.IntegerField()
|
b = serializers.IntegerField()
|
||||||
|
@ -463,7 +463,7 @@ class TestNotRequiredOutput:
|
||||||
|
|
||||||
|
|
||||||
class TestDefaultOutput:
|
class TestDefaultOutput:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class ExampleSerializer(serializers.Serializer):
|
class ExampleSerializer(serializers.Serializer):
|
||||||
has_default = serializers.CharField(default='x')
|
has_default = serializers.CharField(default='x')
|
||||||
has_default_callable = serializers.CharField(default=lambda: 'y')
|
has_default_callable = serializers.CharField(default=lambda: 'y')
|
||||||
|
@ -584,7 +584,7 @@ class TestCacheSerializerData:
|
||||||
|
|
||||||
|
|
||||||
class TestDefaultInclusions:
|
class TestDefaultInclusions:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class ExampleSerializer(serializers.Serializer):
|
class ExampleSerializer(serializers.Serializer):
|
||||||
char = serializers.CharField(default='abc')
|
char = serializers.CharField(default='abc')
|
||||||
integer = serializers.IntegerField()
|
integer = serializers.IntegerField()
|
||||||
|
@ -612,7 +612,7 @@ class TestDefaultInclusions:
|
||||||
|
|
||||||
|
|
||||||
class TestSerializerValidationWithCompiledRegexField:
|
class TestSerializerValidationWithCompiledRegexField:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class ExampleSerializer(serializers.Serializer):
|
class ExampleSerializer(serializers.Serializer):
|
||||||
name = serializers.RegexField(re.compile(r'\d'), required=True)
|
name = serializers.RegexField(re.compile(r'\d'), required=True)
|
||||||
self.Serializer = ExampleSerializer
|
self.Serializer = ExampleSerializer
|
||||||
|
@ -641,7 +641,7 @@ class Test2555Regression:
|
||||||
|
|
||||||
|
|
||||||
class Test4606Regression:
|
class Test4606Regression:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class ExampleSerializer(serializers.Serializer):
|
class ExampleSerializer(serializers.Serializer):
|
||||||
name = serializers.CharField(required=True)
|
name = serializers.CharField(required=True)
|
||||||
choices = serializers.CharField(required=True)
|
choices = serializers.CharField(required=True)
|
||||||
|
|
|
@ -32,7 +32,7 @@ class TestListSerializer:
|
||||||
Note that this is in contrast to using ListSerializer as a field.
|
Note that this is in contrast to using ListSerializer as a field.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class IntegerListSerializer(serializers.ListSerializer):
|
class IntegerListSerializer(serializers.ListSerializer):
|
||||||
child = serializers.IntegerField()
|
child = serializers.IntegerField()
|
||||||
self.Serializer = IntegerListSerializer
|
self.Serializer = IntegerListSerializer
|
||||||
|
@ -70,7 +70,7 @@ class TestListSerializerContainingNestedSerializer:
|
||||||
Tests for using a ListSerializer containing another serializer.
|
Tests for using a ListSerializer containing another serializer.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class TestSerializer(serializers.Serializer):
|
class TestSerializer(serializers.Serializer):
|
||||||
integer = serializers.IntegerField()
|
integer = serializers.IntegerField()
|
||||||
boolean = serializers.BooleanField()
|
boolean = serializers.BooleanField()
|
||||||
|
@ -156,7 +156,7 @@ class TestNestedListSerializer:
|
||||||
Tests for using a ListSerializer as a field.
|
Tests for using a ListSerializer as a field.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class TestSerializer(serializers.Serializer):
|
class TestSerializer(serializers.Serializer):
|
||||||
integers = serializers.ListSerializer(child=serializers.IntegerField())
|
integers = serializers.ListSerializer(child=serializers.IntegerField())
|
||||||
booleans = serializers.ListSerializer(child=serializers.BooleanField())
|
booleans = serializers.ListSerializer(child=serializers.BooleanField())
|
||||||
|
@ -278,7 +278,7 @@ class TestNestedListSerializerAllowEmpty:
|
||||||
|
|
||||||
|
|
||||||
class TestNestedListOfListsSerializer:
|
class TestNestedListOfListsSerializer:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class TestSerializer(serializers.Serializer):
|
class TestSerializer(serializers.Serializer):
|
||||||
integers = serializers.ListSerializer(
|
integers = serializers.ListSerializer(
|
||||||
child=serializers.ListSerializer(
|
child=serializers.ListSerializer(
|
||||||
|
@ -594,7 +594,7 @@ class TestEmptyListSerializer:
|
||||||
Tests the behaviour of ListSerializers when there is no data passed to it
|
Tests the behaviour of ListSerializers when there is no data passed to it
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class ExampleListSerializer(serializers.ListSerializer):
|
class ExampleListSerializer(serializers.ListSerializer):
|
||||||
child = serializers.IntegerField()
|
child = serializers.IntegerField()
|
||||||
|
|
||||||
|
@ -623,7 +623,7 @@ class TestMaxMinLengthListSerializer:
|
||||||
Tests the behaviour of ListSerializers when max_length and min_length are used
|
Tests the behaviour of ListSerializers when max_length and min_length are used
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class IntegerSerializer(serializers.Serializer):
|
class IntegerSerializer(serializers.Serializer):
|
||||||
some_int = serializers.IntegerField()
|
some_int = serializers.IntegerField()
|
||||||
|
|
||||||
|
|
|
@ -9,7 +9,7 @@ from rest_framework.serializers import raise_errors_on_nested_writes
|
||||||
|
|
||||||
|
|
||||||
class TestNestedSerializer:
|
class TestNestedSerializer:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class NestedSerializer(serializers.Serializer):
|
class NestedSerializer(serializers.Serializer):
|
||||||
one = serializers.IntegerField(max_value=10)
|
one = serializers.IntegerField(max_value=10)
|
||||||
two = serializers.IntegerField(max_value=10)
|
two = serializers.IntegerField(max_value=10)
|
||||||
|
@ -54,7 +54,7 @@ class TestNestedSerializer:
|
||||||
|
|
||||||
|
|
||||||
class TestNotRequiredNestedSerializer:
|
class TestNotRequiredNestedSerializer:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class NestedSerializer(serializers.Serializer):
|
class NestedSerializer(serializers.Serializer):
|
||||||
one = serializers.IntegerField(max_value=10)
|
one = serializers.IntegerField(max_value=10)
|
||||||
|
|
||||||
|
@ -83,7 +83,7 @@ class TestNotRequiredNestedSerializer:
|
||||||
|
|
||||||
|
|
||||||
class TestNestedSerializerWithMany:
|
class TestNestedSerializerWithMany:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class NestedSerializer(serializers.Serializer):
|
class NestedSerializer(serializers.Serializer):
|
||||||
example = serializers.IntegerField(max_value=10)
|
example = serializers.IntegerField(max_value=10)
|
||||||
|
|
||||||
|
@ -181,7 +181,7 @@ class TestNestedSerializerWithMany:
|
||||||
|
|
||||||
|
|
||||||
class TestNestedSerializerWithList:
|
class TestNestedSerializerWithList:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class NestedSerializer(serializers.Serializer):
|
class NestedSerializer(serializers.Serializer):
|
||||||
example = serializers.MultipleChoiceField(choices=[1, 2, 3])
|
example = serializers.MultipleChoiceField(choices=[1, 2, 3])
|
||||||
|
|
||||||
|
@ -210,7 +210,7 @@ class TestNestedSerializerWithList:
|
||||||
|
|
||||||
|
|
||||||
class TestNotRequiredNestedSerializerWithMany:
|
class TestNotRequiredNestedSerializerWithMany:
|
||||||
def setup(self):
|
def setup_method(self):
|
||||||
class NestedSerializer(serializers.Serializer):
|
class NestedSerializer(serializers.Serializer):
|
||||||
one = serializers.IntegerField(max_value=10)
|
one = serializers.IntegerField(max_value=10)
|
||||||
|
|
||||||
|
|
|
@ -7,27 +7,27 @@ from rest_framework.status import (
|
||||||
|
|
||||||
class TestStatus(TestCase):
|
class TestStatus(TestCase):
|
||||||
def test_status_categories(self):
|
def test_status_categories(self):
|
||||||
self.assertFalse(is_informational(99))
|
assert not is_informational(99)
|
||||||
self.assertTrue(is_informational(100))
|
assert is_informational(100)
|
||||||
self.assertTrue(is_informational(199))
|
assert is_informational(199)
|
||||||
self.assertFalse(is_informational(200))
|
assert not is_informational(200)
|
||||||
|
|
||||||
self.assertFalse(is_success(199))
|
assert not is_success(199)
|
||||||
self.assertTrue(is_success(200))
|
assert is_success(200)
|
||||||
self.assertTrue(is_success(299))
|
assert is_success(299)
|
||||||
self.assertFalse(is_success(300))
|
assert not is_success(300)
|
||||||
|
|
||||||
self.assertFalse(is_redirect(299))
|
assert not is_redirect(299)
|
||||||
self.assertTrue(is_redirect(300))
|
assert is_redirect(300)
|
||||||
self.assertTrue(is_redirect(399))
|
assert is_redirect(399)
|
||||||
self.assertFalse(is_redirect(400))
|
assert not is_redirect(400)
|
||||||
|
|
||||||
self.assertFalse(is_client_error(399))
|
assert not is_client_error(399)
|
||||||
self.assertTrue(is_client_error(400))
|
assert is_client_error(400)
|
||||||
self.assertTrue(is_client_error(499))
|
assert is_client_error(499)
|
||||||
self.assertFalse(is_client_error(500))
|
assert not is_client_error(500)
|
||||||
|
|
||||||
self.assertFalse(is_server_error(499))
|
assert not is_server_error(499)
|
||||||
self.assertTrue(is_server_error(500))
|
assert is_server_error(500)
|
||||||
self.assertTrue(is_server_error(599))
|
assert is_server_error(599)
|
||||||
self.assertFalse(is_server_error(600))
|
assert not is_server_error(600)
|
||||||
|
|
|
@ -10,6 +10,7 @@ from django.test import TestCase, override_settings
|
||||||
from django.urls import path
|
from django.urls import path
|
||||||
|
|
||||||
from rest_framework import fields, serializers
|
from rest_framework import fields, serializers
|
||||||
|
from rest_framework.authtoken.models import Token
|
||||||
from rest_framework.decorators import api_view
|
from rest_framework.decorators import api_view
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.test import (
|
from rest_framework.test import (
|
||||||
|
@ -19,10 +20,12 @@ from rest_framework.test import (
|
||||||
|
|
||||||
@api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])
|
@api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])
|
||||||
def view(request):
|
def view(request):
|
||||||
return Response({
|
data = {'auth': request.META.get('HTTP_AUTHORIZATION', b'')}
|
||||||
'auth': request.META.get('HTTP_AUTHORIZATION', b''),
|
if request.user:
|
||||||
'user': request.user.username
|
data['user'] = request.user.username
|
||||||
})
|
if request.auth:
|
||||||
|
data['token'] = request.auth.key
|
||||||
|
return Response(data)
|
||||||
|
|
||||||
|
|
||||||
@api_view(['GET', 'POST'])
|
@api_view(['GET', 'POST'])
|
||||||
|
@ -78,14 +81,46 @@ class TestAPITestClient(TestCase):
|
||||||
response = self.client.get('/view/')
|
response = self.client.get('/view/')
|
||||||
assert response.data['auth'] == 'example'
|
assert response.data['auth'] == 'example'
|
||||||
|
|
||||||
def test_force_authenticate(self):
|
def test_force_authenticate_with_user(self):
|
||||||
"""
|
"""
|
||||||
Setting `.force_authenticate()` forcibly authenticates each request.
|
Setting `.force_authenticate()` with a user forcibly authenticates each
|
||||||
|
request with that user.
|
||||||
"""
|
"""
|
||||||
user = User.objects.create_user('example', 'example@example.com')
|
user = User.objects.create_user('example', 'example@example.com')
|
||||||
self.client.force_authenticate(user)
|
|
||||||
|
self.client.force_authenticate(user=user)
|
||||||
response = self.client.get('/view/')
|
response = self.client.get('/view/')
|
||||||
|
|
||||||
assert response.data['user'] == 'example'
|
assert response.data['user'] == 'example'
|
||||||
|
assert 'token' not in response.data
|
||||||
|
|
||||||
|
def test_force_authenticate_with_token(self):
|
||||||
|
"""
|
||||||
|
Setting `.force_authenticate()` with a token forcibly authenticates each
|
||||||
|
request with that token.
|
||||||
|
"""
|
||||||
|
user = User.objects.create_user('example', 'example@example.com')
|
||||||
|
token = Token.objects.create(key='xyz', user=user)
|
||||||
|
|
||||||
|
self.client.force_authenticate(token=token)
|
||||||
|
response = self.client.get('/view/')
|
||||||
|
|
||||||
|
assert response.data['token'] == 'xyz'
|
||||||
|
assert 'user' not in response.data
|
||||||
|
|
||||||
|
def test_force_authenticate_with_user_and_token(self):
|
||||||
|
"""
|
||||||
|
Setting `.force_authenticate()` with a user and token forcibly
|
||||||
|
authenticates each request with that user and token.
|
||||||
|
"""
|
||||||
|
user = User.objects.create_user('example', 'example@example.com')
|
||||||
|
token = Token.objects.create(key='xyz', user=user)
|
||||||
|
|
||||||
|
self.client.force_authenticate(user=user, token=token)
|
||||||
|
response = self.client.get('/view/')
|
||||||
|
|
||||||
|
assert response.data['user'] == 'example'
|
||||||
|
assert response.data['token'] == 'xyz'
|
||||||
|
|
||||||
def test_force_authenticate_with_sessions(self):
|
def test_force_authenticate_with_sessions(self):
|
||||||
"""
|
"""
|
||||||
|
@ -102,8 +137,9 @@ class TestAPITestClient(TestCase):
|
||||||
response = self.client.get('/session-view/')
|
response = self.client.get('/session-view/')
|
||||||
assert response.data['active_session'] is True
|
assert response.data['active_session'] is True
|
||||||
|
|
||||||
# Force authenticating as `None` should also logout the user session.
|
# Force authenticating with `None` user and token should also logout
|
||||||
self.client.force_authenticate(None)
|
# the user session.
|
||||||
|
self.client.force_authenticate(user=None, token=None)
|
||||||
response = self.client.get('/session-view/')
|
response = self.client.get('/session-view/')
|
||||||
assert response.data['active_session'] is False
|
assert response.data['active_session'] is False
|
||||||
|
|
||||||
|
|
12
tox.ini
12
tox.ini
|
@ -1,14 +1,15 @@
|
||||||
[tox]
|
[tox]
|
||||||
envlist =
|
envlist =
|
||||||
{py36,py37,py38,py39}-django22,
|
{py36,py37,py38,py39}-django30,
|
||||||
{py36,py37,py38,py39}-django31,
|
{py36,py37,py38,py39}-django31,
|
||||||
{py36,py37,py38,py39,py310}-django32,
|
{py36,py37,py38,py39,py310}-django32,
|
||||||
{py38,py39,py310}-{django40,django41,djangomain},
|
{py38,py39,py310}-{django40,django41,djangomain},
|
||||||
|
{py311}-{django41,djangomain},
|
||||||
base,dist,docs,
|
base,dist,docs,
|
||||||
|
|
||||||
[travis:env]
|
[travis:env]
|
||||||
DJANGO =
|
DJANGO =
|
||||||
2.2: django22
|
3.0: django30
|
||||||
3.1: django31
|
3.1: django31
|
||||||
3.2: django32
|
3.2: django32
|
||||||
4.0: django40
|
4.0: django40
|
||||||
|
@ -22,11 +23,11 @@ setenv =
|
||||||
PYTHONDONTWRITEBYTECODE=1
|
PYTHONDONTWRITEBYTECODE=1
|
||||||
PYTHONWARNINGS=once
|
PYTHONWARNINGS=once
|
||||||
deps =
|
deps =
|
||||||
django22: Django>=2.2,<3.0
|
django30: Django>=3.0,<3.1
|
||||||
django31: Django>=3.1,<3.2
|
django31: Django>=3.1,<3.2
|
||||||
django32: Django>=3.2,<4.0
|
django32: Django>=3.2,<4.0
|
||||||
django40: Django>=4.0,<4.1
|
django40: Django>=4.0,<4.1
|
||||||
django41: Django>=4.1a1,<4.2
|
django41: Django>=4.1,<4.2
|
||||||
djangomain: https://github.com/django/django/archive/main.tar.gz
|
djangomain: https://github.com/django/django/archive/main.tar.gz
|
||||||
-rrequirements/requirements-testing.txt
|
-rrequirements/requirements-testing.txt
|
||||||
-rrequirements/requirements-optionals.txt
|
-rrequirements/requirements-optionals.txt
|
||||||
|
@ -59,3 +60,6 @@ ignore_outcome = true
|
||||||
|
|
||||||
[testenv:py310-djangomain]
|
[testenv:py310-djangomain]
|
||||||
ignore_outcome = true
|
ignore_outcome = true
|
||||||
|
|
||||||
|
[testenv:py311-djangomain]
|
||||||
|
ignore_outcome = true
|
||||||
|
|
Loading…
Reference in New Issue
Block a user