From acf6582de474ad7f0c5f97d59208691c09c049c0 Mon Sep 17 00:00:00 2001 From: Aaron Taajik <75927372+aaronn44@users.noreply.github.com> Date: Fri, 9 Sep 2022 18:57:15 +0430 Subject: [PATCH 01/47] Docs: edit headings in Authentication (#8644) --- docs/api-guide/authentication.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index fca9374d0..d30b6fed8 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,7 +199,7 @@ 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: @@ -248,7 +248,7 @@ 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`. @@ -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`. From 354ae73ffb37494016f377527a52ea51ed4c29f7 Mon Sep 17 00:00:00 2001 From: willbeaufoy Date: Thu, 15 Sep 2022 09:35:48 +0100 Subject: [PATCH 02/47] Make `APIClient.force_authenticate()` work with `user=None` (#8212) * Fix testing with token * Add unit test * Split unit test into 3 * Fix linting error --- rest_framework/test.py | 2 +- tests/test_testing.py | 54 +++++++++++++++++++++++++++++++++++------- 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/rest_framework/test.py b/rest_framework/test.py index 07df743c8..04409f962 100644 --- a/rest_framework/test.py +++ b/rest_framework/test.py @@ -277,7 +277,7 @@ class APIClient(APIRequestFactory, DjangoClient): """ 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/tests/test_testing.py b/tests/test_testing.py index b6579e369..196319a29 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -10,6 +10,7 @@ from django.test import TestCase, override_settings 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 @@ from rest_framework.test import ( @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 @@ class TestAPITestClient(TestCase): 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 @@ class TestAPITestClient(TestCase): 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 From 4aea8dd65a82c7d8f73c9bffe39309b1adb2ae2f Mon Sep 17 00:00:00 2001 From: David Smith <39445562+smithdc1@users.noreply.github.com> Date: Wed, 21 Sep 2022 12:19:33 +0100 Subject: [PATCH 03/47] Change semantic of OR of two permission classes (#7522) * Change semantic of OR of two permission classes The original semantic of OR is defined as: the request pass either of the two has_permission() check, and pass either of the two has_object_permission() check, which could lead to situations that a request passes has_permission() but fails on has_object_permission() of Permission Class A, fails has_permission() but passes has_object_permission() of Permission Class B, passes the OR permission check. This should not be the desired permission check semantic in applications, because such a request should fail on either Permission Class (on Django object permission) alone, but passes the OR or the two. My code fix this by changing the semantic so that the request has to pass either class's has_permission() and has_object_permission() to get the Django object permission of the OR check. * Update rest_framework/permissions.py * Update setup.cfg Co-authored-by: Mark Yu Co-authored-by: Tom Christie --- rest_framework/permissions.py | 7 +++++-- setup.cfg | 2 +- tests/test_permissions.py | 15 ++++++++++++++- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/rest_framework/permissions.py b/rest_framework/permissions.py index 3a8c58064..16459b251 100644 --- a/rest_framework/permissions.py +++ b/rest_framework/permissions.py @@ -78,8 +78,11 @@ class OR: 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/setup.cfg b/setup.cfg index 1c85a69e4..294e9afdd 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/tests/test_permissions.py b/tests/test_permissions.py index 4e6cae4b8..f00b57ec1 100644 --- a/tests/test_permissions.py +++ b/tests/test_permissions.py @@ -635,7 +635,7 @@ class PermissionsCompositionTests(TestCase): 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 @@ class PermissionsCompositionTests(TestCase): 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 From 3401ef56f8f924fb14bc9baa6a913bd556c646c6 Mon Sep 17 00:00:00 2001 From: Cihan Eran Date: Wed, 21 Sep 2022 15:08:21 +0300 Subject: [PATCH 04/47] Add --version CLI option to generateschema (#8552) --- rest_framework/management/commands/generateschema.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rest_framework/management/commands/generateschema.py b/rest_framework/management/commands/generateschema.py index 024306b65..0cc6953b2 100644 --- a/rest_framework/management/commands/generateschema.py +++ b/rest_framework/management/commands/generateschema.py @@ -26,6 +26,7 @@ class Command(BaseCommand): 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('--version', dest="version", default='', type=str) def handle(self, *args, **options): if options['generator_class']: @@ -37,6 +38,7 @@ class Command(BaseCommand): title=options['title'], description=options['description'], urlconf=options['urlconf'], + version=options['version'], ) schema = generator.get_schema(request=None, public=True) renderer = self.get_renderer(options['format']) From 51f1aff162eecdd61a05244628cd959cda5c0191 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 21 Sep 2022 14:03:39 +0100 Subject: [PATCH 05/47] Revert 8552 (#8661) --- rest_framework/management/commands/generateschema.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/rest_framework/management/commands/generateschema.py b/rest_framework/management/commands/generateschema.py index 0cc6953b2..024306b65 100644 --- a/rest_framework/management/commands/generateschema.py +++ b/rest_framework/management/commands/generateschema.py @@ -26,7 +26,6 @@ class Command(BaseCommand): 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('--version', dest="version", default='', type=str) def handle(self, *args, **options): if options['generator_class']: @@ -38,7 +37,6 @@ class Command(BaseCommand): title=options['title'], description=options['description'], urlconf=options['urlconf'], - version=options['version'], ) schema = generator.get_schema(request=None, public=True) renderer = self.get_renderer(options['format']) From b658915846c257531db5d869feaada7af71980f0 Mon Sep 17 00:00:00 2001 From: Tim Schilling Date: Wed, 21 Sep 2022 08:08:12 -0500 Subject: [PATCH 06/47] Version 3.14.0 proposal (#8599) * Version 3.14.0 * Update docs/community/release-notes.md to use proper links. Co-authored-by: Adam Johnson * Add community announcement page for version 3.14 * Remove deprecated NullBooleanField. * Change openapi _get_reference removal to 3.15 This deprecation was never released in the 3.13.x series and therefore can't be removed at the same time the replacement is released. * Removing deprecated openapi methods. Co-authored-by: Adam Johnson --- docs/api-guide/fields.md | 8 --- docs/community/3.14-announcement.md | 62 +++++++++++++++++ docs/community/release-notes.md | 17 +++++ rest_framework/__init__.py | 6 +- rest_framework/fields.py | 20 +----- rest_framework/metadata.py | 1 - rest_framework/schemas/openapi.py | 102 +--------------------------- rest_framework/serializers.py | 2 +- tests/test_fields.py | 14 +--- 9 files changed, 91 insertions(+), 141 deletions(-) create mode 100644 docs/community/3.14-announcement.md diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index e9ef5c6b6..1e9436213 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -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 diff --git a/docs/community/3.14-announcement.md b/docs/community/3.14-announcement.md new file mode 100644 index 000000000..04d1572b1 --- /dev/null +++ b/docs/community/3.14-announcement.md @@ -0,0 +1,62 @@ + + +# Django REST framework 3.14 + +## Django 4.1 support + +The latest release now fully supports Django 4.1. + +Our requirements are now: + +* Python 3.6+ +* Django 4.1, 4.0, 3.2, 3.1, 2.2 (LTS) + +## `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/release-notes.md b/docs/community/release-notes.md index 8629e4fee..dc8227035 100644 --- a/docs/community/release-notes.md +++ b/docs/community/release-notes.md @@ -34,6 +34,23 @@ You can determine your currently installed version using `pip show`: --- +## 3.14.x series + +### 3.14.0 + +Date: 10th August 2022 + +* Enforce `is_valid(raise_exception=False)` as a keyword-only argument. [[#7952](https://github.com/encode/django-rest-framework/pull/7952)] +* Django 4.1 compatability. [[#8591](https://github.com/encode/django-rest-framework/pull/8591)] +* 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/rest_framework/__init__.py b/rest_framework/__init__.py index 8b0679ef9..568e08074 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' @@ -35,3 +35,7 @@ class RemovedInDRF313Warning(DeprecationWarning): class RemovedInDRF314Warning(PendingDeprecationWarning): pass + + +class RemovedInDRF315Warning(PendingDeprecationWarning): + pass diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 72bfe614d..6374c1ea9 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -5,7 +5,6 @@ import functools import inspect import re import uuid -import warnings from collections import OrderedDict from collections.abc import Mapping @@ -30,7 +29,7 @@ from django.utils.ipv6 import clean_ipv6_address 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 @@ -712,23 +711,6 @@ class BooleanField(Field): 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): diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py index 8a44f2aad..7708fe0a2 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', diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py index 122846376..ee614fdf6 100644 --- a/rest_framework/schemas/openapi.py +++ b/rest_framework/schemas/openapi.py @@ -13,7 +13,7 @@ from django.db import models 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 @@ -713,106 +713,10 @@ class AutoSchema(ViewInspector): 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 052a766cd..083910174 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -52,7 +52,7 @@ from rest_framework.fields import ( # NOQA # isort:skip 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 diff --git a/tests/test_fields.py b/tests/test_fields.py index 56276e6ff..11e293107 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -679,9 +679,9 @@ class TestBooleanField(FieldValues): 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): From f8b3f38b57ff5a8e08b725a4dab81952c43ce972 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 21 Sep 2022 14:32:02 +0100 Subject: [PATCH 07/47] Update supported versions for 3.14 release (#8662) * Update supported versions for 3.14 release * Fix up test case for Django 3.0 --- README.md | 4 ++-- docs/community/3.14-announcement.md | 2 +- tests/authentication/test_authentication.py | 4 ++-- tox.ini | 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6cd4e86c7..e8375291d 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/community/3.14-announcement.md b/docs/community/3.14-announcement.md index 04d1572b1..8b7ee9f14 100644 --- a/docs/community/3.14-announcement.md +++ b/docs/community/3.14-announcement.md @@ -26,7 +26,7 @@ The latest release now fully supports Django 4.1. Our requirements are now: * Python 3.6+ -* Django 4.1, 4.0, 3.2, 3.1, 2.2 (LTS) +* Django 4.1, 4.0, 3.2, 3.1, 3.0 ## `raise_exceptions` argument for `is_valid` is now keyword-only. diff --git a/tests/authentication/test_authentication.py b/tests/authentication/test_authentication.py index d771aaf8b..b64c05de8 100644 --- a/tests/authentication/test_authentication.py +++ b/tests/authentication/test_authentication.py @@ -219,8 +219,8 @@ class SessionAuthTests(TestCase): 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/tox.ini b/tox.ini index c275a0abe..957d8a2e7 100644 --- a/tox.ini +++ b/tox.ini @@ -1,6 +1,6 @@ [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}, @@ -8,7 +8,7 @@ envlist = [travis:env] DJANGO = - 2.2: django22 + 3.0: django30 3.1: django31 3.2: django32 4.0: django40 @@ -22,7 +22,7 @@ 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 From c6cafc97251476399de2822896564c4b15559013 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 21 Sep 2022 14:33:41 +0100 Subject: [PATCH 08/47] Update release-notes.md --- docs/community/release-notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/community/release-notes.md b/docs/community/release-notes.md index dc8227035..485810265 100644 --- a/docs/community/release-notes.md +++ b/docs/community/release-notes.md @@ -38,7 +38,7 @@ You can determine your currently installed version using `pip show`: ### 3.14.0 -Date: 10th August 2022 +Date: 22nd September 2022 * Enforce `is_valid(raise_exception=False)` as a keyword-only argument. [[#7952](https://github.com/encode/django-rest-framework/pull/7952)] * Django 4.1 compatability. [[#8591](https://github.com/encode/django-rest-framework/pull/8591)] From f34f1562ffc880078ac8517dcd818f7cc56edff5 Mon Sep 17 00:00:00 2001 From: David Cain Date: Thu, 22 Sep 2022 02:32:26 -0700 Subject: [PATCH 09/47] Remove old deprecation classes for 3.14 release (#8664) When DRF 3.14 is released, these exception classes will be meaningless, so we can delete them (this has always been done). A previous PR removed the last incidence of `RemovedInDRF313Warning`, but didn't outright delete the class for fear of shipping a breaking change: https://github.com/encode/django-rest-framework/pull/8589 --- rest_framework/__init__.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py index 568e08074..d53b2cb4d 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -29,13 +29,5 @@ if django.VERSION < (3, 2): default_app_config = 'rest_framework.apps.RestFrameworkConfig' -class RemovedInDRF313Warning(DeprecationWarning): - pass - - -class RemovedInDRF314Warning(PendingDeprecationWarning): - pass - - class RemovedInDRF315Warning(PendingDeprecationWarning): pass From eb88dfc4b4df386c6ab42b58ec07c8d97efe554e Mon Sep 17 00:00:00 2001 From: Cihan Eran Date: Thu, 22 Sep 2022 12:36:01 +0300 Subject: [PATCH 10/47] Add --api-version CLI option to generateschema (#8663) * Add --version CLI option to generateschema * fix conflicting argument name --- rest_framework/management/commands/generateschema.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rest_framework/management/commands/generateschema.py b/rest_framework/management/commands/generateschema.py index 024306b65..8c73e4b9c 100644 --- a/rest_framework/management/commands/generateschema.py +++ b/rest_framework/management/commands/generateschema.py @@ -26,6 +26,7 @@ class Command(BaseCommand): 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 @@ class Command(BaseCommand): 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']) From 058424c16a9625739493843061d72302c8eda57d Mon Sep 17 00:00:00 2001 From: Aaron Taajik <75927372+aaronn44@users.noreply.github.com> Date: Thu, 22 Sep 2022 13:20:23 +0330 Subject: [PATCH 11/47] docs: delete duplicate explanation (#8641) --- docs/api-guide/fields.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 1e9436213..ab1847c0c 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -306,10 +306,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 From 11bfda92bae62382e4f709ba43526f34f090b9df Mon Sep 17 00:00:00 2001 From: Gulshan Ramnath Prajapati <35621580+gulshanAI@users.noreply.github.com> Date: Thu, 22 Sep 2022 15:20:56 +0530 Subject: [PATCH 12/47] both statement have dupplicate bodies (#8633) --- rest_framework/static/rest_framework/docs/js/api.js | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/rest_framework/static/rest_framework/docs/js/api.js b/rest_framework/static/rest_framework/docs/js/api.js index e6120cd8e..21663deb6 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) { From 58e0a698e3b02ee586b36a4c166ad3fddcf4b9ab Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 22 Sep 2022 12:31:43 +0100 Subject: [PATCH 13/47] Update setup.py to drop Django 2.2 and update release notes (#8666) --- docs/community/3.14-announcement.md | 2 +- docs/community/release-notes.md | 4 +++- setup.py | 3 +-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/community/3.14-announcement.md b/docs/community/3.14-announcement.md index 8b7ee9f14..0543d0d6d 100644 --- a/docs/community/3.14-announcement.md +++ b/docs/community/3.14-announcement.md @@ -21,7 +21,7 @@ ## Django 4.1 support -The latest release now fully supports Django 4.1. +The latest release now fully supports Django 4.1, and drops support for Django 2.2. Our requirements are now: diff --git a/docs/community/release-notes.md b/docs/community/release-notes.md index 485810265..887cae3b4 100644 --- a/docs/community/release-notes.md +++ b/docs/community/release-notes.md @@ -40,8 +40,10 @@ You can determine your currently installed version using `pip show`: 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)] -* Django 4.1 compatability. [[#8591](https://github.com/encode/django-rest-framework/pull/8591)] * 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)] diff --git a/setup.py b/setup.py index cb6708c6e..181740165 100755 --- a/setup.py +++ b/setup.py @@ -82,14 +82,13 @@ setup( 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', From 2da473c8c8e024e80c13a624782f1da6272812da Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 22 Sep 2022 12:37:51 +0100 Subject: [PATCH 14/47] Add 3.14 announcement to the docs --- mkdocs.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/mkdocs.yml b/mkdocs.yml index 439245a8d..c58e08318 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' From 2de50818296b1b4bae68787626c0236752e35101 Mon Sep 17 00:00:00 2001 From: David Cain Date: Thu, 22 Sep 2022 11:07:43 -0700 Subject: [PATCH 15/47] Use correct class to indicate present deprecation (#8665) `PendingDeprecationWarning` means "we plan to deprecate, but haven't yet." A feature that's to be deleted in the next release is not planned to be deprecated; it **is** deprecated. > Base class for warnings about features which are obsolete and expected > to be deprecated in the future, but are not deprecated at the moment. > > This class is rarely used as emitting a warning about a possible > upcoming deprecation is unusual, and DeprecationWarning is preferred for > already active deprecations. https://docs.python.org/3/library/exceptions.html#PendingDeprecationWarning Co-authored-by: Tom Christie --- rest_framework/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py index d53b2cb4d..cc24ce46c 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -29,5 +29,5 @@ if django.VERSION < (3, 2): default_app_config = 'rest_framework.apps.RestFrameworkConfig' -class RemovedInDRF315Warning(PendingDeprecationWarning): +class RemovedInDRF315Warning(DeprecationWarning): pass From 73f4835a531d7a192946ab8da9e06ef184cb1119 Mon Sep 17 00:00:00 2001 From: Ahzam Ahmed <62069509+AhzamAhmed6@users.noreply.github.com> Date: Mon, 26 Sep 2022 17:05:53 +0500 Subject: [PATCH 16/47] Unnecessary list comprehension (#8670) --- rest_framework/schemas/inspectors.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/schemas/inspectors.py b/rest_framework/schemas/inspectors.py index 027472db1..722fc9b2b 100644 --- a/rest_framework/schemas/inspectors.py +++ b/rest_framework/schemas/inspectors.py @@ -88,7 +88,7 @@ class ViewInspector: view.get_view_description()) def _get_description_section(self, view, header, description): - lines = [line for line in description.splitlines()] + lines = list(description.splitlines()) current_section = '' sections = {'': ''} From 3e51ba4d519e95691f57d3eda714acd49f24dc67 Mon Sep 17 00:00:00 2001 From: Allie Date: Tue, 27 Sep 2022 05:54:52 -0700 Subject: [PATCH 17/47] Update documentation on dependency installation (#8566) We depend on pytz, but until late last year we got it implicitly through depending on Django. Since their release 4.0, however, they no longer depend on pytz; commit 250479dc3 added the dependency directly to our metadata in setup.py, but the documentation about dependencies (most importantly, the instructions for new contributors) was left untouched. This commit updates the new contributor instructions to suggest an "editable installation" of the project at the step that previously had users manually install Django. In this mode, pip fetches and installs the project dependencies automatically (so in the unlikely event we grow another dependency, that doc doesn't need to be changed again) and makes the project available to the virtualenv's python as a normal package, but doesn't require reinstallation for mundane edits. --- docs/community/contributing.md | 2 +- requirements.txt | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/community/contributing.md b/docs/community/contributing.md index 2232bd10b..994226b97 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/requirements.txt b/requirements.txt index 395f3b7a8..c3a1f1187 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 From 9e398c59ab0e91346267c3fcac75ebd97d5b3346 Mon Sep 17 00:00:00 2001 From: Ahzam Ahmed <62069509+AhzamAhmed6@users.noreply.github.com> Date: Tue, 27 Sep 2022 20:08:40 +0500 Subject: [PATCH 18/47] Minor refactor: Unnecessary use of list() function (#8672) --- rest_framework/schemas/inspectors.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/schemas/inspectors.py b/rest_framework/schemas/inspectors.py index 722fc9b2b..cb880e79d 100644 --- a/rest_framework/schemas/inspectors.py +++ b/rest_framework/schemas/inspectors.py @@ -88,7 +88,7 @@ class ViewInspector: view.get_view_description()) def _get_description_section(self, view, header, description): - lines = list(description.splitlines()) + lines = description.splitlines() current_section = '' sections = {'': ''} From 79de112d627d9a84e302d54849e95dd7ab677a43 Mon Sep 17 00:00:00 2001 From: manelbdacosta <30473446+manelbdcosta@users.noreply.github.com> Date: Mon, 3 Oct 2022 10:36:51 +0100 Subject: [PATCH 19/47] Minor fix to SerializeMethodField docstring (#8629) --- rest_framework/fields.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 6374c1ea9..a6924bf23 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1814,7 +1814,7 @@ class SerializerMethodField(Field): For example: - class ExampleSerializer(self): + class ExampleSerializer(Serializer): extra_info = SerializerMethodField() def get_extra_info(self, obj): From ca75300ae9048c8c90d1e57935d22ec99ffbbac7 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Oct 2022 11:39:32 +0100 Subject: [PATCH 20/47] Update requirements-testing.txt (#8680) * Update requirements-testing.txt * Update requirements-testing.txt --- requirements/requirements-testing.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements/requirements-testing.txt b/requirements/requirements-testing.txt index 313fdedc9..f6823e2e2 100644 --- a/requirements/requirements-testing.txt +++ b/requirements/requirements-testing.txt @@ -2,3 +2,4 @@ pytest>=6.1,<7.0 pytest-cov>=2.10.1,<3.0 pytest-django>=4.1.0,<5.0 +importlib-metadata<5.0 From e7777cb1ee98c0215a5f1f082a88290eefa3e293 Mon Sep 17 00:00:00 2001 From: Sardorbek Imomaliev Date: Mon, 3 Oct 2022 15:48:18 +0500 Subject: [PATCH 21/47] Add spaces to router example in 6-viewsets-and-routers.md (#8448) --- docs/tutorial/6-viewsets-and-routers.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index e12becbd0..b7a7696a7 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 = [ From 99cf2c415f5a556e924b04421ad7f92f4c62aa09 Mon Sep 17 00:00:00 2001 From: mschmidm <66086922+mschmidm@users.noreply.github.com> Date: Tue, 4 Oct 2022 13:15:51 +0200 Subject: [PATCH 22/47] Docs: Updated browsable-api.md (#8678) - Replace the broken Bootswatch-Link with an Jsdelivr-Link as suggested at https://bootswatch.com/help/ - Updated the stated Bootstrap version - Added a note that the Bootstrap version must match the default one Co-authored-by: Tom Christie --- docs/topics/browsable-api.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md index ed70c4901..2cdf2a884 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 {% 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 %} - + {% endblock %} {% block bootstrap_navbar_variant %}{% endblock %} From c10f2266222c434485889b08cc1463acdb8fa169 Mon Sep 17 00:00:00 2001 From: Ahzam Ahmed Date: Wed, 5 Oct 2022 15:02:00 +0500 Subject: [PATCH 23/47] Refactor: Replace try/except with contextlib.suppress() (#8676) --- rest_framework/fields.py | 20 +++++++------------- rest_framework/pagination.py | 17 +++++------------ rest_framework/parsers.py | 13 +++++-------- rest_framework/relations.py | 6 ++---- rest_framework/renderers.py | 12 ++++-------- rest_framework/serializers.py | 6 +++--- rest_framework/utils/encoders.py | 6 +++--- rest_framework/utils/serializer_helpers.py | 5 ++--- 8 files changed, 31 insertions(+), 54 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index a6924bf23..7f4c83b5d 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,3 +1,4 @@ +import contextlib import copy import datetime import decimal @@ -690,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): @@ -1158,19 +1157,14 @@ class DateTimeField(Field): 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) diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index e815d8d5c..186e61d9b 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 @@ -257,15 +259,12 @@ class PageNumberPagination(BasePagination): 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): @@ -430,15 +429,12 @@ class LimitOffsetPagination(BasePagination): 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): @@ -680,15 +676,12 @@ class CursorPagination(BasePagination): 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): diff --git a/rest_framework/parsers.py b/rest_framework/parsers.py index 4ee8e578b..f0fd2b884 100644 --- a/rest_framework/parsers.py +++ b/rest_framework/parsers.py @@ -4,7 +4,9 @@ Parsers are used to parse the content of incoming HTTP requests. They give us a generic way of being able to handle various media types 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 @@ class FileUploadParser(BaseParser): 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/relations.py b/rest_framework/relations.py index bdedd43b8..62da685fb 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 @@ class RelatedField(Field): 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 @@ class RelatedField(Field): 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 b74df9a0b..3f47580f1 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -6,7 +6,9 @@ on the response, such as JSON encoded data or HTML output. REST framework also provides an HTML renderer that renders the browsable API. """ + import base64 +import contextlib from collections import OrderedDict from urllib import parse @@ -72,11 +74,8 @@ class JSONRenderer(BaseRenderer): # 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 @@ class BrowsableAPIRenderer(BaseRenderer): 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/serializers.py b/rest_framework/serializers.py index 083910174..7037c07cd 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -10,6 +10,8 @@ python primitives. 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 @@ -1496,12 +1498,10 @@ class ModelSerializer(Serializer): # 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/utils/encoders.py b/rest_framework/utils/encoders.py index 27293b725..35a89eb09 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 @@ class JSONEncoder(json.JSONEncoder): ) 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 54068f5fb..6ca794584 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 @@ class JSONBoundField(BoundField): # 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) From d507cd851c4b1185e3dc720de9ba6a642459d738 Mon Sep 17 00:00:00 2001 From: Markus Legner Date: Fri, 7 Oct 2022 12:58:38 +0200 Subject: [PATCH 24/47] Fix infinite recursion with deepcopy on Request (#8684) --- rest_framework/request.py | 3 ++- tests/test_request.py | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/rest_framework/request.py b/rest_framework/request.py index 93634e667..194be5f6d 100644 --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -413,7 +413,8 @@ class Request: 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/tests/test_request.py b/tests/test_request.py index 8f55d00ed..8c18aea9e 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 @@ class TestHttpRequest(TestCase): # 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) From 911b207fa13f7e1cd65f62a7b6b16fb4a9854098 Mon Sep 17 00:00:00 2001 From: Norbert Schuler Date: Tue, 11 Oct 2022 12:50:33 +0200 Subject: [PATCH 25/47] Added examples to schema of CursorPagination (#8687) * Added examples to schema of CursorPagination Fix https://github.com/encode/django-rest-framework/issues/8686 Added missing examples for CursorPagination class to disable warnings in https://github.com/tfranzel/drf-spectacular and make it consistent with other pagination classes. * Adapted test case for paginated response schema --- rest_framework/pagination.py | 6 ++++++ tests/test_pagination.py | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index 186e61d9b..8c434ea4f 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -898,10 +898,16 @@ class CursorPagination(BasePagination): '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/tests/test_pagination.py b/tests/test_pagination.py index c028f0ea8..5d7864700 100644 --- a/tests/test_pagination.py +++ b/tests/test_pagination.py @@ -922,10 +922,14 @@ class CursorPaginationTestsMixin: '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, }, From 56946fac8f29aa44ce84391f138d63c4c8a2a285 Mon Sep 17 00:00:00 2001 From: Klaas van Schelven Date: Tue, 11 Oct 2022 14:48:57 +0200 Subject: [PATCH 26/47] Preserve exception messages for wrapped Django exceptions (#8051) * Preserve messages for wrapped Django exceptions * Fix the test * Update test_generics.py * Update test_generics.py Co-authored-by: Tom Christie --- rest_framework/views.py | 4 ++-- tests/test_generics.py | 8 +++++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/rest_framework/views.py b/rest_framework/views.py index 5b0622069..4c30029fd 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/tests/test_generics.py b/tests/test_generics.py index 2907d2773..78dc5afb6 100644 --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -5,6 +5,7 @@ from django.shortcuts import get_object_or_404 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 @@ class TestFilterBackendAppliedToViews(TestCase): 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): """ From 20d347a806baa0dd481b31a7f847386574882d5b Mon Sep 17 00:00:00 2001 From: Shyamkumar Yadav <46707211+shyamkumaryadav@users.noreply.github.com> Date: Wed, 12 Oct 2022 15:53:45 +0530 Subject: [PATCH 27/47] Docs: Convert all tabs into spaces (#8692) --- docs/api-guide/authentication.md | 2 +- docs/api-guide/content-negotiation.md | 2 +- docs/api-guide/reverse.md | 16 ++++++++-------- docs/api-guide/serializers.md | 10 +++++----- docs/api-guide/throttling.md | 4 ++-- docs/community/3.12-announcement.md | 10 +++++----- 6 files changed, 22 insertions(+), 22 deletions(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index d30b6fed8..5fa87c031 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -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 diff --git a/docs/api-guide/content-negotiation.md b/docs/api-guide/content-negotiation.md index 3a4b0357f..81cff6a89 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/reverse.md b/docs/api-guide/reverse.md index 70df42b8f..ba37a0f66 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 + 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) + 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/serializers.md b/docs/api-guide/serializers.md index 91a9d63f3..ca120768e 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -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 @@ -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/throttling.md b/docs/api-guide/throttling.md index b87522197..4c58fa713 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/community/3.12-announcement.md b/docs/community/3.12-announcement.md index 9d2220933..4a589e39c 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... From 1fd268ae2b03e3328ba7923a47c6a912b2bc0166 Mon Sep 17 00:00:00 2001 From: Shyamkumar Yadav <46707211+shyamkumaryadav@users.noreply.github.com> Date: Fri, 14 Oct 2022 15:52:19 +0530 Subject: [PATCH 28/47] Docs: use `asterisk` for unordered list (#8697) --- docs/api-guide/fields.md | 110 ++++++++++++++++++------------------ docs/api-guide/relations.md | 8 +-- 2 files changed, 59 insertions(+), 59 deletions(-) diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index ab1847c0c..e5b200bf6 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -78,7 +78,7 @@ 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: @@ -171,10 +171,10 @@ Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.T **Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)` -- `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. @@ -222,11 +222,11 @@ A field that ensures the input is a valid UUID string. The `to_internal_value` m **Signature:** `UUIDField(format='hex_verbose')` -- `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 @@ -237,11 +237,11 @@ Corresponds to `django.forms.fields.FilePathField`. **Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)` -- `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 @@ -251,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'. --- @@ -266,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 @@ -277,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 @@ -288,13 +288,13 @@ Corresponds to `django.db.models.fields.DecimalField`. **Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)` -- `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`. #### Example usage @@ -380,8 +380,8 @@ The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu **Signature:** `DurationField(max_value=None, min_value=None)` -- `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. --- @@ -395,10 +395,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. @@ -408,10 +408,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. @@ -432,9 +432,9 @@ Corresponds to `django.forms.fields.FileField`. **Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)` - - `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 @@ -444,9 +444,9 @@ Corresponds to `django.forms.fields.ImageField`. **Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)` - - `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. @@ -460,10 +460,10 @@ A field class that validates a list of objects. **Signature**: `ListField(child=, 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: @@ -484,8 +484,8 @@ A field class that validates a dictionary of objects. The keys in `DictField` ar **Signature**: `DictField(child=, 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: @@ -502,8 +502,8 @@ A preconfigured `DictField` that is compatible with Django's postgres `HStoreFie **Signature**: `HStoreField(child=, 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. @@ -513,8 +513,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`. --- @@ -565,7 +565,7 @@ This is a read-only field. It gets its value by calling a method on the serializ **Signature**: `SerializerMethodField(method_name=None)` -- `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_`. +* `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_`. 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: diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 9c8295b85..a828a88ac 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) @@ -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`. From 9407833a8316c9b45af07c77ec51de6ccbe93195 Mon Sep 17 00:00:00 2001 From: Ran Benita Date: Fri, 14 Oct 2022 18:30:26 +0300 Subject: [PATCH 29/47] Avoid importing `django.test` package when not testing (#8699) Importing anything `rest_framework` causes `django.test` to be imported. This is because DRF registers a receiver on the `django.test_signals.setting_changed` signal. This is not really a problem, but it is good to avoid this because it bloats the memory with unnecessary modules (e.g. `django.test`, `django.core.servers.basehttp`, `socketserver`) and increases the startup time. It also doesn't feel right to import test code into non-test code. Try to import the signal from a core module if possible. Note that there's another `django.test` import in `MultiPartRenderer`, however this import is done lazily only if the functionality is used so can be easily avoided. --- rest_framework/settings.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/rest_framework/settings.py b/rest_framework/settings.py index 9eb4c5653..96b664574 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -19,7 +19,9 @@ REST framework settings, checking for user settings first, then falling 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 From b221aa2cf6e13907e63311cb0c6df36dede720ea Mon Sep 17 00:00:00 2001 From: mka142 <69858959+mka142@users.noreply.github.com> Date: Mon, 17 Oct 2022 10:54:48 +0200 Subject: [PATCH 30/47] Update schemas.md (#8707) --- docs/api-guide/schemas.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/api-guide/schemas.md b/docs/api-guide/schemas.md index 004e2d3ce..ff27fdffe 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`. From 0cb693700f39f096e6337ccceab4f4b82b293557 Mon Sep 17 00:00:00 2001 From: Jan Lis <114775140+janlis-ff@users.noreply.github.com> Date: Mon, 17 Oct 2022 11:20:59 +0200 Subject: [PATCH 31/47] add `__eq__` method for `OperandHolder` class (#8710) --- rest_framework/permissions.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/rest_framework/permissions.py b/rest_framework/permissions.py index 16459b251..f3ebbcffa 100644 --- a/rest_framework/permissions.py +++ b/rest_framework/permissions.py @@ -46,6 +46,14 @@ class OperandHolder(OperationHolderMixin): 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): From 35c5be6ec23af6e68914812599c905fe0fa2c0cc Mon Sep 17 00:00:00 2001 From: Den Date: Mon, 17 Oct 2022 13:47:45 +0400 Subject: [PATCH 32/47] Add a method for getting serializer field name (OpenAPI) (#7493) * Add a method for getting serializer field name * Add docs and test Co-authored-by: Tom Christie --- rest_framework/schemas/openapi.py | 11 +++++++++-- tests/schemas/test_openapi.py | 14 ++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py index ee614fdf6..2f9fb9f28 100644 --- a/rest_framework/schemas/openapi.py +++ b/rest_framework/schemas/openapi.py @@ -523,7 +523,7 @@ class AutoSchema(ViewInspector): 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 @@ class AutoSchema(ViewInspector): 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 @@ class AutoSchema(ViewInspector): 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: diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py index daa035a3f..7542bb615 100644 --- a/tests/schemas/test_openapi.py +++ b/tests/schemas/test_openapi.py @@ -111,6 +111,20 @@ class TestFieldMapping(TestCase): 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) From e354331743dd6e8999371b0055d61967c78da859 Mon Sep 17 00:00:00 2001 From: Elton Maiyo Date: Wed, 19 Oct 2022 13:11:09 +0300 Subject: [PATCH 33/47] Fixes typo (#8719) --- docs/topics/rest-hypermedia-hateoas.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/topics/rest-hypermedia-hateoas.md b/docs/topics/rest-hypermedia-hateoas.md index a11bd6cc7..3498bddd1 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. From 041b88f8bbb48d9688ebd5add294eee2dfc93d1c Mon Sep 17 00:00:00 2001 From: Francisco Couzo Date: Wed, 19 Oct 2022 07:20:11 -0300 Subject: [PATCH 34/47] Improve style, fix some typos (#8405) * Improve style, fix some typos * Update docs/api-guide/fields.md Co-authored-by: Tom Christie Co-authored-by: Tom Christie --- docs/api-guide/authentication.md | 14 ++++++------- docs/api-guide/fields.md | 10 +++++----- docs/api-guide/format-suffixes.md | 4 ++-- docs/api-guide/generic-views.md | 2 +- docs/api-guide/pagination.md | 2 +- docs/api-guide/parsers.md | 2 +- docs/api-guide/permissions.md | 2 +- docs/api-guide/relations.md | 2 +- docs/api-guide/renderers.md | 6 +++--- docs/api-guide/requests.md | 2 +- docs/api-guide/reverse.md | 2 +- docs/api-guide/schemas.md | 4 ++-- docs/api-guide/serializers.md | 24 +++++++++++------------ docs/api-guide/validators.md | 4 ++-- docs/api-guide/views.md | 2 +- docs/api-guide/viewsets.md | 4 ++-- docs/community/3.0-announcement.md | 4 ++-- docs/community/3.2-announcement.md | 2 +- docs/community/3.3-announcement.md | 2 +- docs/community/3.4-announcement.md | 2 +- docs/community/3.8-announcement.md | 2 +- docs/community/funding.md | 6 +++--- docs/community/third-party-packages.md | 2 +- docs/coreapi/from-documenting-your-api.md | 2 +- docs/coreapi/schemas.md | 12 ++++++------ docs/index.md | 2 +- docs/topics/ajax-csrf-cors.md | 2 +- docs/topics/api-clients.md | 2 +- docs/topics/html-and-forms.md | 20 +++++++++---------- docs/tutorial/1-serialization.md | 4 ++-- docs/tutorial/2-requests-and-responses.md | 2 +- docs/tutorial/3-class-based-views.md | 4 ++-- 32 files changed, 78 insertions(+), 78 deletions(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 5fa87c031..2eb3a2921 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -201,7 +201,7 @@ If you've already created some users, you can generate tokens for all existing u #### 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. @@ -250,7 +250,7 @@ And in your `urls.py`: #### 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/) @@ -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/fields.md b/docs/api-guide/fields.md index e5b200bf6..0a96d0e0c 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. @@ -85,7 +85,7 @@ When serializing fields with dotted notation, it may be necessary to provide a ` 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. @@ -771,7 +771,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: @@ -831,7 +831,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 da4a1af78..9b4e5b9da 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 9467eb6b4..410e3518d 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 aadc1bbc7..3081e2bc3 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 dde77c3e0..4993c447f 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. --- diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 8d6f47c79..6e164d220 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. diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index a828a88ac..56eb61e43 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -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') diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 685a98f5e..44f1b6021 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 e877c868d..d072ac436 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 ba37a0f66..82dd16881 100644 --- a/docs/api-guide/reverse.md +++ b/docs/api-guide/reverse.md @@ -38,7 +38,7 @@ You should **include the request as a keyword argument** to the function, for ex def get(self, request): year = now().year data = { - ... + ... 'year-summary-url': reverse('year-summary', args=[year], request=request) } return Response(data) diff --git a/docs/api-guide/schemas.md b/docs/api-guide/schemas.md index ff27fdffe..e402019a4 100644 --- a/docs/api-guide/schemas.md +++ b/docs/api-guide/schemas.md @@ -293,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 @@ -301,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 ca120768e..0d14cac46 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. @@ -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. diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index 76dcb0d54..bb8466a2c 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 878a291b2..b293de75a 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 417972507..5d5491a83 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 b9461defe..0cb79fc2e 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.2-announcement.md b/docs/community/3.2-announcement.md index a66ad5d29..eda4071b2 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 5dcbe3b3b..24f493dcd 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 67192ecbb..6d5f0399c 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 507299782..f33b220fd 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/funding.md b/docs/community/funding.md index 2158cd38f..951833682 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/third-party-packages.md b/docs/community/third-party-packages.md index 9513b13d1..1a40539da 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 65ad71c7a..f8ddff019 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 9f1482d2d..73fc7b67d 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 2f44fae9a..0c428c8ec 100644 --- a/docs/index.md +++ b/docs/index.md @@ -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 a65e3fdf8..094ecc4a4 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 b9f5e3ecd..3732d3f93 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/html-and-forms.md b/docs/topics/html-and-forms.md index 18774926b..17c9e3314 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/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 67746c517..6db3ea282 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 1d272f304..47c7facfc 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 e02feaa5e..ccfcd095d 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. From 2510456817d9d2840a4080e69a0efb8a4da423ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A9ry=20Ogam?= Date: Thu, 20 Oct 2022 16:32:25 +0200 Subject: [PATCH 35/47] Update quickstart.md (#8575) * Update quickstart.md * Use PEP 8 compliant import * Remove unauthorized password by Django (too common) --- docs/tutorial/quickstart.md | 74 +++++++++++++++++++------------------ 1 file changed, 39 insertions(+), 35 deletions(-) diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 4fa2fbbe5..754b46f9a 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -30,22 +30,24 @@ The project layout should look like: /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,9 +168,30 @@ We're now ready to test the API we've built. Let's fire up the server from the We can now access our API, both from the command-line, using tools like `curl`... - bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/ + bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/ + Enter host password for user 'admin': { - "count": 2, + "count": 1, + "next": null, + "previous": null, + "results": [ + { + "url": "http://127.0.0.1:8000/users/1/", + "username": "admin", + "email": "admin@example.com", + "groups": [] + } + ] + } + +Or using the [httpie][httpie], command line tool... + + bash: http -a admin http://127.0.0.1:8000/users/ + http: password for admin@127.0.0.1:8000:: + $HTTP/1.1 200 OK + ... + { + "count": 1, "next": null, "previous": null, "results": [ @@ -176,27 +200,7 @@ We can now access our API, both from the command-line, using tools like `curl`.. "groups": [], "url": "http://127.0.0.1:8000/users/1/", "username": "admin" - }, - ] - } - -Or using the [httpie][httpie], command line tool... - - bash: http -a admin:password123 http://127.0.0.1:8000/users/ - - HTTP/1.1 200 OK - ... - { - "count": 2, - "next": null, - "previous": null, - "results": [ - { - "email": "admin@example.com", - "groups": [], - "url": "http://localhost:8000/users/1/", - "username": "paul" - }, + } ] } From 1142ee5fc11991b39ecbc815d85d60e932b24895 Mon Sep 17 00:00:00 2001 From: Thomas <17140634+tompec@users.noreply.github.com> Date: Wed, 2 Nov 2022 19:10:45 +0800 Subject: [PATCH 36/47] Update jobs.md (#8737) Update remoteok.io to remoteok.com Add pyjobs.com --- docs/community/jobs.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/community/jobs.md b/docs/community/jobs.md index ce85b7570..aa1c5d4b4 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 From ae7a2b0dfadc8f2ac5b648ad4391101bab7baf51 Mon Sep 17 00:00:00 2001 From: "Lewis M. Kabui" <13940255+lewisemm@users.noreply.github.com> Date: Thu, 10 Nov 2022 13:31:06 +0300 Subject: [PATCH 37/47] Remove extraneous word "Both" (#8740) * Remove extraneous word "Both" * Update Multiparser docs Co-authored-by: Lewis Kabui --- docs/api-guide/parsers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 4993c447f..0a85d474f 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -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. From 78cdae69997c9fd95211ec15fb4e21f4cd45e30a Mon Sep 17 00:00:00 2001 From: Stanislav Levin Date: Tue, 15 Nov 2022 15:29:15 +0300 Subject: [PATCH 38/47] Fix Pytest's deprecation warnings about nose usage (#8758) Pytest 7.2.0 deprecated plain `setup` and `teardown` functions and methods as nose idioms: https://docs.pytest.org/en/latest/changelog.html#pytest-7-2-0-2022-10-23 `setup` can be safely replaced with `setup_method`: https://docs.pytest.org/en/stable/deprecations.html#setup-teardown Fixes: https://github.com/encode/django-rest-framework/issues/8757 Signed-off-by: Stanislav Levin Signed-off-by: Stanislav Levin --- tests/test_fields.py | 14 +++++++------- tests/test_pagination.py | 12 ++++++------ tests/test_relations.py | 2 +- tests/test_serializer.py | 14 +++++++------- tests/test_serializer_lists.py | 12 ++++++------ tests/test_serializer_nested.py | 10 +++++----- 6 files changed, 32 insertions(+), 32 deletions(-) diff --git a/tests/test_fields.py b/tests/test_fields.py index 11e293107..72ef23dca 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -239,7 +239,7 @@ class TestSource: 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 @@ class TestReadOnly: 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 @@ class TestWriteOnly: 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 @@ class TestInitial: class TestInitialWithCallable: - def setup(self): + def setup_method(self): def initial_value(): return 123 @@ -331,7 +331,7 @@ class TestInitialWithCallable: 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 @@ class TestLabel: 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 TestHTMLInput: class TestCreateOnlyDefault: - def setup(self): + def setup_method(self): default = serializers.CreateOnlyDefault('2001-01-01') class TestSerializer(serializers.Serializer): diff --git a/tests/test_pagination.py b/tests/test_pagination.py index 5d7864700..74a65bf50 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 @@ -941,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_relations.py b/tests/test_relations.py index bb719a65a..7a4db1c48 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -374,7 +374,7 @@ class TestManyRelatedField(APISimpleTestCase): 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_serializer.py b/tests/test_serializer.py index c4c29ba4a..1d9efaa43 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -61,7 +61,7 @@ class TestFieldImports: # ----------------------------- class TestSerializer: - def setup(self): + def setup_method(self): class ExampleSerializer(serializers.Serializer): char = serializers.CharField() integer = serializers.IntegerField() @@ -240,7 +240,7 @@ class TestValidateMethod: 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 @@ class TestNotRequiredOutput: 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 TestCacheSerializerData: 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 @@ class TestDefaultInclusions: 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 Test2555Regression: 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 551f62666..4b60643a8 100644 --- a/tests/test_serializer_lists.py +++ b/tests/test_serializer_lists.py @@ -32,7 +32,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 @@ -70,7 +70,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() @@ -156,7 +156,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()) @@ -278,7 +278,7 @@ class TestNestedListSerializerAllowEmpty: class TestNestedListOfListsSerializer: - def setup(self): + def setup_method(self): class TestSerializer(serializers.Serializer): integers = serializers.ListSerializer( child=serializers.ListSerializer( @@ -594,7 +594,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() @@ -623,7 +623,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 09ac37f24..986972a65 100644 --- a/tests/test_serializer_nested.py +++ b/tests/test_serializer_nested.py @@ -9,7 +9,7 @@ from rest_framework.serializers import raise_errors_on_nested_writes 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 @@ class TestNestedSerializer: class TestNotRequiredNestedSerializer: - def setup(self): + def setup_method(self): class NestedSerializer(serializers.Serializer): one = serializers.IntegerField(max_value=10) @@ -83,7 +83,7 @@ class TestNotRequiredNestedSerializer: class TestNestedSerializerWithMany: - def setup(self): + def setup_method(self): class NestedSerializer(serializers.Serializer): example = serializers.IntegerField(max_value=10) @@ -181,7 +181,7 @@ class TestNestedSerializerWithMany: class TestNestedSerializerWithList: - def setup(self): + def setup_method(self): class NestedSerializer(serializers.Serializer): example = serializers.MultipleChoiceField(choices=[1, 2, 3]) @@ -210,7 +210,7 @@ class TestNestedSerializerWithList: class TestNotRequiredNestedSerializerWithMany: - def setup(self): + def setup_method(self): class NestedSerializer(serializers.Serializer): one = serializers.IntegerField(max_value=10) From d5f228dd0012fe514e552224c1501782237eecb0 Mon Sep 17 00:00:00 2001 From: Henrik Wahlgren Date: Wed, 16 Nov 2022 15:31:50 +0100 Subject: [PATCH 39/47] Possibility to remove trailing zeros on DecimalFields representation (#6514) * Added normalize parameter to DecimalField to be able to strip trailing zeros. Fixes #6151. * Updated docs to include normalize option on DecimalField * Fixed linting error in test_fields * Removed comment and renamed normalize to normalize_output as suggested in code review Co-authored-by: Tom Christie --- docs/api-guide/fields.md | 1 + rest_framework/fields.py | 6 +++++- tests/test_fields.py | 21 +++++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 0a96d0e0c..4b4ea83cc 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -295,6 +295,7 @@ Corresponds to `django.db.models.fields.DecimalField`. * `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 diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 7f4c83b5d..88d606b28 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -963,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: @@ -1079,6 +1080,9 @@ class DecimalField(Field): quantized = self.quantize(value) + if self.normalize_output: + quantized = quantized.normalize() + if not coerce_to_string: return quantized if self.localize: diff --git a/tests/test_fields.py b/tests/test_fields.py index 72ef23dca..3112fc2cc 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1251,6 +1251,27 @@ class TestQuantizedValueForDecimal(TestCase): 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'), From 759fc6f42e834b204501b17049daa473bdd2ce2c Mon Sep 17 00:00:00 2001 From: Clemens Wolff Date: Thu, 17 Nov 2022 13:47:47 +0100 Subject: [PATCH 40/47] Make request consistently available in pagination classes (#8764) * Store request in CursorPagination field * Define request at start of pagination entrypoint --- rest_framework/pagination.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index 8c434ea4f..50e5aaacb 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -195,6 +195,7 @@ class PageNumberPagination(BasePagination): 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 @@ -214,7 +215,6 @@ class PageNumberPagination(BasePagination): # 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): @@ -379,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 @@ -599,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 From 3e052376ace520135d42dcf52f35a51b7dcc5ac2 Mon Sep 17 00:00:00 2001 From: Ilaletdinov Almaz <45946541+blablatdinov@users.noreply.github.com> Date: Thu, 17 Nov 2022 16:13:09 +0300 Subject: [PATCH 41/47] Added http 102, 103, 421, and 425 status codes in documentation (#8763) --- docs/api-guide/status-codes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md index a37ba15d4..fb2f9bf13 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 From df60510db51eaee06f4b4483e31b1d2f7aa5ed7e Mon Sep 17 00:00:00 2001 From: Manos Date: Thu, 17 Nov 2022 14:13:18 +0000 Subject: [PATCH 42/47] Add 3rd party entry for rest-framework-roles (#8755) --- docs/api-guide/permissions.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 6e164d220..d945e95c3 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -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 From 21fdf066b4dce6ebef4539cded53fa3ab84ce78f Mon Sep 17 00:00:00 2001 From: Asif Saif Uddin Date: Fri, 18 Nov 2022 17:09:05 +0600 Subject: [PATCH 43/47] pytest versions update (#8745) * pytest versions update * pytest>=7.0.0,<8.0 * pytest>=7.2.0,<8.0 * pytest>=6.2.0,<8.0 --- requirements/requirements-testing.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements/requirements-testing.txt b/requirements/requirements-testing.txt index f6823e2e2..fb6dbf05f 100644 --- a/requirements/requirements-testing.txt +++ b/requirements/requirements-testing.txt @@ -1,5 +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 From cac89ae65defa1a89cb931106775314f0671bb46 Mon Sep 17 00:00:00 2001 From: Asif Saif Uddin Date: Fri, 18 Nov 2022 21:32:10 +0600 Subject: [PATCH 44/47] update minimum version to psycopg2-binary>=2.9.5 (#8767) --- requirements/requirements-optionals.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/requirements-optionals.txt b/requirements/requirements-optionals.txt index f3bb9b709..3de07d1c7 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 From 2a2b092864a2b33b41336b83f8b2ebf6c5ef6076 Mon Sep 17 00:00:00 2001 From: Paolo Melchiorre Date: Mon, 21 Nov 2022 11:47:21 +0100 Subject: [PATCH 45/47] Fix #8751 - Add support to Python 3.11 (#8752) --- .github/workflows/main.yml | 1 + docs/index.md | 2 +- setup.py | 1 + tox.ini | 6 +++++- 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c88dc55cd..b635573f2 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/docs/index.md b/docs/index.md index 0c428c8ec..cab5511ac 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 diff --git a/setup.py b/setup.py index 181740165..d00470268 100755 --- a/setup.py +++ b/setup.py @@ -104,6 +104,7 @@ setup( '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/tox.ini b/tox.ini index 957d8a2e7..2b421f6c2 100644 --- a/tox.ini +++ b/tox.ini @@ -4,6 +4,7 @@ envlist = {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] @@ -26,7 +27,7 @@ deps = 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 From 751808c59b973b329d8da89c7ae78048e499cc40 Mon Sep 17 00:00:00 2001 From: Asif Saif Uddin Date: Mon, 21 Nov 2022 17:32:07 +0600 Subject: [PATCH 46/47] converted assertion to pytest style in test status (#8769) --- tests/test_status.py | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/tests/test_status.py b/tests/test_status.py index b10f7df99..4d7aeb90a 100644 --- a/tests/test_status.py +++ b/tests/test_status.py @@ -7,27 +7,27 @@ from rest_framework.status import ( 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) From dc300aa4e01c4cc53c5d74057dc307e31d8ef56d Mon Sep 17 00:00:00 2001 From: smt-insens <102955499+smt-insens@users.noreply.github.com> Date: Mon, 21 Nov 2022 15:33:19 +0100 Subject: [PATCH 47/47] [FIX] add missing DurationField to SimpleMetada label_lookup (#8702) --- rest_framework/metadata.py | 1 + 1 file changed, 1 insertion(+) diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py index 7708fe0a2..015587897 100644 --- a/rest_framework/metadata.py +++ b/rest_framework/metadata.py @@ -48,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',