diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c88dc55cd99..b635573f260 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -19,6 +19,7 @@ jobs: - '3.8' - '3.9' - '3.10' + - '3.11' steps: - uses: actions/checkout@v3 diff --git a/README.md b/README.md index 6cd4e86c768..e8375291dcd 100644 --- a/README.md +++ b/README.md @@ -54,8 +54,8 @@ There is a live example API for testing purposes, [available here][sandbox]. # Requirements -* Python (3.6, 3.7, 3.8, 3.9, 3.10) -* Django (2.2, 3.0, 3.1, 3.2, 4.0, 4.1) +* Python 3.6+ +* Django 4.1, 4.0, 3.2, 3.1, 3.0 We **highly recommend** and only officially support the latest patch release of each Python and Django series. diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index fca9374d0af..2eb3a2921ef 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -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. @@ -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(): 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 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. -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. 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`: @@ -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. -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 @@ -299,7 +299,7 @@ environment variable. 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 -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/). 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.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) * [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'. - from django.contrib.auth.models import User + from django.contrib.auth.models import User from rest_framework import authentication 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**. -#### Installation & configuration +### Installation & configuration 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. -#### Installation & configuration +### Installation & configuration Install the package using `pip`. @@ -418,7 +418,7 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a ## 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 diff --git a/docs/api-guide/content-negotiation.md b/docs/api-guide/content-negotiation.md index 3a4b0357fa6..81cff6a89bf 100644 --- a/docs/api-guide/content-negotiation.md +++ b/docs/api-guide/content-negotiation.md @@ -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. - from myapp.negotiation import IgnoreClientContentNegotiation + from myapp.negotiation import IgnoreClientContentNegotiation from rest_framework.response import Response from rest_framework.views import APIView diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index e9ef5c6b642..4b4ea83cc13 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -46,7 +46,7 @@ Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-f ### `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. @@ -78,14 +78,14 @@ Defaults to `False` ### `source` -The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. +The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal. Beware of possible n+1 problems when using source attribute if you are accessing a relational orm model. For example: class CommentSerializer(serializers.Serializer): 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. @@ -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 without the `required` kwarg (i.e. equivalent to `required=True`) whereas with 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 `extra_kwargs` option to set the `required` flag. @@ -159,14 +159,6 @@ Corresponds to `django.db.models.fields.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 @@ -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)` -- `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. -- `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`. +* `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. +* `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`. 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')` -- `format`: Determines the representation format of the uuid value - - `'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"` - - `'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"` +* `format`: Determines the representation format of the uuid value + * `'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"` + * `'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"` Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value` ## 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)` -- `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. -- `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_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`. +* `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. +* `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_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`. ## IPAddressField @@ -259,8 +251,8 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen **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. -- `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'. +* `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'. --- @@ -274,8 +266,8 @@ Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields. **Signature**: `IntegerField(max_value=None, min_value=None)` -- `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. +* `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. ## FloatField @@ -285,8 +277,8 @@ Corresponds to `django.db.models.fields.FloatField`. **Signature**: `FloatField(max_value=None, min_value=None)` -- `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. +* `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. ## 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)` -- `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. -- `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. -- `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. -- `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`. +* `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. +* `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. +* `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. +* `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 @@ -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) -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 @@ -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)` -- `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. +* `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. --- @@ -407,10 +396,10 @@ Used by `ModelSerializer` to automatically generate fields if the corresponding **Signature:** `ChoiceField(choices)` -- `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`. -- `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…"` +* `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`. +* `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…"` 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)` -- `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`. -- `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…"` +* `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`. +* `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…"` 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)` - - `max_length` - Designates the maximum length for the file name. - - `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. +* `max_length` - Designates the maximum length for the file name. +* `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. ## 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)` - - `max_length` - Designates the maximum length for the file name. - - `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. +* `max_length` - Designates the maximum length for the file name. +* `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. 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)` -- `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. -- `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. +* `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. +* `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. 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)` -- `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. +* `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. 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)` -- `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. +* `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. 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)` -- `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`. +* `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`. --- @@ -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)` -- `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: @@ -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` 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. Serializing: @@ -843,7 +832,7 @@ the [djangorestframework-recursive][djangorestframework-recursive] package provi ## 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 diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md index da4a1af78b1..9b4e5b9da41 100644 --- a/docs/api-guide/format-suffixes.md +++ b/docs/api-guide/format-suffixes.md @@ -23,8 +23,8 @@ Returns a URL pattern list which includes format suffix patterns appended to eac Arguments: * **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. -* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. +* **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. Example: diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 9467eb6b480..410e3518dfa 100644 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -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]. --- diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index aadc1bbc7fe..3081e2bc36a 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -227,7 +227,7 @@ Note that the `paginate_queryset` method may set state on the pagination instanc ## 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): def get_paginated_response(self, data): diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index dde77c3e0ea..0a85d474f68 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -15,7 +15,7 @@ REST framework includes a number of built in Parser classes, that allow you to a ## 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 -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. diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 8d6f47c79be..d945e95c3b4 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -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. * `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. @@ -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. +## 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 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 [dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions [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/ [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 diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 9c8295b8538..56eb61e436c 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -33,7 +33,7 @@ For example, the following serializer would lead to a database hit each time eva class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] - + # For each album object, tracks should be fetched from database qs = Album.objects.all() print(AlbumSerializer(qs, many=True).data) @@ -246,7 +246,7 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e ## 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): track_listing = serializers.HyperlinkedIdentityField(view_name='track-list') @@ -278,7 +278,7 @@ This field is always read-only. As opposed to previously discussed _references_ to another entity, the referred entity can instead also be embedded or _nested_ in the representation of the object that refers to it. -Such nested relationships can be expressed by using serializers as fields. +Such nested relationships can be expressed by using serializers as fields. If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field. @@ -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: -- `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` - 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…"` You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`. diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 685a98f5e05..44f1b60218e 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -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} @@ -192,7 +192,7 @@ By default the response content will be rendered with the highest priority rende def get_default_renderer(self, view): return JSONRenderer() -## AdminRenderer +## AdminRenderer 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. * 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. diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md index e877c868df9..d072ac43674 100644 --- a/docs/api-guide/requests.md +++ b/docs/api-guide/requests.md @@ -49,7 +49,7 @@ If a client sends a request with a content-type that cannot be parsed then a `Un # 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 diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md index 70df42b8f09..82dd168818c 100644 --- a/docs/api-guide/reverse.md +++ b/docs/api-guide/reverse.md @@ -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.views import APIView - from django.utils.timezone import now - - class APIRootView(APIView): - def get(self, request): - year = now().year - data = { - ... - 'year-summary-url': reverse('year-summary', args=[year], request=request) + from django.utils.timezone import now + + class APIRootView(APIView): + def get(self, request): + year = now().year + data = { + ... + 'year-summary-url': reverse('year-summary', args=[year], request=request) } - return Response(data) + return Response(data) ## reverse_lazy diff --git a/docs/api-guide/schemas.md b/docs/api-guide/schemas.md index 004e2d3ce9d..e402019a4f1 100644 --- a/docs/api-guide/schemas.md +++ b/docs/api-guide/schemas.md @@ -122,6 +122,7 @@ The `get_schema_view()` helper takes the following keyword arguments: url='https://www.example.org/api/', 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 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. -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. ### `AutoSchema` methods @@ -300,7 +301,7 @@ the more commonly needed options do. #### `get_components()` 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 representation. By default this has just a single pair but you may override diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 91a9d63f306..0d14cac46bc 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -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. -### `.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. -### `.serializer_related_field` +### `serializer_related_field` 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`. -### `.serializer_url_field` +### `serializer_url_field` The serializer field class that should be used for any `url` field on the serializer. 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. @@ -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)`. -### `.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. 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. @@ -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. -### `.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. @@ -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. -### `.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. 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. -### `.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. 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): instance = HighScore.objects.get(pk=pk) serializer = HighScoreSerializer(instance) - return Response(serializer.data) + return Response(serializer.data) Or use it to serialize multiple instances: @@ -918,7 +918,7 @@ Or use it to serialize multiple instances: def all_high_scores(request): queryset = HighScore.objects.order_by('-score') serializer = HighScoreSerializer(queryset, many=True) - return Response(serializer.data) + return Response(serializer.data) #### Read-write `BaseSerializer` classes @@ -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.' }) - # Return the validated values. This will be available as - # the `.validated_data` property. + # Return the validated values. This will be available as + # the `.validated_data` property. return { 'score': int(score), 'player_name': player_name @@ -1021,7 +1021,7 @@ Some reasons this might be useful include... 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. @@ -1033,7 +1033,7 @@ May be overridden in order to modify the representation style. For example: ret['username'] = ret['username'].lower() 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. @@ -1189,7 +1189,7 @@ The [drf-writable-nested][drf-writable-nested] package provides writable nested ## DRF Encrypt Content -The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data. +The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data. [cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md index a37ba15d451..fb2f9bf138e 100644 --- a/docs/api-guide/status-codes.md +++ b/docs/api-guide/status-codes.md @@ -41,6 +41,8 @@ This class of status code indicates a provisional response. There are no 1xx st HTTP_100_CONTINUE HTTP_101_SWITCHING_PROTOCOLS + HTTP_102_PROCESSING + HTTP_103_EARLY_HINTS ## 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_416_REQUESTED_RANGE_NOT_SATISFIABLE HTTP_417_EXPECTATION_FAILED + HTTP_421_MISDIRECTED_REQUEST HTTP_422_UNPROCESSABLE_ENTITY HTTP_423_LOCKED HTTP_424_FAILED_DEPENDENCY + HTTP_425_TOO_EARLY HTTP_426_UPGRADE_REQUIRED HTTP_428_PRECONDITION_REQUIRED HTTP_429_TOO_MANY_REQUESTS diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index b875221978b..4c58fa713f9 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -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, 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.views import APIView + from rest_framework.views import APIView class ExampleView(APIView): throttle_classes = [UserRateThrottle] diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index 76dcb0d541f..bb8466a2c86 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -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: * 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. 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 `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. In this case you will typically need to exclude the validator from the diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md index 878a291b229..b293de75ab2 100644 --- a/docs/api-guide/views.md +++ b/docs/api-guide/views.md @@ -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]. -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']) def hello_world(request): diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 41797250781..5d5491a83f4 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -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`. * `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): """ @@ -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 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 diff --git a/docs/community/3.0-announcement.md b/docs/community/3.0-announcement.md index b9461defe91..0cb79fc2e29 100644 --- a/docs/community/3.0-announcement.md +++ b/docs/community/3.0-announcement.md @@ -24,7 +24,7 @@ Notable features of this new release include: * 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 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. @@ -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 `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): """A custom read-only field that returns the class name.""" diff --git a/docs/community/3.12-announcement.md b/docs/community/3.12-announcement.md index 9d2220933cb..4a589e39c0c 100644 --- a/docs/community/3.12-announcement.md +++ b/docs/community/3.12-announcement.md @@ -30,12 +30,12 @@ in the URL path. For example... -Method | Path | Tags +Method | Path | Tags --------------------------------|-----------------|------------- -`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']` -`GET`, `POST` | `/users/` | `['users']` -`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']` -`GET`, `POST` | `/orders/` | `['orders']` +`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']` +`GET`, `POST` | `/users/` | `['users']` +`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']` +`GET`, `POST` | `/orders/` | `['orders']` The tags used for a particular view may also be overridden... diff --git a/docs/community/3.14-announcement.md b/docs/community/3.14-announcement.md new file mode 100644 index 00000000000..0543d0d6d60 --- /dev/null +++ b/docs/community/3.14-announcement.md @@ -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. diff --git a/docs/community/3.2-announcement.md b/docs/community/3.2-announcement.md index a66ad5d2921..eda4071b2ed 100644 --- a/docs/community/3.2-announcement.md +++ b/docs/community/3.2-announcement.md @@ -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 -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. diff --git a/docs/community/3.3-announcement.md b/docs/community/3.3-announcement.md index 5dcbe3b3b54..24f493dcdcf 100644 --- a/docs/community/3.3-announcement.md +++ b/docs/community/3.3-announcement.md @@ -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. * 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. diff --git a/docs/community/3.4-announcement.md b/docs/community/3.4-announcement.md index 67192ecbb26..6d5f0399c50 100644 --- a/docs/community/3.4-announcement.md +++ b/docs/community/3.4-announcement.md @@ -89,7 +89,7 @@ Name | Support | PyPI pa ---------------------------------|-------------------------------------|-------------------------------- [Core JSON][core-json] | Schema generation & client support. | Built-in support in `coreapi`. [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. --- diff --git a/docs/community/3.8-announcement.md b/docs/community/3.8-announcement.md index 507299782d2..f33b220fd7f 100644 --- a/docs/community/3.8-announcement.md +++ b/docs/community/3.8-announcement.md @@ -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 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 [gh5886]: https://github.com/encode/django-rest-framework/issues/5886 diff --git a/docs/community/contributing.md b/docs/community/contributing.md index 2232bd10b95..994226b97ab 100644 --- a/docs/community/contributing.md +++ b/docs/community/contributing.md @@ -80,7 +80,7 @@ To run the tests, clone the repository, and then: # Setup the virtual environment python3 -m venv env source env/bin/activate - pip install django + pip install -e . pip install -r requirements.txt # Run the tests diff --git a/docs/community/funding.md b/docs/community/funding.md index 2158cd38f3c..951833682e0 100644 --- a/docs/community/funding.md +++ b/docs/community/funding.md @@ -124,7 +124,7 @@ REST framework continues to be open-source and permissively licensed, but we fir ## 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.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 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. @@ -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 -> 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. > > — Andrew Conti, Django REST framework user diff --git a/docs/community/jobs.md b/docs/community/jobs.md index ce85b75707a..aa1c5d4b4c5 100644 --- a/docs/community/jobs.md +++ b/docs/community/jobs.md @@ -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://www.upwork.com/o/jobs/browse/skill/django-framework/][upwork-com] * [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.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]. @@ -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 [upwork-com]: https://www.upwork.com/o/jobs/browse/skill/django-framework/ [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/ +[pyjobs-com]: https://www.pyjobs.com/ [drf-funding]: https://fund.django-rest-framework.org/topics/funding/ [submit-pr]: https://github.com/encode/django-rest-framework [anna-email]: mailto:anna@django-rest-framework.org diff --git a/docs/community/release-notes.md b/docs/community/release-notes.md index 8629e4fee70..887cae3b478 100644 --- a/docs/community/release-notes.md +++ b/docs/community/release-notes.md @@ -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.1 diff --git a/docs/community/third-party-packages.md b/docs/community/third-party-packages.md index 9513b13d1a2..1a40539da9c 100644 --- a/docs/community/third-party-packages.md +++ b/docs/community/third-party-packages.md @@ -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 [django-url-filter]: https://github.com/miki725/django-url-filter [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/ [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 diff --git a/docs/coreapi/from-documenting-your-api.md b/docs/coreapi/from-documenting-your-api.md index 65ad71c7a77..f8ddff019ec 100644 --- a/docs/coreapi/from-documenting-your-api.md +++ b/docs/coreapi/from-documenting-your-api.md @@ -43,7 +43,7 @@ This will include two different views: **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`. -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`: diff --git a/docs/coreapi/schemas.md b/docs/coreapi/schemas.md index 9f1482d2d87..73fc7b67d1a 100644 --- a/docs/coreapi/schemas.md +++ b/docs/coreapi/schemas.md @@ -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. 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. 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. -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 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.""" extra_fields = [] - if method=='GET': - extra_fields = # ... list of extra fields for GET ... - if method=='POST': - extra_fields = # ... list of extra fields for POST ... + if method == 'GET': + extra_fields = ... # list of extra fields for GET + if method == 'POST': + extra_fields = ... # list of extra fields for POST manual_fields = super().get_manual_fields(path, method) return manual_fields + extra_fields diff --git a/docs/index.md b/docs/index.md index 2f44fae9a05..cab5511ac17 100644 --- a/docs/index.md +++ b/docs/index.md @@ -85,7 +85,7 @@ continued development by **[signing up for a paid plan][funding]**. 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) We **highly recommend** and only officially support the latest patch release of @@ -188,7 +188,7 @@ Framework. ## 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/). diff --git a/docs/topics/ajax-csrf-cors.md b/docs/topics/ajax-csrf-cors.md index a65e3fdf8d3..094ecc4a417 100644 --- a/docs/topics/ajax-csrf-cors.md +++ b/docs/topics/ajax-csrf-cors.md @@ -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." > -> — [Jeff Atwood][cite] +> — [Jeff Atwood][cite] ## Javascript clients diff --git a/docs/topics/api-clients.md b/docs/topics/api-clients.md index b9f5e3ecd8f..3732d3f93de 100644 --- a/docs/topics/api-clients.md +++ b/docs/topics/api-clients.md @@ -230,7 +230,7 @@ started. 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 when interacting with an API, which allows you to provide for more advanced -kinds of behaviour. +kinds of behavior. import coreapi client = coreapi.Client() diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md index ed70c490189..2cdf2a884c6 100644 --- a/docs/topics/browsable-api.md +++ b/docs/topics/browsable-api.md @@ -17,7 +17,7 @@ By default, the API will return the format specified by the headers, which in th ## 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: @@ -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"> {% 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. @@ -44,7 +44,7 @@ Full example: {% extends "rest_framework/base.html" %} {% 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 %} {% block bootstrap_navbar_variant %}{% endblock %} diff --git a/docs/topics/html-and-forms.md b/docs/topics/html-and-forms.md index 18774926b5c..17c9e3314cd 100644 --- a/docs/topics/html-and-forms.md +++ b/docs/topics/html-and-forms.md @@ -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. -base_template | Valid field types | Additional style options -----|----|---- -input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus -textarea.html | `CharField` | rows, placeholder, hide_label -select.html | `ChoiceField` or relational field types | hide_label -radio.html | `ChoiceField` or relational field types | inline, hide_label -select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label +base_template | Valid field types | Additional style options +-----------------------|-------------------------------------------------------------|----------------------------------------------- +input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus +textarea.html | `CharField` | rows, placeholder, hide_label +select.html | `ChoiceField` or relational field types | hide_label +radio.html | `ChoiceField` or relational field types | inline, 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.html | `BooleanField` | hide_label -fieldset.html | Nested serializer | hide_label -list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label +checkbox.html | `BooleanField` | hide_label +fieldset.html | Nested serializer | hide_label +list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label diff --git a/docs/topics/rest-hypermedia-hateoas.md b/docs/topics/rest-hypermedia-hateoas.md index a11bd6cc727..3498bddd1cb 100644 --- a/docs/topics/rest-hypermedia-hateoas.md +++ b/docs/topics/rest-hypermedia-hateoas.md @@ -4,7 +4,7 @@ > > — 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. diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 67746c517ee..6db3ea282d5 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -179,7 +179,7 @@ We can also serialize querysets instead of model instances. To do so we simply ## 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. @@ -307,7 +307,7 @@ Quit out of the shell... Validating models... 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/ Quit the server with CONTROL-C. diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 1d272f30409..47c7facfc63 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -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. -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 diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index e02feaa5ea3..ccfcd095da8 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -79,9 +79,9 @@ Okay, we're done. If you run the development server everything should be workin ## 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. diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index e12becbd06b..b7a7696a728 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -112,8 +112,8 @@ Here's our re-wired `snippets/urls.py` file. # Create a router and register our viewsets with it. router = DefaultRouter() - router.register(r'snippets', views.SnippetViewSet,basename="snippet") - router.register(r'users', views.UserViewSet,basename="user") + router.register(r'snippets', views.SnippetViewSet, basename='snippet') + router.register(r'users', views.UserViewSet, basename='user') # The API URLs are now determined automatically by the router. urlpatterns = [ diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 4fa2fbbe527..754b46f9abf 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -30,22 +30,24 @@ The project layout should look like: <some path>/tutorial $ find . . - ./manage.py ./tutorial + ./tutorial/asgi.py ./tutorial/__init__.py ./tutorial/quickstart - ./tutorial/quickstart/__init__.py - ./tutorial/quickstart/admin.py - ./tutorial/quickstart/apps.py ./tutorial/quickstart/migrations ./tutorial/quickstart/migrations/__init__.py ./tutorial/quickstart/models.py + ./tutorial/quickstart/__init__.py + ./tutorial/quickstart/apps.py + ./tutorial/quickstart/admin.py ./tutorial/quickstart/tests.py ./tutorial/quickstart/views.py - ./tutorial/asgi.py ./tutorial/settings.py ./tutorial/urls.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). @@ -53,9 +55,9 @@ Now sync your database for the first time: 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... @@ -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. - from django.contrib.auth.models import User, Group + from django.contrib.auth.models import Group, User 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. - from django.contrib.auth.models import User, Group - from rest_framework import viewsets - from rest_framework import permissions - from tutorial.quickstart.serializers import UserSerializer, GroupSerializer + from django.contrib.auth.models import Group, User + from rest_framework import permissions, viewsets + + from tutorial.quickstart.serializers import GroupSerializer, UserSerializer 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 rest_framework import routers + from tutorial.quickstart import views router = routers.DefaultRouter() @@ -165,38 +168,39 @@ 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`... - 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": [ { - "email": "admin@example.com", - "groups": [], "url": "http://127.0.0.1:8000/users/1/", - "username": "admin" - }, + "username": "admin", + "email": "admin@example.com", + "groups": [] + } ] } 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 + 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": 2, + "count": 1, "next": null, "previous": null, "results": [ { "email": "admin@example.com", "groups": [], - "url": "http://localhost:8000/users/1/", - "username": "paul" - }, + "url": "http://127.0.0.1:8000/users/1/", + "username": "admin" + } ] } diff --git a/mkdocs.yml b/mkdocs.yml index 439245a8d2f..c58e083183f 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -66,6 +66,7 @@ nav: - 'Contributing to REST framework': 'community/contributing.md' - 'Project management': 'community/project-management.md' - 'Release Notes': 'community/release-notes.md' + - '3.14 Announcement': 'community/3.14-announcement.md' - '3.13 Announcement': 'community/3.13-announcement.md' - '3.12 Announcement': 'community/3.12-announcement.md' - '3.11 Announcement': 'community/3.11-announcement.md' diff --git a/requirements.txt b/requirements.txt index 395f3b7a860..c3a1f1187c2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ # The base set of requirements for REST framework is actually -# just Django, but for the purposes of development and testing -# there are a number of packages that are useful to install. +# just Django and pytz, but for the purposes of development +# and testing there are a number of packages that are useful +# to install. # Laying these out as separate requirements files, allows us to # only included the relevant sets when running tox, and ensures diff --git a/requirements/requirements-optionals.txt b/requirements/requirements-optionals.txt index f3bb9b709dc..3de07d1c7b3 100644 --- a/requirements/requirements-optionals.txt +++ b/requirements/requirements-optionals.txt @@ -4,6 +4,6 @@ coreschema==0.0.4 django-filter>=2.4.0,<3.0 django-guardian>=2.4.0,<2.5 markdown==3.3 -psycopg2-binary>=2.8.5,<2.9 +psycopg2-binary>=2.9.5,<2.10 pygments==2.12 pyyaml>=5.3.1,<5.4 diff --git a/requirements/requirements-testing.txt b/requirements/requirements-testing.txt index 313fdedc9b7..fb6dbf05fd5 100644 --- a/requirements/requirements-testing.txt +++ b/requirements/requirements-testing.txt @@ -1,4 +1,5 @@ # Pytest for running the tests. -pytest>=6.1,<7.0 -pytest-cov>=2.10.1,<3.0 -pytest-django>=4.1.0,<5.0 +pytest>=6.2.0,<8.0 +pytest-cov>=4.0.0,<5.0 +pytest-django>=4.5.2,<5.0 +importlib-metadata<5.0 diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py index 8b0679ef95b..cc24ce46c5c 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -10,7 +10,7 @@ import django __title__ = 'Django REST framework' -__version__ = '3.13.1' +__version__ = '3.14.0' __author__ = 'Tom Christie' __license__ = 'BSD 3-Clause' __copyright__ = 'Copyright 2011-2019 Encode OSS Ltd' @@ -29,9 +29,5 @@ default_app_config = 'rest_framework.apps.RestFrameworkConfig' -class RemovedInDRF313Warning(DeprecationWarning): - pass - - -class RemovedInDRF314Warning(PendingDeprecationWarning): +class RemovedInDRF315Warning(DeprecationWarning): pass diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 72bfe614d92..88d606b2822 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,3 +1,4 @@ +import contextlib import copy import datetime import decimal @@ -5,7 +6,6 @@ import inspect import re import uuid -import warnings from collections import OrderedDict from collections.abc import Mapping @@ -30,7 +30,7 @@ from django.utils.translation import gettext_lazy as _ 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.settings import api_settings from rest_framework.utils import html, humanize_datetime, json, representation @@ -691,15 +691,13 @@ class BooleanField(Field): NULL_VALUES = {'null', 'Null', 'NULL', '', None} def to_internal_value(self, data): - try: + with contextlib.suppress(TypeError): if data in self.TRUE_VALUES: return True elif data in self.FALSE_VALUES: return False elif data in self.NULL_VALUES and self.allow_null: return None - except TypeError: # Input is an unhashable type - pass self.fail('invalid', input=data) def to_representation(self, value): @@ -712,23 +710,6 @@ def to_representation(self, 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... class CharField(Field): @@ -982,10 +963,11 @@ class DecimalField(Field): 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, - localize=False, rounding=None, **kwargs): + localize=False, rounding=None, normalize_output=False, **kwargs): self.max_digits = max_digits self.decimal_places = decimal_places self.localize = localize + self.normalize_output = normalize_output if coerce_to_string is not None: self.coerce_to_string = coerce_to_string if self.localize: @@ -1098,6 +1080,9 @@ def to_representation(self, value): quantized = self.quantize(value) + if self.normalize_output: + quantized = quantized.normalize() + if not coerce_to_string: return quantized if self.localize: @@ -1176,19 +1161,14 @@ def to_internal_value(self, value): return self.enforce_timezone(value) for input_format in input_formats: - if input_format.lower() == ISO_8601: - try: + with contextlib.suppress(ValueError, TypeError): + if input_format.lower() == ISO_8601: parsed = parse_datetime(value) if parsed is not None: return self.enforce_timezone(parsed) - except (ValueError, TypeError): - pass - else: - try: - parsed = self.datetime_parser(value, input_format) - return self.enforce_timezone(parsed) - except (ValueError, TypeError): - pass + + parsed = self.datetime_parser(value, input_format) + return self.enforce_timezone(parsed) humanized_format = humanize_datetime.datetime_formats(input_formats) self.fail('invalid', format=humanized_format) @@ -1832,7 +1812,7 @@ class SerializerMethodField(Field): For example: - class ExampleSerializer(self): + class ExampleSerializer(Serializer): extra_info = SerializerMethodField() def get_extra_info(self, obj): diff --git a/rest_framework/management/commands/generateschema.py b/rest_framework/management/commands/generateschema.py index 024306b65f7..8c73e4b9c8e 100644 --- a/rest_framework/management/commands/generateschema.py +++ b/rest_framework/management/commands/generateschema.py @@ -26,6 +26,7 @@ def add_arguments(self, parser): 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('--file', dest="file", default=None, type=str) + parser.add_argument('--api_version', dest="api_version", default='', type=str) def handle(self, *args, **options): if options['generator_class']: @@ -37,6 +38,7 @@ def handle(self, *args, **options): title=options['title'], description=options['description'], urlconf=options['urlconf'], + version=options['api_version'], ) schema = generator.get_schema(request=None, public=True) renderer = self.get_renderer(options['format']) diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py index 8a44f2aad38..015587897d6 100644 --- a/rest_framework/metadata.py +++ b/rest_framework/metadata.py @@ -36,7 +36,6 @@ class SimpleMetadata(BaseMetadata): label_lookup = ClassLookupDict({ serializers.Field: 'field', serializers.BooleanField: 'boolean', - serializers.NullBooleanField: 'boolean', serializers.CharField: 'string', serializers.UUIDField: 'string', serializers.URLField: 'url', @@ -49,6 +48,7 @@ class SimpleMetadata(BaseMetadata): serializers.DateField: 'date', serializers.DateTimeField: 'datetime', serializers.TimeField: 'time', + serializers.DurationField: 'duration', serializers.ChoiceField: 'choice', serializers.MultipleChoiceField: 'multiple choice', serializers.FileField: 'file upload', diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index e815d8d5cff..50e5aaacbea 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -2,6 +2,8 @@ Pagination serializers determine the structure of the output that should be used for paginated responses. """ + +import contextlib from base64 import b64decode, b64encode from collections import OrderedDict, namedtuple from urllib import parse @@ -193,6 +195,7 @@ def paginate_queryset(self, queryset, request, view=None): Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. """ + self.request = request page_size = self.get_page_size(request) if not page_size: return None @@ -212,7 +215,6 @@ def paginate_queryset(self, queryset, request, view=None): # The browsable API should display pagination controls. self.display_page_controls = True - self.request = request return list(self.page) def get_page_number(self, request, paginator): @@ -257,15 +259,12 @@ def get_paginated_response_schema(self, schema): def get_page_size(self, request): if self.page_size_query_param: - try: + with contextlib.suppress(KeyError, ValueError): return _positive_int( request.query_params[self.page_size_query_param], strict=True, cutoff=self.max_page_size ) - except (KeyError, ValueError): - pass - return self.page_size def get_next_link(self): @@ -380,13 +379,13 @@ class LimitOffsetPagination(BasePagination): template = 'rest_framework/pagination/numbers.html' def paginate_queryset(self, queryset, request, view=None): + self.request = request self.limit = self.get_limit(request) if self.limit is None: return None self.count = self.get_count(queryset) self.offset = self.get_offset(request) - self.request = request if self.count > self.limit and self.template is not None: self.display_page_controls = True @@ -430,15 +429,12 @@ def get_paginated_response_schema(self, schema): def get_limit(self, request): if self.limit_query_param: - try: + with contextlib.suppress(KeyError, ValueError): return _positive_int( request.query_params[self.limit_query_param], strict=True, cutoff=self.max_limit ) - except (KeyError, ValueError): - pass - return self.default_limit def get_offset(self, request): @@ -603,6 +599,7 @@ class CursorPagination(BasePagination): offset_cutoff = 1000 def paginate_queryset(self, queryset, request, view=None): + self.request = request self.page_size = self.get_page_size(request) if not self.page_size: return None @@ -680,15 +677,12 @@ def paginate_queryset(self, queryset, request, view=None): def get_page_size(self, request): if self.page_size_query_param: - try: + with contextlib.suppress(KeyError, ValueError): return _positive_int( request.query_params[self.page_size_query_param], strict=True, cutoff=self.max_page_size ) - except (KeyError, ValueError): - pass - return self.page_size def get_next_link(self): @@ -905,10 +899,16 @@ def get_paginated_response_schema(self, schema): 'next': { 'type': 'string', 'nullable': True, + 'format': 'uri', + 'example': 'http://api.example.org/accounts/?{cursor_query_param}=cD00ODY%3D"'.format( + cursor_query_param=self.cursor_query_param) }, 'previous': { 'type': 'string', 'nullable': True, + 'format': 'uri', + 'example': 'http://api.example.org/accounts/?{cursor_query_param}=cj0xJnA9NDg3'.format( + cursor_query_param=self.cursor_query_param) }, 'results': schema, }, diff --git a/rest_framework/parsers.py b/rest_framework/parsers.py index 4ee8e578b88..f0fd2b8844e 100644 --- a/rest_framework/parsers.py +++ b/rest_framework/parsers.py @@ -4,7 +4,9 @@ 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. """ + import codecs +import contextlib from django.conf import settings from django.core.files.uploadhandler import StopFutureHandlers @@ -193,17 +195,12 @@ def get_filename(self, stream, media_type, parser_context): Detects the uploaded file name. First searches a 'filename' url kwarg. Then tries to parse Content-Disposition header. """ - try: + with contextlib.suppress(KeyError): return parser_context['kwargs']['filename'] - except KeyError: - pass - try: + with contextlib.suppress(AttributeError, KeyError, ValueError): meta = parser_context['request'].META disposition, params = parse_header_parameters(meta['HTTP_CONTENT_DISPOSITION']) if 'filename*' in params: return params['filename*'] - else: - return params['filename'] - except (AttributeError, KeyError, ValueError): - pass + return params['filename'] diff --git a/rest_framework/permissions.py b/rest_framework/permissions.py index 3a8c5806465..f3ebbcffa72 100644 --- a/rest_framework/permissions.py +++ b/rest_framework/permissions.py @@ -46,6 +46,14 @@ def __call__(self, *args, **kwargs): op2 = self.op2_class(*args, **kwargs) 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: def __init__(self, op1, op2): @@ -78,8 +86,11 @@ def has_permission(self, request, view): def has_object_permission(self, request, view, obj): return ( - self.op1.has_object_permission(request, view, obj) or - self.op2.has_object_permission(request, view, obj) + self.op1.has_permission(request, view) + 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) ) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index bdedd43b86e..62da685fb6a 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -1,3 +1,4 @@ +import contextlib import sys from collections import OrderedDict from urllib import parse @@ -170,7 +171,7 @@ def use_pk_only_optimization(self): def get_attribute(self, instance): if self.use_pk_only_optimization() and self.source_attrs: # 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]) value = attribute_instance.serializable_value(self.source_attrs[-1]) if is_simple_callable(value): @@ -183,9 +184,6 @@ def get_attribute(self, instance): value = getattr(value, 'pk', value) return PKOnlyObject(pk=value) - except AttributeError: - pass - # Standard case, return the object instance. return super().get_attribute(instance) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index b74df9a0bb9..3f47580f157 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -6,7 +6,9 @@ REST framework also provides an HTML renderer that renders the browsable API. """ + import base64 +import contextlib from collections import OrderedDict from urllib import parse @@ -72,11 +74,8 @@ def get_indent(self, accepted_media_type, renderer_context): # then pretty print the result. # Note that we coerce `indent=0` into `indent=None`. 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)) - except (KeyError, ValueError, TypeError): - pass - # If 'indent' is provided in the context, then pretty print the result. # E.g. If we're being called by the BrowsableAPIRenderer. return renderer_context.get('indent', None) @@ -488,11 +487,8 @@ def get_rendered_html_form(self, data, view, method, request): return if existing_serializer is not None: - try: + with contextlib.suppress(TypeError): return self.render_form_for_serializer(existing_serializer) - except TypeError: - pass - if has_serializer: if method in ('PUT', 'PATCH'): serializer = view.get_serializer(instance=instance, **kwargs) diff --git a/rest_framework/request.py b/rest_framework/request.py index 93634e667d4..194be5f6d4d 100644 --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -413,7 +413,8 @@ def __getattr__(self, attr): to proxy it to the underlying HttpRequest object. """ try: - return getattr(self._request, attr) + _request = self.__getattribute__("_request") + return getattr(_request, attr) except AttributeError: return self.__getattribute__(attr) diff --git a/rest_framework/schemas/inspectors.py b/rest_framework/schemas/inspectors.py index 027472db14c..cb880e79d66 100644 --- a/rest_framework/schemas/inspectors.py +++ b/rest_framework/schemas/inspectors.py @@ -88,7 +88,7 @@ def get_description(self, path, method): view.get_view_description()) def _get_description_section(self, view, header, description): - lines = [line for line in description.splitlines()] + lines = description.splitlines() current_section = '' sections = {'': ''} diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py index 122846376f2..2f9fb9f28f3 100644 --- a/rest_framework/schemas/openapi.py +++ b/rest_framework/schemas/openapi.py @@ -13,7 +13,7 @@ from django.utils.encoding import force_str from rest_framework import ( - RemovedInDRF314Warning, exceptions, renderers, serializers + RemovedInDRF315Warning, exceptions, renderers, serializers ) from rest_framework.compat import uritemplate from rest_framework.fields import _UnvalidatedField, empty @@ -523,7 +523,7 @@ def map_serializer(self, serializer): continue if field.required: - required.append(field.field_name) + required.append(self.get_field_name(field)) schema = self.map_field(field) if field.read_only: @@ -538,7 +538,7 @@ def map_serializer(self, serializer): schema['description'] = str(field.help_text) self.map_field_validators(field, schema) - properties[field.field_name] = schema + properties[self.get_field_name(field)] = schema result = { 'type': 'object', @@ -589,6 +589,13 @@ def map_field_validators(self, field, schema): schema['maximum'] = int(digits * '9') + 1 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): pagination_class = getattr(self.view, 'pagination_class', None) if pagination_class: @@ -713,106 +720,10 @@ def get_tags(self, path, method): 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): warnings.warn( "Method `_get_reference()` has been renamed to `get_reference()`. " - "The old name will be removed in DRF v3.14.", - RemovedInDRF314Warning, stacklevel=2 + "The old name will be removed in DRF v3.15.", + RemovedInDRF315Warning, stacklevel=2 ) return self.get_reference(serializer) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 9dfb90f7691..eae6a0b2e14 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -10,6 +10,8 @@ 2. The process of marshalling between python primitives and request and response content is handled by parsers and renderers. """ + +import contextlib import copy import inspect import traceback @@ -52,7 +54,7 @@ BooleanField, CharField, ChoiceField, DateField, DateTimeField, DecimalField, DictField, DurationField, EmailField, Field, FileField, FilePathField, FloatField, HiddenField, HStoreField, IPAddressField, ImageField, IntegerField, JSONField, - ListField, ModelField, MultipleChoiceField, NullBooleanField, ReadOnlyField, + ListField, ModelField, MultipleChoiceField, ReadOnlyField, RegexField, SerializerMethodField, SlugField, TimeField, URLField, UUIDField, ) from rest_framework.relations import ( # NOQA # isort:skip @@ -1496,12 +1498,10 @@ def _get_model_fields(self, field_names, declared_fields, extra_kwargs): # they can't be nested attribute lookups. continue - try: + with contextlib.suppress(FieldDoesNotExist): field = model._meta.get_field(source) if isinstance(field, DjangoModelField): model_fields[source] = field - except FieldDoesNotExist: - pass return model_fields diff --git a/rest_framework/settings.py b/rest_framework/settings.py index 9eb4c5653b2..96b66457422 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -19,7 +19,9 @@ back to the defaults. """ 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 rest_framework import ISO_8601 diff --git a/rest_framework/static/rest_framework/docs/js/api.js b/rest_framework/static/rest_framework/docs/js/api.js index e6120cd8eb5..21663deb67c 100644 --- a/rest_framework/static/rest_framework/docs/js/api.js +++ b/rest_framework/static/rest_framework/docs/js/api.js @@ -131,13 +131,7 @@ $(function () { if (value !== undefined) { params[paramKey] = value } - } else if (dataType === 'array' && paramValue) { - try { - params[paramKey] = JSON.parse(paramValue) - } catch (err) { - // Ignore malformed JSON - } - } else if (dataType === 'object' && paramValue) { + } else if ((dataType === 'array' && paramValue) || (dataType === 'object' && paramValue)) { try { params[paramKey] = JSON.parse(paramValue) } catch (err) { diff --git a/rest_framework/test.py b/rest_framework/test.py index 07df743c8e4..04409f9621d 100644 --- a/rest_framework/test.py +++ b/rest_framework/test.py @@ -277,7 +277,7 @@ def force_authenticate(self, user=None, token=None): """ self.handler._force_user = user 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 def request(self, **kwargs): diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index 27293b72528..35a89eb0902 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -1,6 +1,8 @@ """ Helper classes for parsers. """ + +import contextlib import datetime import decimal import json # noqa @@ -58,10 +60,8 @@ def default(self, obj): ) elif hasattr(obj, '__getitem__'): cls = (list if isinstance(obj, (list, tuple)) else dict) - try: + with contextlib.suppress(Exception): return cls(obj) - except Exception: - pass elif hasattr(obj, '__iter__'): return tuple(item for item in obj) return super().default(obj) diff --git a/rest_framework/utils/serializer_helpers.py b/rest_framework/utils/serializer_helpers.py index 54068f5fb05..6ca794584bf 100644 --- a/rest_framework/utils/serializer_helpers.py +++ b/rest_framework/utils/serializer_helpers.py @@ -1,3 +1,4 @@ +import contextlib import sys from collections import OrderedDict from collections.abc import Mapping, MutableMapping @@ -103,15 +104,13 @@ def as_form_field(self): # When HTML form input is used and the input is not valid # value will be a JSONString, rather than a JSON primitive. if not getattr(value, 'is_json_string', False): - try: + with contextlib.suppress(TypeError, ValueError): value = json.dumps( self.value, sort_keys=True, indent=4, separators=(',', ': '), ) - except (TypeError, ValueError): - pass return self.__class__(self._field, value, self.errors, self._prefix) diff --git a/rest_framework/views.py b/rest_framework/views.py index 5b062206911..4c30029fdc5 100644 --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -79,9 +79,9 @@ def exception_handler(exc, context): to be raised. """ if isinstance(exc, Http404): - exc = exceptions.NotFound() + exc = exceptions.NotFound(*(exc.args)) elif isinstance(exc, PermissionDenied): - exc = exceptions.PermissionDenied() + exc = exceptions.PermissionDenied(*(exc.args)) if isinstance(exc, exceptions.APIException): headers = {} diff --git a/setup.cfg b/setup.cfg index 1c85a69e4ae..294e9afdd62 100644 --- a/setup.cfg +++ b/setup.cfg @@ -5,7 +5,7 @@ license_files = LICENSE.md addopts=--tb=short --strict-markers -ra [flake8] -ignore = E501,W504 +ignore = E501,W503,W504 banned-modules = json = use from rest_framework.utils import json! [isort] diff --git a/setup.py b/setup.py index cb6708c6e91..d0047026805 100755 --- a/setup.py +++ b/setup.py @@ -82,14 +82,13 @@ def get_version(package): author_email='tom@tomchristie.com', # SEE NOTE BELOW (*) packages=find_packages(exclude=['tests*']), include_package_data=True, - install_requires=["django>=2.2", "pytz"], + install_requires=["django>=3.0", "pytz"], python_requires=">=3.6", zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', - 'Framework :: Django :: 2.2', 'Framework :: Django :: 3.0', 'Framework :: Django :: 3.1', 'Framework :: Django :: 3.2', @@ -105,6 +104,7 @@ def get_version(package): 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3 :: Only', 'Topic :: Internet :: WWW/HTTP', ], diff --git a/tests/authentication/test_authentication.py b/tests/authentication/test_authentication.py index d771aaf8b49..b64c05de844 100644 --- a/tests/authentication/test_authentication.py +++ b/tests/authentication/test_authentication.py @@ -219,8 +219,8 @@ def test_post_form_session_auth_passing_csrf(self): Ensure POSTing form over session authentication with CSRF token succeeds. Regression test for #6088 """ - # Remove this shim when dropping support for Django 2.2. - if django.VERSION < (3, 0): + # Remove this shim when dropping support for Django 3.0. + if django.VERSION < (3, 1): from django.middleware.csrf import _get_new_csrf_token else: from django.middleware.csrf import ( diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py index daa035a3f35..7542bb61522 100644 --- a/tests/schemas/test_openapi.py +++ b/tests/schemas/test_openapi.py @@ -111,6 +111,20 @@ class Serializer(serializers.Serializer): 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" + 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): class Model(models.Model): rw_field = models.CharField(null=True) diff --git a/tests/test_fields.py b/tests/test_fields.py index 56276e6ffc1..3112fc2cced 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -239,7 +239,7 @@ class BuiltinSerializer(serializers.Serializer): class TestReadOnly: - def setup(self): + def setup_method(self): class TestSerializer(serializers.Serializer): read_only = serializers.ReadOnlyField(default="789") writable = serializers.IntegerField() @@ -271,7 +271,7 @@ def test_serialize_read_only(self): class TestWriteOnly: - def setup(self): + def setup_method(self): class TestSerializer(serializers.Serializer): write_only = serializers.IntegerField(write_only=True) readable = serializers.IntegerField() @@ -296,7 +296,7 @@ def test_serialize_write_only(self): class TestInitial: - def setup(self): + def setup_method(self): class TestSerializer(serializers.Serializer): initial_field = serializers.IntegerField(initial=123) blank_field = serializers.IntegerField() @@ -313,7 +313,7 @@ def test_initial(self): class TestInitialWithCallable: - def setup(self): + def setup_method(self): def initial_value(): return 123 @@ -331,7 +331,7 @@ def test_initial_should_accept_callable(self): class TestLabel: - def setup(self): + def setup_method(self): class TestSerializer(serializers.Serializer): labeled = serializers.IntegerField(label='My label') self.serializer = TestSerializer() @@ -345,7 +345,7 @@ def test_label(self): class TestInvalidErrorKey: - def setup(self): + def setup_method(self): class ExampleField(serializers.Field): def to_native(self, data): self.fail('incorrect') @@ -539,7 +539,7 @@ class TestSerializer(serializers.Serializer): class TestCreateOnlyDefault: - def setup(self): + def setup_method(self): default = serializers.CreateOnlyDefault('2001-01-01') class TestSerializer(serializers.Serializer): @@ -679,9 +679,9 @@ def test_disallow_unhashable_collection_types(self): 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 = { 'true': True, @@ -706,16 +706,6 @@ class TestNullBooleanField(TestBooleanField): 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... class TestCharField(FieldValues): @@ -1261,6 +1251,27 @@ def test_part_precision_string_quantized_value_for_decimal(self): 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): valid_inputs = { '0.12345': Decimal('0.12345'), diff --git a/tests/test_generics.py b/tests/test_generics.py index 2907d277336..78dc5afb64f 100644 --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -5,6 +5,7 @@ from django.test import TestCase from rest_framework import generics, renderers, serializers, status +from rest_framework.exceptions import ErrorDetail from rest_framework.response import Response from rest_framework.test import APIRequestFactory from tests.models import ( @@ -519,7 +520,12 @@ def test_get_instance_view_filters_out_name_with_filter_backend(self): request = factory.get('/1') response = instance_view(request, pk=1).render() 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): """ diff --git a/tests/test_pagination.py b/tests/test_pagination.py index c028f0ea8b2..74a65bf5062 100644 --- a/tests/test_pagination.py +++ b/tests/test_pagination.py @@ -18,7 +18,7 @@ class TestPaginationIntegration: Integration tests. """ - def setup(self): + def setup_method(self): class PassThroughSerializer(serializers.BaseSerializer): def to_representation(self, item): return item @@ -140,7 +140,7 @@ class TestPaginationDisabledIntegration: Integration tests for disabled pagination. """ - def setup(self): + def setup_method(self): class PassThroughSerializer(serializers.BaseSerializer): def to_representation(self, item): return item @@ -163,7 +163,7 @@ class TestPageNumberPagination: Unit tests for `pagination.PageNumberPagination`. """ - def setup(self): + def setup_method(self): class ExamplePagination(pagination.PageNumberPagination): page_size = 5 @@ -302,7 +302,7 @@ class TestPageNumberPaginationOverride: the Django Paginator Class is overridden. """ - def setup(self): + def setup_method(self): class OverriddenDjangoPaginator(DjangoPaginator): # override the count in our overridden Django Paginator # we will only return one page, with one item @@ -358,7 +358,7 @@ class TestLimitOffset: Unit tests for `pagination.LimitOffsetPagination`. """ - def setup(self): + def setup_method(self): class ExamplePagination(pagination.LimitOffsetPagination): default_limit = 10 max_limit = 15 @@ -922,10 +922,14 @@ def test_get_paginated_response_schema(self): 'next': { 'type': 'string', 'nullable': True, + 'format': 'uri', + 'example': 'http://api.example.org/accounts/?cursor=cD00ODY%3D"' }, 'previous': { 'type': 'string', 'nullable': True, + 'format': 'uri', + 'example': 'http://api.example.org/accounts/?cursor=cj0xJnA9NDg3' }, 'results': unpaginated_schema, }, @@ -937,7 +941,7 @@ class TestCursorPagination(CursorPaginationTestsMixin): Unit tests for `pagination.CursorPagination`. """ - def setup(self): + def setup_method(self): class MockObject: def __init__(self, idx): self.created = idx diff --git a/tests/test_permissions.py b/tests/test_permissions.py index 4e6cae4b811..f00b57ec19f 100644 --- a/tests/test_permissions.py +++ b/tests/test_permissions.py @@ -635,7 +635,7 @@ def test_object_or_lazyness(self): composed_perm = (permissions.IsAuthenticated | permissions.AllowAny) hasperm = composed_perm().has_object_permission(request, None, None) assert hasperm is True - assert mock_deny.call_count == 1 + assert mock_deny.call_count == 0 assert mock_allow.call_count == 1 def test_and_lazyness(self): @@ -677,3 +677,16 @@ def test_object_and_lazyness(self): assert hasperm is False assert mock_deny.call_count == 1 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 diff --git a/tests/test_relations.py b/tests/test_relations.py index bb719a65a97..7a4db1c4875 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -374,7 +374,7 @@ def test_get_value_multi_dictionary_partial(self): class TestHyperlink: - def setup(self): + def setup_method(self): self.default_hyperlink = serializers.Hyperlink('http://example.com', 'test') def test_can_be_pickled(self): diff --git a/tests/test_request.py b/tests/test_request.py index 8f55d00ed4f..8c18aea9e67 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -1,6 +1,7 @@ """ Tests for content parsing, and form-overloaded content parsing. """ +import copy import os.path import tempfile @@ -344,3 +345,10 @@ def test_duplicate_request_form_data_access(self): # ensure that request stream was consumed by form parser assert request.content_type.startswith('multipart/form-data') assert response.data == {'a': ['b']} + + +class TestDeepcopy(TestCase): + + def test_deepcopy_works(self): + request = Request(factory.get('/', secure=False)) + copy.deepcopy(request) diff --git a/tests/test_serializer.py b/tests/test_serializer.py index c4c29ba4ade..1d9efaa4344 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -61,7 +61,7 @@ def test_relations(self): # ----------------------------- class TestSerializer: - def setup(self): + def setup_method(self): class ExampleSerializer(serializers.Serializer): char = serializers.CharField() integer = serializers.IntegerField() @@ -240,7 +240,7 @@ def validate(self, attrs): class TestBaseSerializer: - def setup(self): + def setup_method(self): class ExampleSerializer(serializers.BaseSerializer): def to_representation(self, obj): return { @@ -337,7 +337,7 @@ class TestStarredSource: 'nested2': {'c': 3, 'd': 4} } - def setup(self): + def setup_method(self): class NestedSerializer1(serializers.Serializer): a = serializers.IntegerField() b = serializers.IntegerField() @@ -463,7 +463,7 @@ def create(self, validated_data): class TestDefaultOutput: - def setup(self): + def setup_method(self): class ExampleSerializer(serializers.Serializer): has_default = serializers.CharField(default='x') has_default_callable = serializers.CharField(default=lambda: 'y') @@ -584,7 +584,7 @@ class ExampleSerializer(serializers.Serializer): class TestDefaultInclusions: - def setup(self): + def setup_method(self): class ExampleSerializer(serializers.Serializer): char = serializers.CharField(default='abc') integer = serializers.IntegerField() @@ -612,7 +612,7 @@ def test_default_should_not_be_included_on_partial_update(self): class TestSerializerValidationWithCompiledRegexField: - def setup(self): + def setup_method(self): class ExampleSerializer(serializers.Serializer): name = serializers.RegexField(re.compile(r'\d'), required=True) self.Serializer = ExampleSerializer @@ -641,7 +641,7 @@ class ParentSerializer(serializers.Serializer): class Test4606Regression: - def setup(self): + def setup_method(self): class ExampleSerializer(serializers.Serializer): name = serializers.CharField(required=True) choices = serializers.CharField(required=True) diff --git a/tests/test_serializer_lists.py b/tests/test_serializer_lists.py index 661799fae4b..74af2f3d8ed 100644 --- a/tests/test_serializer_lists.py +++ b/tests/test_serializer_lists.py @@ -37,7 +37,7 @@ class TestListSerializer: Note that this is in contrast to using ListSerializer as a field. """ - def setup(self): + def setup_method(self): class IntegerListSerializer(serializers.ListSerializer): child = serializers.IntegerField() self.Serializer = IntegerListSerializer @@ -75,7 +75,7 @@ class TestListSerializerContainingNestedSerializer: Tests for using a ListSerializer containing another serializer. """ - def setup(self): + def setup_method(self): class TestSerializer(serializers.Serializer): integer = serializers.IntegerField() boolean = serializers.BooleanField() @@ -161,7 +161,7 @@ class TestNestedListSerializer: Tests for using a ListSerializer as a field. """ - def setup(self): + def setup_method(self): class TestSerializer(serializers.Serializer): integers = serializers.ListSerializer(child=serializers.IntegerField()) booleans = serializers.ListSerializer(child=serializers.BooleanField()) @@ -283,7 +283,7 @@ class ParentSerializer(serializers.Serializer): class TestNestedListOfListsSerializer: - def setup(self): + def setup_method(self): class TestSerializer(serializers.Serializer): integers = serializers.ListSerializer( child=serializers.ListSerializer( @@ -599,7 +599,7 @@ class TestEmptyListSerializer: Tests the behaviour of ListSerializers when there is no data passed to it """ - def setup(self): + def setup_method(self): class ExampleListSerializer(serializers.ListSerializer): child = serializers.IntegerField() @@ -628,7 +628,7 @@ class TestMaxMinLengthListSerializer: Tests the behaviour of ListSerializers when max_length and min_length are used """ - def setup(self): + def setup_method(self): class IntegerSerializer(serializers.Serializer): some_int = serializers.IntegerField() diff --git a/tests/test_serializer_nested.py b/tests/test_serializer_nested.py index 09ac37f246c..986972a65a8 100644 --- a/tests/test_serializer_nested.py +++ b/tests/test_serializer_nested.py @@ -9,7 +9,7 @@ class TestNestedSerializer: - def setup(self): + def setup_method(self): class NestedSerializer(serializers.Serializer): one = serializers.IntegerField(max_value=10) two = serializers.IntegerField(max_value=10) @@ -54,7 +54,7 @@ def test_nested_serialize_no_data(self): class TestNotRequiredNestedSerializer: - def setup(self): + def setup_method(self): class NestedSerializer(serializers.Serializer): one = serializers.IntegerField(max_value=10) @@ -83,7 +83,7 @@ def test_multipart_validate(self): class TestNestedSerializerWithMany: - def setup(self): + def setup_method(self): class NestedSerializer(serializers.Serializer): example = serializers.IntegerField(max_value=10) @@ -181,7 +181,7 @@ def test_empty_not_allowed_if_allow_empty_is_set_to_false(self): class TestNestedSerializerWithList: - def setup(self): + def setup_method(self): class NestedSerializer(serializers.Serializer): example = serializers.MultipleChoiceField(choices=[1, 2, 3]) @@ -210,7 +210,7 @@ def test_nested_serializer_with_list_multipart(self): class TestNotRequiredNestedSerializerWithMany: - def setup(self): + def setup_method(self): class NestedSerializer(serializers.Serializer): one = serializers.IntegerField(max_value=10) diff --git a/tests/test_status.py b/tests/test_status.py index b10f7df9949..4d7aeb90a6d 100644 --- a/tests/test_status.py +++ b/tests/test_status.py @@ -7,27 +7,27 @@ class TestStatus(TestCase): def test_status_categories(self): - self.assertFalse(is_informational(99)) - self.assertTrue(is_informational(100)) - self.assertTrue(is_informational(199)) - self.assertFalse(is_informational(200)) + assert not is_informational(99) + assert is_informational(100) + assert is_informational(199) + assert not is_informational(200) - self.assertFalse(is_success(199)) - self.assertTrue(is_success(200)) - self.assertTrue(is_success(299)) - self.assertFalse(is_success(300)) + assert not is_success(199) + assert is_success(200) + assert is_success(299) + assert not is_success(300) - self.assertFalse(is_redirect(299)) - self.assertTrue(is_redirect(300)) - self.assertTrue(is_redirect(399)) - self.assertFalse(is_redirect(400)) + assert not is_redirect(299) + assert is_redirect(300) + assert is_redirect(399) + assert not is_redirect(400) - self.assertFalse(is_client_error(399)) - self.assertTrue(is_client_error(400)) - self.assertTrue(is_client_error(499)) - self.assertFalse(is_client_error(500)) + assert not is_client_error(399) + assert is_client_error(400) + assert is_client_error(499) + assert not is_client_error(500) - self.assertFalse(is_server_error(499)) - self.assertTrue(is_server_error(500)) - self.assertTrue(is_server_error(599)) - self.assertFalse(is_server_error(600)) + assert not is_server_error(499) + assert is_server_error(500) + assert is_server_error(599) + assert not is_server_error(600) diff --git a/tests/test_testing.py b/tests/test_testing.py index b6579e3690e..196319a29ee 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -10,6 +10,7 @@ from django.urls import path from rest_framework import fields, serializers +from rest_framework.authtoken.models import Token from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.test import ( @@ -19,10 +20,12 @@ @api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']) def view(request): - return Response({ - 'auth': request.META.get('HTTP_AUTHORIZATION', b''), - 'user': request.user.username - }) + data = {'auth': request.META.get('HTTP_AUTHORIZATION', b'')} + if request.user: + data['user'] = request.user.username + if request.auth: + data['token'] = request.auth.key + return Response(data) @api_view(['GET', 'POST']) @@ -78,14 +81,46 @@ def test_credentials(self): response = self.client.get('/view/') 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') - self.client.force_authenticate(user) + + self.client.force_authenticate(user=user) + response = self.client.get('/view/') + + 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): """ @@ -102,8 +137,9 @@ def test_force_authenticate_with_sessions(self): response = self.client.get('/session-view/') assert response.data['active_session'] is True - # Force authenticating as `None` should also logout the user session. - self.client.force_authenticate(None) + # Force authenticating with `None` user and token should also logout + # the user session. + self.client.force_authenticate(user=None, token=None) response = self.client.get('/session-view/') assert response.data['active_session'] is False diff --git a/tox.ini b/tox.ini index c275a0abef0..2b421f6c271 100644 --- a/tox.ini +++ b/tox.ini @@ -1,14 +1,15 @@ [tox] envlist = - {py36,py37,py38,py39}-django22, + {py36,py37,py38,py39}-django30, {py36,py37,py38,py39}-django31, {py36,py37,py38,py39,py310}-django32, {py38,py39,py310}-{django40,django41,djangomain}, + {py311}-{django41,djangomain}, base,dist,docs, [travis:env] DJANGO = - 2.2: django22 + 3.0: django30 3.1: django31 3.2: django32 4.0: django40 @@ -22,11 +23,11 @@ setenv = PYTHONDONTWRITEBYTECODE=1 PYTHONWARNINGS=once deps = - django22: Django>=2.2,<3.0 + django30: Django>=3.0,<3.1 django31: Django>=3.1,<3.2 django32: Django>=3.2,<4.0 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 -rrequirements/requirements-testing.txt -rrequirements/requirements-optionals.txt @@ -59,3 +60,6 @@ ignore_outcome = true [testenv:py310-djangomain] ignore_outcome = true + +[testenv:py311-djangomain] +ignore_outcome = true