From 5cc16335eea8ef7b4969b790dc384fe7ec4b5066 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 9 Oct 2025 06:10:06 +0200 Subject: [PATCH 01/19] GitHub Actions: Test on Python 3.14 release candidate 2 (#9780) Python v3.14 -- October 7th * https://www.python.org/download/pre-releases * https://www.python.org/downloads/release/python-3140rc2 --- .github/workflows/main.yml | 2 ++ docs/index.md | 2 +- pyproject.toml | 4 ++++ tox.ini | 4 ++++ 4 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 6d930bff9..45e745ccc 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -18,6 +18,7 @@ jobs: - '3.11' - '3.12' - '3.13' + - '3.14' steps: - uses: actions/checkout@v5 @@ -25,6 +26,7 @@ jobs: - uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} + allow-prereleases: true cache: 'pip' cache-dependency-path: 'requirements/*.txt' diff --git a/docs/index.md b/docs/index.md index 64dd28a45..87330f5af 100644 --- a/docs/index.md +++ b/docs/index.md @@ -88,7 +88,7 @@ continued development by **[signing up for a paid plan][funding]**. REST framework requires the following: * Django (4.2, 5.0, 5.1, 5.2) -* Python (3.10, 3.11, 3.12, 3.13) +* Python (3.10, 3.11, 3.12, 3.13, 3.14) We **highly recommend** and only officially support the latest patch release of each Python and Django series. diff --git a/pyproject.toml b/pyproject.toml index 37308429b..f5551d80a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", "Topic :: Internet :: WWW/HTTP", ] dynamic = [ "version" ] @@ -56,6 +57,9 @@ known_first_party = [ "rest_framework", "tests" ] skip = "*/kickstarter-announcement.md,*.js,*.map,*.po" ignore-words-list = "fo,malcom,ser" +[tool.pyproject-fmt] +max_supported_python = "3.14" + [tool.pytest.ini_options] addopts = "--tb=short --strict-markers -ra" testpaths = [ "tests" ] diff --git a/tox.ini b/tox.ini index f2df7301a..cbaaf159e 100644 --- a/tox.ini +++ b/tox.ini @@ -4,6 +4,7 @@ envlist = {py311}-{django42,django51,django52} {py312}-{django42,django51,django52,djangomain} {py313}-{django51,django52,djangomain} + {py314}-{django52,djangomain} base dist docs @@ -49,3 +50,6 @@ ignore_outcome = true [testenv:py313-djangomain] ignore_outcome = true + +[testenv:py314-djangomain] +ignore_outcome = true From a323cf7c0a33d7ffd395a6805019f613fb79f985 Mon Sep 17 00:00:00 2001 From: Uchenna Adubasim <76544543+journpy@users.noreply.github.com> Date: Thu, 9 Oct 2025 05:27:01 +0100 Subject: [PATCH 02/19] improved docs/api-guide/filtering.md for better understanding (#9795) --- docs/api-guide/filtering.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 6c80dc754..d36d4ce95 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -235,7 +235,7 @@ For example: search_fields = ['=username', '=email'] -By default, the search parameter is named `'search'`, but this may be overridden with the `SEARCH_PARAM` setting. +By default, the search parameter is named `'search'`, but this may be overridden with the `SEARCH_PARAM` setting in the `REST_FRAMEWORK` configuration. To dynamically change search fields based on request content, it's possible to subclass the `SearchFilter` and override the `get_search_fields()` function. For example, the following subclass will only search on `title` if the query parameter `title_only` is in the request: @@ -257,7 +257,7 @@ The `OrderingFilter` class supports simple query parameter controlled ordering o ![Ordering Filter](../img/ordering-filter.png) -By default, the query parameter is named `'ordering'`, but this may be overridden with the `ORDERING_PARAM` setting. +By default, the query parameter is named `'ordering'`, but this may be overridden with the `ORDERING_PARAM` setting in the `REST_FRAMEWORK` configuration. For example, to order users by username: From 9cf6efb4a8de4e99ee77217f088879889b4b3e85 Mon Sep 17 00:00:00 2001 From: Sergei Aleshin <66841202+s-aleshin@users.noreply.github.com> Date: Thu, 9 Oct 2025 21:47:30 +0400 Subject: [PATCH 03/19] Support `violation_error_code` and `violation_error_message` from `UniqueConstraint` in `UniqueTogetherValidator` (#9766) * fix(serializer): restore get_unique_together_constraints method signature Extracted error message logic to a separate method. fix: conditionally include violation_error_code for Django >= 5.0 fix(validators): use custom error message and code from model constraints * fix: add model parents to create unique_constraint_by_fields * fix: order of model classes in the unique_constraint_by_fields --- rest_framework/serializers.py | 24 +++++++++++++++++ rest_framework/validators.py | 7 +++-- tests/test_validators.py | 51 +++++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 2 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 8fe284bc8..5ca1ad55f 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -1569,6 +1569,17 @@ class ModelSerializer(Serializer): self.get_unique_for_date_validators() ) + def _get_constraint_violation_error_message(self, constraint): + """ + Returns the violation error message for the UniqueConstraint, + or None if the message is the default. + """ + violation_error_message = constraint.get_violation_error_message() + default_error_message = constraint.default_violation_error_message % {"name": constraint.name} + if violation_error_message == default_error_message: + return None + return violation_error_message + def get_unique_together_validators(self): """ Determine a default set of validators for any unique_together constraints. @@ -1595,6 +1606,13 @@ class ModelSerializer(Serializer): for name, source in field_sources.items(): source_map[source].append(name) + unique_constraint_by_fields = { + constraint.fields: constraint + for model_cls in (*self.Meta.model._meta.parents, self.Meta.model) + for constraint in model_cls._meta.constraints + if isinstance(constraint, models.UniqueConstraint) + } + # Note that we make sure to check `unique_together` both on the # base model class, but also on any parent classes. validators = [] @@ -1621,11 +1639,17 @@ class ModelSerializer(Serializer): ) field_names = tuple(source_map[f][0] for f in unique_together) + + constraint = unique_constraint_by_fields.get(tuple(unique_together)) + violation_error_message = self._get_constraint_violation_error_message(constraint) if constraint else None + validator = UniqueTogetherValidator( queryset=queryset, fields=field_names, condition_fields=tuple(source_map[f][0] for f in condition_fields), condition=condition, + message=violation_error_message, + code=getattr(constraint, 'violation_error_code', None), ) validators.append(validator) return validators diff --git a/rest_framework/validators.py b/rest_framework/validators.py index 76d2a2159..cc759b39c 100644 --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -111,13 +111,15 @@ class UniqueTogetherValidator: message = _('The fields {field_names} must make a unique set.') missing_message = _('This field is required.') requires_context = True + code = 'unique' - def __init__(self, queryset, fields, message=None, condition_fields=None, condition=None): + def __init__(self, queryset, fields, message=None, condition_fields=None, condition=None, code=None): self.queryset = queryset self.fields = fields self.message = message or self.message self.condition_fields = [] if condition_fields is None else condition_fields self.condition = condition + self.code = code or self.code def enforce_required_fields(self, attrs, serializer): """ @@ -198,7 +200,7 @@ class UniqueTogetherValidator: if checked_values and None not in checked_values and qs_exists_with_condition(queryset, self.condition, condition_kwargs): field_names = ', '.join(self.fields) message = self.message.format(field_names=field_names) - raise ValidationError(message, code='unique') + raise ValidationError(message, code=self.code) def __repr__(self): return '<{}({})>'.format( @@ -217,6 +219,7 @@ class UniqueTogetherValidator: and self.missing_message == other.missing_message and self.queryset == other.queryset and self.fields == other.fields + and self.code == other.code ) diff --git a/tests/test_validators.py b/tests/test_validators.py index ea5bf3a4d..79d4c0cf8 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -616,6 +616,26 @@ class UniqueConstraintNullableModel(models.Model): ] +class UniqueConstraintCustomMessageCodeModel(models.Model): + username = models.CharField(max_length=32) + company_id = models.IntegerField() + role = models.CharField(max_length=32) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=("username", "company_id"), + name="unique_username_company_custom_msg", + violation_error_message="Username must be unique within a company.", + **(dict(violation_error_code="duplicate_username") if django_version[0] >= 5 else {}), + ), + models.UniqueConstraint( + fields=("company_id", "role"), + name="unique_company_role_default_msg", + ), + ] + + class UniqueConstraintSerializer(serializers.ModelSerializer): class Meta: model = UniqueConstraintModel @@ -628,6 +648,12 @@ class UniqueConstraintNullableSerializer(serializers.ModelSerializer): fields = ('title', 'age', 'tag') +class UniqueConstraintCustomMessageCodeSerializer(serializers.ModelSerializer): + class Meta: + model = UniqueConstraintCustomMessageCodeModel + fields = ('username', 'company_id', 'role') + + class TestUniqueConstraintValidation(TestCase): def setUp(self): self.instance = UniqueConstraintModel.objects.create( @@ -778,6 +804,31 @@ class TestUniqueConstraintValidation(TestCase): ) assert serializer.is_valid() + def test_unique_constraint_custom_message_code(self): + UniqueConstraintCustomMessageCodeModel.objects.create(username="Alice", company_id=1, role="member") + expected_code = "duplicate_username" if django_version[0] >= 5 else UniqueTogetherValidator.code + + serializer = UniqueConstraintCustomMessageCodeSerializer(data={ + "username": "Alice", + "company_id": 1, + "role": "admin", + }) + assert not serializer.is_valid() + assert serializer.errors == {"non_field_errors": ["Username must be unique within a company."]} + assert serializer.errors["non_field_errors"][0].code == expected_code + + def test_unique_constraint_default_message_code(self): + UniqueConstraintCustomMessageCodeModel.objects.create(username="Alice", company_id=1, role="member") + serializer = UniqueConstraintCustomMessageCodeSerializer(data={ + "username": "John", + "company_id": 1, + "role": "member", + }) + expected_message = UniqueTogetherValidator.message.format(field_names=', '.join(("company_id", "role"))) + assert not serializer.is_valid() + assert serializer.errors == {"non_field_errors": [expected_message]} + assert serializer.errors["non_field_errors"][0].code == UniqueTogetherValidator.code + # Tests for `UniqueForDateValidator` # ---------------------------------- From c0f3649224117609d19e79c77242b525570d25c0 Mon Sep 17 00:00:00 2001 From: Syed Mehdi <114935139+Infamous003@users.noreply.github.com> Date: Tue, 14 Oct 2025 11:31:35 +0530 Subject: [PATCH 04/19] docs: Add syntax highlighting to code examples (#9794) --- docs/tutorial/1-serialization.md | 447 ++++++++++-------- docs/tutorial/2-requests-and-responses.md | 223 +++++---- docs/tutorial/3-class-based-views.md | 189 ++++---- .../4-authentication-and-permissions.md | 195 +++++--- .../5-relationships-and-hyperlinked-apis.md | 146 +++--- docs/tutorial/6-viewsets-and-routers.md | 139 +++--- docs/tutorial/quickstart.md | 262 +++++----- 7 files changed, 898 insertions(+), 703 deletions(-) diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index b9bf67acb..99393bbaa 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -16,14 +16,18 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o Before we do anything else we'll create a new virtual environment, using [venv]. This will make sure our package configuration is kept nicely isolated from any other projects we're working on. - python3 -m venv env - source env/bin/activate +```bash +python3 -m venv env +source env/bin/activate +``` Now that we're inside a virtual environment, we can install our package requirements. - pip install django - pip install djangorestframework - pip install pygments # We'll be using this for the code highlighting +```bash +pip install django +pip install djangorestframework +pip install pygments # We'll be using this for the code highlighting +``` **Note:** To exit the virtual environment at any time, just type `deactivate`. For more information see the [venv documentation][venv]. @@ -32,21 +36,27 @@ Now that we're inside a virtual environment, we can install our package requirem Okay, we're ready to get coding. To get started, let's create a new project to work with. - cd ~ - django-admin startproject tutorial - cd tutorial +```bash +cd ~ +django-admin startproject tutorial +cd tutorial +``` Once that's done we can create an app that we'll use to create a simple Web API. - python manage.py startapp snippets +```bash +python manage.py startapp snippets +``` We'll need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. Let's edit the `tutorial/settings.py` file: - INSTALLED_APPS = [ - ... - 'rest_framework', - 'snippets', - ] +```text +INSTALLED_APPS = [ + ... + 'rest_framework', + 'snippets', +] +``` Okay, we're ready to roll. @@ -54,64 +64,72 @@ Okay, we're ready to roll. For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets/models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself. - from django.db import models - from pygments.lexers import get_all_lexers - from pygments.styles import get_all_styles +```python +from django.db import models +from pygments.lexers import get_all_lexers +from pygments.styles import get_all_styles - LEXERS = [item for item in get_all_lexers() if item[1]] - LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) - STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()]) +LEXERS = [item for item in get_all_lexers() if item[1]] +LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) +STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()]) - class Snippet(models.Model): - created = models.DateTimeField(auto_now_add=True) - title = models.CharField(max_length=100, blank=True, default='') - code = models.TextField() - linenos = models.BooleanField(default=False) - language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) - style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) +class Snippet(models.Model): + created = models.DateTimeField(auto_now_add=True) + title = models.CharField(max_length=100, blank=True, default="") + code = models.TextField() + linenos = models.BooleanField(default=False) + language = models.CharField( + choices=LANGUAGE_CHOICES, default="python", max_length=100 + ) + style = models.CharField(choices=STYLE_CHOICES, default="friendly", max_length=100) - class Meta: - ordering = ['created'] + class Meta: + ordering = ["created"] +``` We'll also need to create an initial migration for our snippet model, and sync the database for the first time. - python manage.py makemigrations snippets - python manage.py migrate snippets +```bash +python manage.py makemigrations snippets +python manage.py migrate snippets +``` ## Creating a Serializer class The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as `json`. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the `snippets` directory named `serializers.py` and add the following. - from rest_framework import serializers - from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES +```python +from rest_framework import serializers +from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES - class SnippetSerializer(serializers.Serializer): - id = serializers.IntegerField(read_only=True) - title = serializers.CharField(required=False, allow_blank=True, max_length=100) - code = serializers.CharField(style={'base_template': 'textarea.html'}) - linenos = serializers.BooleanField(required=False) - language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') - style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') +class SnippetSerializer(serializers.Serializer): + id = serializers.IntegerField(read_only=True) + title = serializers.CharField(required=False, allow_blank=True, max_length=100) + code = serializers.CharField(style={"base_template": "textarea.html"}) + linenos = serializers.BooleanField(required=False) + language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default="python") + style = serializers.ChoiceField(choices=STYLE_CHOICES, default="friendly") - def create(self, validated_data): - """ - Create and return a new `Snippet` instance, given the validated data. - """ - return Snippet.objects.create(**validated_data) + def create(self, validated_data): + """ + Create and return a new `Snippet` instance, given the validated data. + """ + return Snippet.objects.create(**validated_data) - def update(self, instance, validated_data): - """ - Update and return an existing `Snippet` instance, given the validated data. - """ - instance.title = validated_data.get('title', instance.title) - instance.code = validated_data.get('code', instance.code) - instance.linenos = validated_data.get('linenos', instance.linenos) - instance.language = validated_data.get('language', instance.language) - instance.style = validated_data.get('style', instance.style) - instance.save() - return instance + def update(self, instance, validated_data): + """ + Update and return an existing `Snippet` instance, given the validated data. + """ + instance.title = validated_data.get("title", instance.title) + instance.code = validated_data.get("code", instance.code) + instance.linenos = validated_data.get("linenos", instance.linenos) + instance.language = validated_data.get("language", instance.language) + instance.style = validated_data.get("style", instance.style) + instance.save() + return instance +``` The first part of the serializer class defines the fields that get serialized/deserialized. The `create()` and `update()` methods define how fully fledged instances are created or modified when calling `serializer.save()` @@ -125,57 +143,71 @@ We can actually also save ourselves some time by using the `ModelSerializer` cla Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell. - python manage.py shell +```bash +python manage.py shell +``` Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with. - from snippets.models import Snippet - from snippets.serializers import SnippetSerializer - from rest_framework.renderers import JSONRenderer - from rest_framework.parsers import JSONParser +```pycon +>>> from snippets.models import Snippet +>>> from snippets.serializers import SnippetSerializer +>>> from rest_framework.renderers import JSONRenderer +>>> from rest_framework.parsers import JSONParser - snippet = Snippet(code='foo = "bar"\n') - snippet.save() +>>> snippet = Snippet(code='foo = "bar"\n') +>>> snippet.save() - snippet = Snippet(code='print("hello, world")\n') - snippet.save() +>>> snippet = Snippet(code='print("hello, world")\n') +>>> snippet.save() +``` We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances. - serializer = SnippetSerializer(snippet) - serializer.data - # {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'} +```pycon +>>> serializer = SnippetSerializer(snippet) +>>> serializer.data +{'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'} +``` At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`. - content = JSONRenderer().render(serializer.data) - content - # b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}' +```pycon +>>> content = JSONRenderer().render(serializer.data) +>>> content +b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}' +``` Deserialization is similar. First we parse a stream into Python native datatypes... - import io +```pycon +>>> import io - stream = io.BytesIO(content) - data = JSONParser().parse(stream) +>>> stream = io.BytesIO(content) +>>> data = JSONParser().parse(stream) +``` ...then we restore those native datatypes into a fully populated object instance. - serializer = SnippetSerializer(data=data) - serializer.is_valid() - # True - serializer.validated_data - # {'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'} - serializer.save() - # +```pycon +>>> serializer = SnippetSerializer(data=data) +>>> serializer.is_valid() +True +>>> serializer.validated_data +{'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'} +>>> serializer.save() + +``` Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer. We can also serialize querysets instead of model instances. To do so we simply add a `many=True` flag to the serializer arguments. - serializer = SnippetSerializer(Snippet.objects.all(), many=True) - serializer.data - # [{'id': 1, 'title': '', 'code': 'foo = "bar"\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 3, 'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}] +```pycon +>>> serializer = SnippetSerializer(Snippet.objects.all(), many=True) +>>> serializer.data +[{'id': 1, 'title': '', 'code': 'foo = "bar"\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 3, 'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}] +``` ## Using ModelSerializers @@ -186,23 +218,28 @@ In the same way that Django provides both `Form` classes and `ModelForm` classes Let's look at refactoring our serializer using the `ModelSerializer` class. Open the file `snippets/serializers.py` again, and replace the `SnippetSerializer` class with the following. - class SnippetSerializer(serializers.ModelSerializer): - class Meta: - model = Snippet - fields = ['id', 'title', 'code', 'linenos', 'language', 'style'] +```python +class SnippetSerializer(serializers.ModelSerializer): + class Meta: + model = Snippet + fields = ["id", "title", "code", "linenos", "language", "style"] +``` One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with `python manage.py shell`, then try the following: - from snippets.serializers import SnippetSerializer - serializer = SnippetSerializer() - print(repr(serializer)) - # SnippetSerializer(): - # id = IntegerField(label='ID', read_only=True) - # title = CharField(allow_blank=True, max_length=100, required=False) - # code = CharField(style={'base_template': 'textarea.html'}) - # linenos = BooleanField(required=False) - # language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... - # style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')... +```pycon +>>> from snippets.serializers import SnippetSerializer + +>>> serializer = SnippetSerializer() +>>> print(repr(serializer)) +SnippetSerializer(): + id = IntegerField(label='ID', read_only=True) + title = CharField(allow_blank=True, max_length=100, required=False) + code = CharField(style={'base_template': 'textarea.html'}) + linenos = BooleanField(required=False) + language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... + style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')... +``` It's important to remember that `ModelSerializer` classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes: @@ -216,79 +253,89 @@ For the moment we won't use any of REST framework's other features, we'll just w Edit the `snippets/views.py` file, and add the following. - from django.http import HttpResponse, JsonResponse - from django.views.decorators.csrf import csrf_exempt - from rest_framework.parsers import JSONParser - from snippets.models import Snippet - from snippets.serializers import SnippetSerializer +```python +from django.http import HttpResponse, JsonResponse +from django.views.decorators.csrf import csrf_exempt +from rest_framework.parsers import JSONParser +from snippets.models import Snippet +from snippets.serializers import SnippetSerializer +``` The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet. - @csrf_exempt - def snippet_list(request): - """ - List all code snippets, or create a new snippet. - """ - if request.method == 'GET': - snippets = Snippet.objects.all() - serializer = SnippetSerializer(snippets, many=True) - return JsonResponse(serializer.data, safe=False) +```python +@csrf_exempt +def snippet_list(request): + """ + List all code snippets, or create a new snippet. + """ + if request.method == "GET": + snippets = Snippet.objects.all() + serializer = SnippetSerializer(snippets, many=True) + return JsonResponse(serializer.data, safe=False) - elif request.method == 'POST': - data = JSONParser().parse(request) - serializer = SnippetSerializer(data=data) - if serializer.is_valid(): - serializer.save() - return JsonResponse(serializer.data, status=201) - return JsonResponse(serializer.errors, status=400) + elif request.method == "POST": + data = JSONParser().parse(request) + serializer = SnippetSerializer(data=data) + if serializer.is_valid(): + serializer.save() + return JsonResponse(serializer.data, status=201) + return JsonResponse(serializer.errors, status=400) +``` Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as `csrf_exempt`. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now. We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet. - @csrf_exempt - def snippet_detail(request, pk): - """ - Retrieve, update or delete a code snippet. - """ - try: - snippet = Snippet.objects.get(pk=pk) - except Snippet.DoesNotExist: - return HttpResponse(status=404) +```python +@csrf_exempt +def snippet_detail(request, pk): + """ + Retrieve, update or delete a code snippet. + """ + try: + snippet = Snippet.objects.get(pk=pk) + except Snippet.DoesNotExist: + return HttpResponse(status=404) - if request.method == 'GET': - serializer = SnippetSerializer(snippet) + if request.method == "GET": + serializer = SnippetSerializer(snippet) + return JsonResponse(serializer.data) + + elif request.method == "PUT": + data = JSONParser().parse(request) + serializer = SnippetSerializer(snippet, data=data) + if serializer.is_valid(): + serializer.save() return JsonResponse(serializer.data) + return JsonResponse(serializer.errors, status=400) - elif request.method == 'PUT': - data = JSONParser().parse(request) - serializer = SnippetSerializer(snippet, data=data) - if serializer.is_valid(): - serializer.save() - return JsonResponse(serializer.data) - return JsonResponse(serializer.errors, status=400) - - elif request.method == 'DELETE': - snippet.delete() - return HttpResponse(status=204) + elif request.method == "DELETE": + snippet.delete() + return HttpResponse(status=204) +``` Finally we need to wire these views up. Create the `snippets/urls.py` file: - from django.urls import path - from snippets import views +```python +from django.urls import path +from snippets import views - urlpatterns = [ - path('snippets/', views.snippet_list), - path('snippets//', views.snippet_detail), - ] +urlpatterns = [ + path("snippets/", views.snippet_list), + path("snippets//", views.snippet_detail), +] +``` We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs. - from django.urls import path, include +```python +from django.urls import path, include - urlpatterns = [ - path('', include('snippets.urls')), - ] +urlpatterns = [ + path("", include("snippets.urls")), +] +``` It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now. @@ -298,18 +345,22 @@ Now we can start up a sample server that serves our snippets. Quit out of the shell... - quit() +```pycon +>>> quit() +``` ...and start up Django's development server. - python manage.py runserver +```bash +python manage.py runserver - Validating models... +Validating models... - 0 errors found - Django version 5.0, using settings 'tutorial.settings' - Starting Development server at http://127.0.0.1:8000/ - Quit the server with CONTROL-C. +0 errors found +Django version 5.0, using settings 'tutorial.settings' +Starting Development server at http://127.0.0.1:8000/ +Quit the server with CONTROL-C. +``` In another terminal window, we can test the server. @@ -317,47 +368,26 @@ We can test our API using [curl][curl] or [httpie][httpie]. Httpie is a user fri You can install httpie using pip: - pip install httpie +```bash +pip install httpie +``` Finally, we can get a list of all of the snippets: - http GET http://127.0.0.1:8000/snippets/ --unsorted +```bash +http GET http://127.0.0.1:8000/snippets/ --unsorted - HTTP/1.1 200 OK - ... - [ - { - "id": 1, - "title": "", - "code": "foo = \"bar\"\n", - "linenos": false, - "language": "python", - "style": "friendly" - }, - { - "id": 2, - "title": "", - "code": "print(\"hello, world\")\n", - "linenos": false, - "language": "python", - "style": "friendly" - }, - { - "id": 3, - "title": "", - "code": "print(\"hello, world\")", - "linenos": false, - "language": "python", - "style": "friendly" - } - ] - -Or we can get a particular snippet by referencing its id: - - http GET http://127.0.0.1:8000/snippets/2/ --unsorted - - HTTP/1.1 200 OK - ... +HTTP/1.1 200 OK +... +[ + { + "id": 1, + "title": "", + "code": "foo = \"bar\"\n", + "linenos": false, + "language": "python", + "style": "friendly" + }, { "id": 2, "title": "", @@ -365,7 +395,34 @@ Or we can get a particular snippet by referencing its id: "linenos": false, "language": "python", "style": "friendly" + }, + { + "id": 3, + "title": "", + "code": "print(\"hello, world\")", + "linenos": false, + "language": "python", + "style": "friendly" } +] +``` + +Or we can get a particular snippet by referencing its id: + +```bash +http GET http://127.0.0.1:8000/snippets/2/ --unsorted + +HTTP/1.1 200 OK +... +{ + "id": 2, + "title": "", + "code": "print(\"hello, world\")\n", + "linenos": false, + "language": "python", + "style": "friendly" +} +``` Similarly, you can have the same json displayed by visiting these URLs in a web browser. diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 47c7facfc..fceb118bd 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -7,14 +7,18 @@ Let's introduce a couple of essential building blocks. REST framework introduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.data` attribute, which is similar to `request.POST`, but more useful for working with Web APIs. - request.POST # Only handles form data. Only works for 'POST' method. - request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods. +```python +request.POST # Only handles form data. Only works for 'POST' method. +request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods. +``` ## Response objects REST framework also introduces a `Response` object, which is a type of `TemplateResponse` that takes unrendered content and uses content negotiation to determine the correct content type to return to the client. - return Response(data) # Renders to content type as requested by the client. +```python +return Response(data) # Renders to content type as requested by the client. +``` ## Status codes @@ -35,58 +39,62 @@ The wrappers also provide behavior such as returning `405 Method Not Allowed` re Okay, let's go ahead and start using these new components to refactor our views slightly. - from rest_framework import status - from rest_framework.decorators import api_view - from rest_framework.response import Response - from snippets.models import Snippet - from snippets.serializers import SnippetSerializer +```python +from rest_framework import status +from rest_framework.decorators import api_view +from rest_framework.response import Response +from snippets.models import Snippet +from snippets.serializers import SnippetSerializer - @api_view(['GET', 'POST']) - def snippet_list(request): - """ - List all code snippets, or create a new snippet. - """ - if request.method == 'GET': - snippets = Snippet.objects.all() - serializer = SnippetSerializer(snippets, many=True) - return Response(serializer.data) +@api_view(["GET", "POST"]) +def snippet_list(request): + """ + List all code snippets, or create a new snippet. + """ + if request.method == "GET": + snippets = Snippet.objects.all() + serializer = SnippetSerializer(snippets, many=True) + return Response(serializer.data) - elif request.method == 'POST': - serializer = SnippetSerializer(data=request.data) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data, status=status.HTTP_201_CREATED) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + elif request.method == "POST": + serializer = SnippetSerializer(data=request.data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) +``` Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious. Here is the view for an individual snippet, in the `views.py` module. - @api_view(['GET', 'PUT', 'DELETE']) - def snippet_detail(request, pk): - """ - Retrieve, update or delete a code snippet. - """ - try: - snippet = Snippet.objects.get(pk=pk) - except Snippet.DoesNotExist: - return Response(status=status.HTTP_404_NOT_FOUND) +```python +@api_view(["GET", "PUT", "DELETE"]) +def snippet_detail(request, pk): + """ + Retrieve, update or delete a code snippet. + """ + try: + snippet = Snippet.objects.get(pk=pk) + except Snippet.DoesNotExist: + return Response(status=status.HTTP_404_NOT_FOUND) - if request.method == 'GET': - serializer = SnippetSerializer(snippet) + if request.method == "GET": + serializer = SnippetSerializer(snippet) + return Response(serializer.data) + + elif request.method == "PUT": + serializer = SnippetSerializer(snippet, data=request.data) + if serializer.is_valid(): + serializer.save() return Response(serializer.data) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - elif request.method == 'PUT': - serializer = SnippetSerializer(snippet, data=request.data) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - - elif request.method == 'DELETE': - snippet.delete() - return Response(status=status.HTTP_204_NO_CONTENT) + elif request.method == "DELETE": + snippet.delete() + return Response(status=status.HTTP_204_NO_CONTENT) +``` This should all feel very familiar - it is not a lot different from working with regular Django views. @@ -94,28 +102,27 @@ Notice that we're no longer explicitly tying our requests or responses to a give ## Adding optional format suffixes to our URLs -To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4.json][json-url]. +To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [][json-url]. Start by adding a `format` keyword argument to both of the views, like so. - - def snippet_list(request, format=None): - +`def snippet_list(request, format=None):` and - - def snippet_detail(request, pk, format=None): +`def snippet_detail(request, pk, format=None):` Now update the `snippets/urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs. - from django.urls import path - from rest_framework.urlpatterns import format_suffix_patterns - from snippets import views +```python +from django.urls import path +from rest_framework.urlpatterns import format_suffix_patterns +from snippets import views - urlpatterns = [ - path('snippets/', views.snippet_list), - path('snippets//', views.snippet_detail), - ] +urlpatterns = [ + path("snippets/", views.snippet_list), + path("snippets//", views.snippet_detail), +] - urlpatterns = format_suffix_patterns(urlpatterns) +urlpatterns = format_suffix_patterns(urlpatterns) +``` We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format. @@ -125,68 +132,76 @@ Go ahead and test the API from the command line, as we did in [tutorial part 1][ We can get a list of all of the snippets, as before. - http http://127.0.0.1:8000/snippets/ +```bash +http http://127.0.0.1:8000/snippets/ - HTTP/1.1 200 OK - ... - [ - { - "id": 1, - "title": "", - "code": "foo = \"bar\"\n", - "linenos": false, - "language": "python", - "style": "friendly" - }, - { - "id": 2, - "title": "", - "code": "print(\"hello, world\")\n", - "linenos": false, - "language": "python", - "style": "friendly" - } - ] +HTTP/1.1 200 OK +... +[ + { + "id": 1, + "title": "", + "code": "foo = \"bar\"\n", + "linenos": false, + "language": "python", + "style": "friendly" + }, + { + "id": 2, + "title": "", + "code": "print(\"hello, world\")\n", + "linenos": false, + "language": "python", + "style": "friendly" + } +] +``` We can control the format of the response that we get back, either by using the `Accept` header: - http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON - http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML +```bash +http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON +http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML +``` Or by appending a format suffix: - http http://127.0.0.1:8000/snippets.json # JSON suffix - http http://127.0.0.1:8000/snippets.api # Browsable API suffix +```bash +http http://127.0.0.1:8000/snippets.json # JSON suffix +http http://127.0.0.1:8000/snippets.api # Browsable API suffix +``` Similarly, we can control the format of the request that we send, using the `Content-Type` header. - # POST using form data - http --form POST http://127.0.0.1:8000/snippets/ code="print(123)" +```bash +# POST using form data +http --form POST http://127.0.0.1:8000/snippets/ code="print(123)" - { - "id": 3, - "title": "", - "code": "print(123)", - "linenos": false, - "language": "python", - "style": "friendly" - } +{ + "id": 3, + "title": "", + "code": "print(123)", + "linenos": false, + "language": "python", + "style": "friendly" +} - # POST using JSON - http --json POST http://127.0.0.1:8000/snippets/ code="print(456)" +# POST using JSON +http --json POST http://127.0.0.1:8000/snippets/ code="print(456)" - { - "id": 4, - "title": "", - "code": "print(456)", - "linenos": false, - "language": "python", - "style": "friendly" - } +{ + "id": 4, + "title": "", + "code": "print(456)", + "linenos": false, + "language": "python", + "style": "friendly" +} +``` If you add a `--debug` switch to the `http` requests above, you will be able to see the request type in request headers. -Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver]. +Now go and open the API in a web browser, by visiting [][devserver]. ### Browsability diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index ccfcd095d..59aee8813 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -6,74 +6,82 @@ We can also write our API views using class-based views, rather than function ba We'll start by rewriting the root view as a class-based view. All this involves is a little bit of refactoring of `views.py`. - from snippets.models import Snippet - from snippets.serializers import SnippetSerializer - from django.http import Http404 - from rest_framework.views import APIView - from rest_framework.response import Response - from rest_framework import status +```python +from snippets.models import Snippet +from snippets.serializers import SnippetSerializer +from django.http import Http404 +from rest_framework.views import APIView +from rest_framework.response import Response +from rest_framework import status - class SnippetList(APIView): - """ - List all snippets, or create a new snippet. - """ - def get(self, request, format=None): - snippets = Snippet.objects.all() - serializer = SnippetSerializer(snippets, many=True) - return Response(serializer.data) +class SnippetList(APIView): + """ + List all snippets, or create a new snippet. + """ - def post(self, request, format=None): - serializer = SnippetSerializer(data=request.data) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data, status=status.HTTP_201_CREATED) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + def get(self, request, format=None): + snippets = Snippet.objects.all() + serializer = SnippetSerializer(snippets, many=True) + return Response(serializer.data) + + def post(self, request, format=None): + serializer = SnippetSerializer(data=request.data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) +``` So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view in `views.py`. - class SnippetDetail(APIView): - """ - Retrieve, update or delete a snippet instance. - """ - def get_object(self, pk): - try: - return Snippet.objects.get(pk=pk) - except Snippet.DoesNotExist: - raise Http404 +```python +class SnippetDetail(APIView): + """ + Retrieve, update or delete a snippet instance. + """ - def get(self, request, pk, format=None): - snippet = self.get_object(pk) - serializer = SnippetSerializer(snippet) + def get_object(self, pk): + try: + return Snippet.objects.get(pk=pk) + except Snippet.DoesNotExist: + raise Http404 + + def get(self, request, pk, format=None): + snippet = self.get_object(pk) + serializer = SnippetSerializer(snippet) + return Response(serializer.data) + + def put(self, request, pk, format=None): + snippet = self.get_object(pk) + serializer = SnippetSerializer(snippet, data=request.data) + if serializer.is_valid(): + serializer.save() return Response(serializer.data) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - def put(self, request, pk, format=None): - snippet = self.get_object(pk) - serializer = SnippetSerializer(snippet, data=request.data) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - - def delete(self, request, pk, format=None): - snippet = self.get_object(pk) - snippet.delete() - return Response(status=status.HTTP_204_NO_CONTENT) + def delete(self, request, pk, format=None): + snippet = self.get_object(pk) + snippet.delete() + return Response(status=status.HTTP_204_NO_CONTENT) +``` That's looking good. Again, it's still pretty similar to the function based view right now. We'll also need to refactor our `snippets/urls.py` slightly now that we're using class-based views. - from django.urls import path - from rest_framework.urlpatterns import format_suffix_patterns - from snippets import views +```python +from django.urls import path +from rest_framework.urlpatterns import format_suffix_patterns +from snippets import views - urlpatterns = [ - path('snippets/', views.SnippetList.as_view()), - path('snippets//', views.SnippetDetail.as_view()), - ] +urlpatterns = [ + path("snippets/", views.SnippetList.as_view()), + path("snippets//", views.SnippetDetail.as_view()), +] - urlpatterns = format_suffix_patterns(urlpatterns) +urlpatterns = format_suffix_patterns(urlpatterns) +``` Okay, we're done. If you run the development server everything should be working just as before. @@ -85,42 +93,49 @@ The create/retrieve/update/delete operations that we've been using so far are go 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 snippets.models import Snippet - from snippets.serializers import SnippetSerializer - from rest_framework import mixins - from rest_framework import generics +```python +from snippets.models import Snippet +from snippets.serializers import SnippetSerializer +from rest_framework import mixins +from rest_framework import generics - class SnippetList(mixins.ListModelMixin, - mixins.CreateModelMixin, - generics.GenericAPIView): - queryset = Snippet.objects.all() - serializer_class = SnippetSerializer - def get(self, request, *args, **kwargs): - return self.list(request, *args, **kwargs) +class SnippetList( + mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView +): + queryset = Snippet.objects.all() + serializer_class = SnippetSerializer - def post(self, request, *args, **kwargs): - return self.create(request, *args, **kwargs) + def get(self, request, *args, **kwargs): + return self.list(request, *args, **kwargs) + + def post(self, request, *args, **kwargs): + return self.create(request, *args, **kwargs) +``` We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`. The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far. - class SnippetDetail(mixins.RetrieveModelMixin, - mixins.UpdateModelMixin, - mixins.DestroyModelMixin, - generics.GenericAPIView): - queryset = Snippet.objects.all() - serializer_class = SnippetSerializer +```python +class SnippetDetail( + mixins.RetrieveModelMixin, + mixins.UpdateModelMixin, + mixins.DestroyModelMixin, + generics.GenericAPIView, +): + queryset = Snippet.objects.all() + serializer_class = SnippetSerializer - def get(self, request, *args, **kwargs): - return self.retrieve(request, *args, **kwargs) + def get(self, request, *args, **kwargs): + return self.retrieve(request, *args, **kwargs) - def put(self, request, *args, **kwargs): - return self.update(request, *args, **kwargs) + def put(self, request, *args, **kwargs): + return self.update(request, *args, **kwargs) - def delete(self, request, *args, **kwargs): - return self.destroy(request, *args, **kwargs) + def delete(self, request, *args, **kwargs): + return self.destroy(request, *args, **kwargs) +``` Pretty similar. Again we're using the `GenericAPIView` class to provide the core functionality, and adding in mixins to provide the `.retrieve()`, `.update()` and `.destroy()` actions. @@ -128,19 +143,21 @@ Pretty similar. Again we're using the `GenericAPIView` class to provide the cor Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our `views.py` module even more. - from snippets.models import Snippet - from snippets.serializers import SnippetSerializer - from rest_framework import generics +```python +from snippets.models import Snippet +from snippets.serializers import SnippetSerializer +from rest_framework import generics - class SnippetList(generics.ListCreateAPIView): - queryset = Snippet.objects.all() - serializer_class = SnippetSerializer +class SnippetList(generics.ListCreateAPIView): + queryset = Snippet.objects.all() + serializer_class = SnippetSerializer - class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): - queryset = Snippet.objects.all() - serializer_class = SnippetSerializer +class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): + queryset = Snippet.objects.all() + serializer_class = SnippetSerializer +``` Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django. diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index cb0321ea2..cb5eef469 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -14,81 +14,103 @@ First, let's add a couple of fields. One of those fields will be used to repres Add the following two fields to the `Snippet` model in `models.py`. - owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE) - highlighted = models.TextField() +```python +owner = models.ForeignKey( + "auth.User", related_name="snippets", on_delete=models.CASCADE +) +highlighted = models.TextField() +``` We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code highlighting library. We'll need some extra imports: - from pygments.lexers import get_lexer_by_name - from pygments.formatters.html import HtmlFormatter - from pygments import highlight +```python +from pygments.lexers import get_lexer_by_name +from pygments.formatters.html import HtmlFormatter +from pygments import highlight +``` And now we can add a `.save()` method to our model class: - def save(self, *args, **kwargs): - """ - Use the `pygments` library to create a highlighted HTML - representation of the code snippet. - """ - lexer = get_lexer_by_name(self.language) - linenos = 'table' if self.linenos else False - options = {'title': self.title} if self.title else {} - formatter = HtmlFormatter(style=self.style, linenos=linenos, - full=True, **options) - self.highlighted = highlight(self.code, lexer, formatter) - super().save(*args, **kwargs) +```python +def save(self, *args, **kwargs): + """ + Use the `pygments` library to create a highlighted HTML + representation of the code snippet. + """ + lexer = get_lexer_by_name(self.language) + linenos = "table" if self.linenos else False + options = {"title": self.title} if self.title else {} + formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) + self.highlighted = highlight(self.code, lexer, formatter) + super().save(*args, **kwargs) +``` When that's all done we'll need to update our database tables. Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again. - rm -f db.sqlite3 - rm -r snippets/migrations - python manage.py makemigrations snippets - python manage.py migrate +```bash +rm -f db.sqlite3 +rm -r snippets/migrations +python manage.py makemigrations snippets +python manage.py migrate +``` You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the `createsuperuser` command. - python manage.py createsuperuser +```bash +python manage.py createsuperuser +``` ## Adding endpoints for our User models Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In `serializers.py` add: - from django.contrib.auth.models import User +```python +from django.contrib.auth.models import User - class UserSerializer(serializers.ModelSerializer): - snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all()) - class Meta: - model = User - fields = ['id', 'username', 'snippets'] +class UserSerializer(serializers.ModelSerializer): + snippets = serializers.PrimaryKeyRelatedField( + many=True, queryset=Snippet.objects.all() + ) + + class Meta: + model = User + fields = ["id", "username", "snippets"] +``` Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it. We'll also add a couple of views to `views.py`. We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class-based views. - from django.contrib.auth.models import User +```python +from django.contrib.auth.models import User - class UserList(generics.ListAPIView): - queryset = User.objects.all() - serializer_class = UserSerializer +class UserList(generics.ListAPIView): + queryset = User.objects.all() + serializer_class = UserSerializer - class UserDetail(generics.RetrieveAPIView): - queryset = User.objects.all() - serializer_class = UserSerializer +class UserDetail(generics.RetrieveAPIView): + queryset = User.objects.all() + serializer_class = UserSerializer +``` Make sure to also import the `UserSerializer` class - from snippets.serializers import UserSerializer +```python +from snippets.serializers import UserSerializer +``` Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `snippets/urls.py`. - path('users/', views.UserList.as_view()), - path('users//', views.UserDetail.as_view()), +```python +path("users/", views.UserList.as_view()), +path("users//", views.UserDetail.as_view()), +``` ## Associating Snippets with Users @@ -98,8 +120,10 @@ The way we deal with that is by overriding a `.perform_create()` method on our s On the `SnippetList` view class, add the following method: - def perform_create(self, serializer): - serializer.save(owner=self.request.user) +```python +def perform_create(self, serializer): + serializer.save(owner=self.request.user) +``` The `create()` method of our serializer will now be passed an additional `'owner'` field, along with the validated data from the request. @@ -107,7 +131,9 @@ The `create()` method of our serializer will now be passed an additional `'owner Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition in `serializers.py`: - owner = serializers.ReadOnlyField(source='owner.username') +```python +owner = serializers.ReadOnlyField(source="owner.username") +``` **Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class. @@ -123,11 +149,15 @@ REST framework includes a number of permission classes that we can use to restri First add the following import in the views module - from rest_framework import permissions +```python +from rest_framework import permissions +``` Then, add the following property to **both** the `SnippetList` and `SnippetDetail` view classes. - permission_classes = [permissions.IsAuthenticatedOrReadOnly] +```python +permission_classes = [permissions.IsAuthenticatedOrReadOnly] +``` ## Adding login to the Browsable API @@ -137,13 +167,17 @@ We can add a login view for use with the browsable API, by editing the URLconf i Add the following import at the top of the file: - from django.urls import path, include +```python +from django.urls import path, include +``` And, at the end of the file, add a pattern to include the login and logout views for the browsable API. - urlpatterns += [ - path('api-auth/', include('rest_framework.urls')), - ] +```python +urlpatterns += [ + path("api-auth/", include("rest_framework.urls")), +] +``` The `'api-auth/'` part of pattern can actually be whatever URL you want to use. @@ -159,31 +193,36 @@ To do that we're going to need to create a custom permission. In the snippets app, create a new file, `permissions.py` - from rest_framework import permissions +```python +from rest_framework import permissions - class IsOwnerOrReadOnly(permissions.BasePermission): - """ - Custom permission to only allow owners of an object to edit it. - """ +class IsOwnerOrReadOnly(permissions.BasePermission): + """ + Custom permission to only allow owners of an object to edit it. + """ - def has_object_permission(self, request, view, obj): - # Read permissions are allowed to any request, - # so we'll always allow GET, HEAD or OPTIONS requests. - if request.method in permissions.SAFE_METHODS: - return True + def has_object_permission(self, request, view, obj): + # Read permissions are allowed to any request, + # so we'll always allow GET, HEAD or OPTIONS requests. + if request.method in permissions.SAFE_METHODS: + return True - # Write permissions are only allowed to the owner of the snippet. - return obj.owner == request.user + # Write permissions are only allowed to the owner of the snippet. + return obj.owner == request.user +``` Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` view class: - permission_classes = [permissions.IsAuthenticatedOrReadOnly, - IsOwnerOrReadOnly] +```python +permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] +``` Make sure to also import the `IsOwnerOrReadOnly` class. - from snippets.permissions import IsOwnerOrReadOnly +```python +from snippets.permissions import IsOwnerOrReadOnly +``` Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet. @@ -197,25 +236,29 @@ If we're interacting with the API programmatically we need to explicitly provide If we try to create a snippet without authenticating, we'll get an error: - http POST http://127.0.0.1:8000/snippets/ code="print(123)" +```bash +http POST http://127.0.0.1:8000/snippets/ code="print(123)" - { - "detail": "Authentication credentials were not provided." - } +{ + "detail": "Authentication credentials were not provided." +} +``` We can make a successful request by including the username and password of one of the users we created earlier. - http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)" +```bash +http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)" - { - "id": 1, - "owner": "admin", - "title": "foo", - "code": "print(789)", - "linenos": false, - "language": "python", - "style": "friendly" - } +{ + "id": 1, + "owner": "admin", + "title": "foo", + "code": "print(789)", + "linenos": false, + "language": "python", + "style": "friendly" +} +``` ## Summary diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index f5aaee2bb..3800c168b 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -6,17 +6,21 @@ At the moment relationships within our API are represented by using primary keys Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. In your `snippets/views.py` add: - from rest_framework.decorators import api_view - from rest_framework.response import Response - from rest_framework.reverse import reverse +```python +from rest_framework.decorators import api_view +from rest_framework.response import Response +from rest_framework.reverse import reverse - @api_view(['GET']) - def api_root(request, format=None): - return Response({ - 'users': reverse('user-list', request=request, format=format), - 'snippets': reverse('snippet-list', request=request, format=format) - }) +@api_view(["GET"]) +def api_root(request, format=None): + return Response( + { + "users": reverse("user-list", request=request, format=format), + "snippets": reverse("snippet-list", request=request, format=format), + } + ) +``` Two things should be noticed here. First, we're using REST framework's `reverse` function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our `snippets/urls.py`. @@ -30,24 +34,31 @@ The other thing we need to consider when creating the code highlight view is tha Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets/views.py` add: - from rest_framework import renderers +```python +from rest_framework import renderers - class SnippetHighlight(generics.GenericAPIView): - queryset = Snippet.objects.all() - renderer_classes = [renderers.StaticHTMLRenderer] - def get(self, request, *args, **kwargs): - snippet = self.get_object() - return Response(snippet.highlighted) +class SnippetHighlight(generics.GenericAPIView): + queryset = Snippet.objects.all() + renderer_classes = [renderers.StaticHTMLRenderer] + + def get(self, request, *args, **kwargs): + snippet = self.get_object() + return Response(snippet.highlighted) +``` As usual we need to add the new views that we've created in to our URLconf. We'll add a url pattern for our new API root in `snippets/urls.py`: - path('', views.api_root), +```python +path("", views.api_root), +``` And then add a url pattern for the snippet highlights: - path('snippets//highlight/', views.SnippetHighlight.as_view()), +```python +path("snippets//highlight/", views.SnippetHighlight.as_view()), +``` ## Hyperlinking our API @@ -73,22 +84,37 @@ The `HyperlinkedModelSerializer` has the following differences from `ModelSerial We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add: - class SnippetSerializer(serializers.HyperlinkedModelSerializer): - owner = serializers.ReadOnlyField(source='owner.username') - highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') +```python +class SnippetSerializer(serializers.HyperlinkedModelSerializer): + owner = serializers.ReadOnlyField(source="owner.username") + highlight = serializers.HyperlinkedIdentityField( + view_name="snippet-highlight", format="html" + ) - class Meta: - model = Snippet - fields = ['url', 'id', 'highlight', 'owner', - 'title', 'code', 'linenos', 'language', 'style'] + class Meta: + model = Snippet + fields = [ + "url", + "id", + "highlight", + "owner", + "title", + "code", + "linenos", + "language", + "style", + ] - class UserSerializer(serializers.HyperlinkedModelSerializer): - snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True) +class UserSerializer(serializers.HyperlinkedModelSerializer): + snippets = serializers.HyperlinkedRelatedField( + many=True, view_name="snippet-detail", read_only=True + ) - class Meta: - model = User - fields = ['url', 'id', 'username', 'snippets'] + class Meta: + model = User + fields = ["url", "id", "username", "snippets"] +``` Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern. @@ -100,11 +126,15 @@ Because we've included format suffixed URLs such as `'.json'`, we also need to i When you are manually instantiating these serializers inside your views (e.g., in `SnippetDetail` or `SnippetList`), you **must** pass `context={'request': request}` so the serializer knows how to build absolute URLs. For example, instead of: - serializer = SnippetSerializer(snippet) +```python +serializer = SnippetSerializer(snippet) +``` You must write: - serializer = SnippetSerializer(snippet, context={'request': request}) +```python +serializer = SnippetSerializer(snippet, context={"request": request}) +``` If your view is a subclass of `GenericAPIView`, you may use the `get_serializer_context()` as a convenience method. @@ -121,29 +151,29 @@ If we're going to have a hyperlinked API, we need to make sure we name our URL p After adding all those names into our URLconf, our final `snippets/urls.py` file should look like this: - from django.urls import path - from rest_framework.urlpatterns import format_suffix_patterns - from snippets import views +```python +from django.urls import path +from rest_framework.urlpatterns import format_suffix_patterns +from snippets import views - # API endpoints - urlpatterns = format_suffix_patterns([ - path('', views.api_root), - path('snippets/', - views.SnippetList.as_view(), - name='snippet-list'), - path('snippets//', - views.SnippetDetail.as_view(), - name='snippet-detail'), - path('snippets//highlight/', +# API endpoints +urlpatterns = format_suffix_patterns( + [ + path("", views.api_root), + path("snippets/", views.SnippetList.as_view(), name="snippet-list"), + path( + "snippets//", views.SnippetDetail.as_view(), name="snippet-detail" + ), + path( + "snippets//highlight/", views.SnippetHighlight.as_view(), - name='snippet-highlight'), - path('users/', - views.UserList.as_view(), - name='user-list'), - path('users//', - views.UserDetail.as_view(), - name='user-detail') - ]) + name="snippet-highlight", + ), + path("users/", views.UserList.as_view(), name="user-list"), + path("users//", views.UserDetail.as_view(), name="user-detail"), + ] +) +``` ## Adding pagination @@ -151,10 +181,12 @@ The list views for users and code snippets could end up returning quite a lot of We can change the default list style to use pagination, by modifying our `tutorial/settings.py` file slightly. Add the following setting: - REST_FRAMEWORK = { - 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', - 'PAGE_SIZE': 10 - } +```python +REST_FRAMEWORK = { + "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", + "PAGE_SIZE": 10, +} +``` Note that settings in REST framework are all namespaced into a single dictionary setting, named `REST_FRAMEWORK`, which helps keep them well separated from your other project settings. diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index 6fa2111e7..2c6760a54 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -12,45 +12,50 @@ Let's take our current set of views, and refactor them into view sets. First of all let's refactor our `UserList` and `UserDetail` classes into a single `UserViewSet` class. In the `snippets/views.py` file, we can remove the two view classes and replace them with a single ViewSet class: - from rest_framework import viewsets +```python +from rest_framework import viewsets - class UserViewSet(viewsets.ReadOnlyModelViewSet): - """ - This viewset automatically provides `list` and `retrieve` actions. - """ - queryset = User.objects.all() - serializer_class = UserSerializer +class UserViewSet(viewsets.ReadOnlyModelViewSet): + """ + This viewset automatically provides `list` and `retrieve` actions. + """ + + queryset = User.objects.all() + serializer_class = UserSerializer +``` Here we've used the `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations. We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes. Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class. - from rest_framework import permissions - from rest_framework import renderers - from rest_framework.decorators import action - from rest_framework.response import Response +```python +from rest_framework import permissions +from rest_framework import renderers +from rest_framework.decorators import action +from rest_framework.response import Response - class SnippetViewSet(viewsets.ModelViewSet): - """ - This ViewSet automatically provides `list`, `create`, `retrieve`, - `update` and `destroy` actions. +class SnippetViewSet(viewsets.ModelViewSet): + """ + This ViewSet automatically provides `list`, `create`, `retrieve`, + `update` and `destroy` actions. - Additionally we also provide an extra `highlight` action. - """ - queryset = Snippet.objects.all() - serializer_class = SnippetSerializer - permission_classes = [permissions.IsAuthenticatedOrReadOnly, - IsOwnerOrReadOnly] + Additionally we also provide an extra `highlight` action. + """ - @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer]) - def highlight(self, request, *args, **kwargs): - snippet = self.get_object() - return Response(snippet.highlighted) + queryset = Snippet.objects.all() + serializer_class = SnippetSerializer + permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] - def perform_create(self, serializer): - serializer.save(owner=self.request.user) + @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer]) + def highlight(self, request, *args, **kwargs): + snippet = self.get_object() + return Response(snippet.highlighted) + + def perform_create(self, serializer): + serializer.save(owner=self.request.user) +``` This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations. @@ -67,42 +72,40 @@ To see what's going on under the hood let's first explicitly create a set of vie In the `snippets/urls.py` file we bind our `ViewSet` classes into a set of concrete views. - from rest_framework import renderers +```python +from rest_framework import renderers - from snippets.views import api_root, SnippetViewSet, UserViewSet +from snippets.views import api_root, SnippetViewSet, UserViewSet - snippet_list = SnippetViewSet.as_view({ - 'get': 'list', - 'post': 'create' - }) - snippet_detail = SnippetViewSet.as_view({ - 'get': 'retrieve', - 'put': 'update', - 'patch': 'partial_update', - 'delete': 'destroy' - }) - snippet_highlight = SnippetViewSet.as_view({ - 'get': 'highlight' - }, renderer_classes=[renderers.StaticHTMLRenderer]) - user_list = UserViewSet.as_view({ - 'get': 'list' - }) - user_detail = UserViewSet.as_view({ - 'get': 'retrieve' - }) +snippet_list = SnippetViewSet.as_view({"get": "list", "post": "create"}) +snippet_detail = SnippetViewSet.as_view( + {"get": "retrieve", "put": "update", "patch": "partial_update", "delete": "destroy"} +) +snippet_highlight = SnippetViewSet.as_view( + {"get": "highlight"}, renderer_classes=[renderers.StaticHTMLRenderer] +) +user_list = UserViewSet.as_view({"get": "list"}) +user_detail = UserViewSet.as_view({"get": "retrieve"}) +``` Notice how we're creating multiple views from each `ViewSet` class, by binding the HTTP methods to the required action for each view. Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual. - urlpatterns = format_suffix_patterns([ - path('', api_root), - path('snippets/', snippet_list, name='snippet-list'), - path('snippets//', snippet_detail, name='snippet-detail'), - path('snippets//highlight/', snippet_highlight, name='snippet-highlight'), - path('users/', user_list, name='user-list'), - path('users//', user_detail, name='user-detail') - ]) +```python +urlpatterns = format_suffix_patterns( + [ + path("", api_root), + path("snippets/", snippet_list, name="snippet-list"), + path("snippets//", snippet_detail, name="snippet-detail"), + path( + "snippets//highlight/", snippet_highlight, name="snippet-highlight" + ), + path("users/", user_list, name="user-list"), + path("users//", user_detail, name="user-detail"), + ] +) +``` ## Using Routers @@ -110,20 +113,22 @@ Because we're using `ViewSet` classes rather than `View` classes, we actually do Here's our re-wired `snippets/urls.py` file. - from django.urls import path, include - from rest_framework.routers import DefaultRouter +```python +from django.urls import path, include +from rest_framework.routers import DefaultRouter - from snippets import views +from snippets import views - # 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') +# 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") - # The API URLs are now determined automatically by the router. - urlpatterns = [ - path('', include(router.urls)), - ] +# The API URLs are now determined automatically by the router. +urlpatterns = [ + path("", include(router.urls)), +] +``` Registering the ViewSets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the view set itself. diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index a140dbce0..f0f6e6c4b 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -6,57 +6,65 @@ We're going to create a simple API to allow admin users to view and edit the use Create a new Django project named `tutorial`, then start a new app called `quickstart`. - # Create the project directory - mkdir tutorial - cd tutorial +```bash +# Create the project directory +mkdir tutorial +cd tutorial - # Create a virtual environment to isolate our package dependencies locally - python3 -m venv env - source env/bin/activate # On Windows use `env\Scripts\activate` +# Create a virtual environment to isolate our package dependencies locally +python3 -m venv env +source env/bin/activate # On Windows use `env\Scripts\activate` - # Install Django and Django REST framework into the virtual environment - pip install djangorestframework +# Install Django and Django REST framework into the virtual environment +pip install djangorestframework - # Set up a new project with a single application - django-admin startproject tutorial . # Note the trailing '.' character - cd tutorial - django-admin startapp quickstart - cd .. +# Set up a new project with a single application +django-admin startproject tutorial . # Note the trailing '.' character +cd tutorial +django-admin startapp quickstart +cd .. +``` The project layout should look like: - $ pwd - /tutorial - $ find . - . - ./tutorial - ./tutorial/asgi.py - ./tutorial/__init__.py - ./tutorial/quickstart - ./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/settings.py - ./tutorial/urls.py - ./tutorial/wsgi.py - ./env - ./env/... - ./manage.py +```bash +$ pwd +/tutorial +$ find . +. +./tutorial +./tutorial/asgi.py +./tutorial/__init__.py +./tutorial/quickstart +./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/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). Now sync your database for the first time: - python manage.py migrate +```bash +python manage.py migrate +``` 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 --username admin --email admin@example.com +```bash +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... @@ -64,20 +72,22 @@ 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 Group, User - from rest_framework import serializers +```python +from django.contrib.auth.models import Group, User +from rest_framework import serializers - class UserSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = User - fields = ['url', 'username', 'email', 'groups'] +class UserSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = User + fields = ["url", "username", "email", "groups"] - class GroupSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = Group - fields = ['url', 'name'] +class GroupSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = Group + fields = ["url", "name"] +``` Notice that we're using hyperlinked relations in this case with `HyperlinkedModelSerializer`. You can also use primary key and various other relationships, but hyperlinking is good RESTful design. @@ -85,28 +95,32 @@ 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 Group, User - from rest_framework import permissions, viewsets +```python +from django.contrib.auth.models import Group, User +from rest_framework import permissions, viewsets - from tutorial.quickstart.serializers import GroupSerializer, UserSerializer +from tutorial.quickstart.serializers import GroupSerializer, UserSerializer - class UserViewSet(viewsets.ModelViewSet): - """ - API endpoint that allows users to be viewed or edited. - """ - queryset = User.objects.all().order_by('-date_joined') - serializer_class = UserSerializer - permission_classes = [permissions.IsAuthenticated] +class UserViewSet(viewsets.ModelViewSet): + """ + API endpoint that allows users to be viewed or edited. + """ + + queryset = User.objects.all().order_by("-date_joined") + serializer_class = UserSerializer + permission_classes = [permissions.IsAuthenticated] - class GroupViewSet(viewsets.ModelViewSet): - """ - API endpoint that allows groups to be viewed or edited. - """ - queryset = Group.objects.all().order_by('name') - serializer_class = GroupSerializer - permission_classes = [permissions.IsAuthenticated] +class GroupViewSet(viewsets.ModelViewSet): + """ + API endpoint that allows groups to be viewed or edited. + """ + + queryset = Group.objects.all().order_by("name") + serializer_class = GroupSerializer + permission_classes = [permissions.IsAuthenticated] +``` Rather than write multiple views we're grouping together all the common behavior into classes called `ViewSets`. @@ -116,21 +130,23 @@ We can easily break these down into individual views if we need to, but using vi 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 +```python +from django.urls import include, path +from rest_framework import routers - from tutorial.quickstart import views +from tutorial.quickstart import views - router = routers.DefaultRouter() - router.register(r'users', views.UserViewSet) - router.register(r'groups', views.GroupViewSet) +router = routers.DefaultRouter() +router.register(r"users", views.UserViewSet) +router.register(r"groups", views.GroupViewSet) - # Wire up our API using automatic URL routing. - # Additionally, we include login URLs for the browsable API. - urlpatterns = [ - path('', include(router.urls)), - path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) - ] +# Wire up our API using automatic URL routing. +# Additionally, we include login URLs for the browsable API. +urlpatterns = [ + path("", include(router.urls)), + path("api-auth/", include("rest_framework.urls", namespace="rest_framework")), +] +``` Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class. @@ -139,21 +155,26 @@ Again, if we need more control over the API URLs we can simply drop down to usin Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API. ## Pagination + Pagination allows you to control how many objects per page are returned. To enable it add the following lines to `tutorial/settings.py` - REST_FRAMEWORK = { - 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', - 'PAGE_SIZE': 10 - } +```python +REST_FRAMEWORK = { + "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", + "PAGE_SIZE": 10, +} +``` ## Settings Add `'rest_framework'` to `INSTALLED_APPS`. The settings module will be in `tutorial/settings.py` - INSTALLED_APPS = [ - ... - 'rest_framework', - ] +```text +INSTALLED_APPS = [ + ... + 'rest_framework', +] +``` Okay, we're done. @@ -163,46 +184,51 @@ Okay, we're done. We're now ready to test the API we've built. Let's fire up the server from the command line. - python manage.py runserver +```bash +python manage.py runserver +``` We can now access our API, both from the command-line, using tools like `curl`... - bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/ - Enter host password for user 'admin': - { - "count": 1, - "next": null, - "previous": null, - "results": [ - { - "url": "http://127.0.0.1:8000/users/1/", - "username": "admin", - "email": "admin@example.com", - "groups": [] - } - ] - } +```bash +bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/ +Enter host password for user 'admin': +{ + "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": [ - { - "email": "admin@example.com", - "groups": [], - "url": "http://127.0.0.1:8000/users/1/", - "username": "admin" - } - ] - } - +```bash +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": [ + { + "email": "admin@example.com", + "groups": [], + "url": "http://127.0.0.1:8000/users/1/", + "username": "admin" + } + ] +} +``` Or directly through the browser, by going to the URL `http://127.0.0.1:8000/users/`... From 577bb3c81973eaa543e3eb47ae3bdd4c4968cc01 Mon Sep 17 00:00:00 2001 From: Genaro Camele Date: Tue, 14 Oct 2025 03:22:23 -0300 Subject: [PATCH 05/19] Validation on ManyToManyField when default=None (#9790) * Added validation on ManyToMany relations when default=None and tests * Some clarifications in contributing.md --- docs/community/contributing.md | 34 +++++++++++++++++++++++++++++++ rest_framework/serializers.py | 7 +++++++ tests/test_serializer.py | 37 +++++++++++++++++++++++++++++++++- 3 files changed, 77 insertions(+), 1 deletion(-) diff --git a/docs/community/contributing.md b/docs/community/contributing.md index aceff45ac..797bf72e3 100644 --- a/docs/community/contributing.md +++ b/docs/community/contributing.md @@ -81,12 +81,45 @@ To run the tests, clone the repository, and then: # Run the tests ./runtests.py +--- + +**Note:** if your tests require access to the database, do not forget to inherit from `django.test.TestCase` or use the `@pytest.mark.django_db()` decorator. + +For example, with TestCase: + + from django.test import TestCase + + class MyDatabaseTest(TestCase): + def test_something(self): + # Your test code here + pass + +Or with decorator: + + import pytest + + @pytest.mark.django_db() + class MyDatabaseTest: + def test_something(self): + # Your test code here + pass + +You can reuse existing models defined in `tests/models.py` for your tests. + +--- + ### Test options Run using a more concise output style. ./runtests.py -q + +If you do not want the output to be captured (for example, to see print statements directly), you can use the `-s` flag. + + ./runtests.py -s + + Run the tests for a given test case. ./runtests.py MyTestCase @@ -99,6 +132,7 @@ Shorter form to run the tests for a given test method. ./runtests.py test_this_method + Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input. ### Running against multiple environments diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 5ca1ad55f..290534300 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -1090,6 +1090,13 @@ class ModelSerializer(Serializer): # Determine the fields that should be included on the serializer. fields = {} + # If it's a ManyToMany field, and the default is None, then raises an exception to prevent exceptions on .set() + for field_name in declared_fields.keys(): + if field_name in info.relations and info.relations[field_name].to_many and declared_fields[field_name].default is None: + raise ValueError( + f"The field '{field_name}' on serializer '{self.__class__.__name__}' is a ManyToMany field and cannot have a default value of None." + ) + for field_name in field_names: # If the field is explicitly declared on the class then use that. if field_name in declared_fields: diff --git a/tests/test_serializer.py b/tests/test_serializer.py index cefa2ee38..ed8a74911 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -6,12 +6,14 @@ from collections.abc import Mapping import pytest from django.db import models +from django.test import TestCase from rest_framework import exceptions, fields, relations, serializers from rest_framework.fields import Field from .models import ( - ForeignKeyTarget, NestedForeignKeySource, NullableForeignKeySource + ForeignKeyTarget, ManyToManySource, ManyToManyTarget, + NestedForeignKeySource, NullableForeignKeySource ) from .utils import MockObject @@ -64,6 +66,7 @@ class TestSerializer: class ExampleSerializer(serializers.Serializer): char = serializers.CharField() integer = serializers.IntegerField() + self.Serializer = ExampleSerializer def test_valid_serializer(self): @@ -774,3 +777,35 @@ class TestSetValueMethod: ret = {'a': 1} self.s.set_value(ret, ['x', 'y'], 2) assert ret == {'a': 1, 'x': {'y': 2}} + + +class TestWarningManyToMany(TestCase): + def test_warning_many_to_many(self): + """Tests that using a PrimaryKeyRelatedField for a ManyToMany field breaks with default=None.""" + class ManyToManySourceSerializer(serializers.ModelSerializer): + targets = serializers.PrimaryKeyRelatedField( + many=True, + queryset=ManyToManyTarget.objects.all(), + default=None + ) + + class Meta: + model = ManyToManySource + fields = '__all__' + + # Instantiates serializer without 'value' field to force using the default=None for the ManyToMany relation + serializer = ManyToManySourceSerializer(data={ + "name": "Invalid Example", + }) + + error_msg = "The field 'targets' on serializer 'ManyToManySourceSerializer' is a ManyToMany field and cannot have a default value of None." + + # Calls to get_fields() should raise a ValueError + with pytest.raises(ValueError) as exc_info: + serializer.get_fields() + assert str(exc_info.value) == error_msg + + # Calls to is_valid() should behave the same + with pytest.raises(ValueError) as exc_info: + serializer.is_valid(raise_exception=True) + assert str(exc_info.value) == error_msg From fb1db15f38ab2768e025394798cf8e7602826738 Mon Sep 17 00:00:00 2001 From: "Julian V." <11302774+TheFunctionalGuy@users.noreply.github.com> Date: Mon, 20 Oct 2025 16:34:21 +0200 Subject: [PATCH 06/19] chore: fix invalid SPDX license expression in __init__.py of rest_framework (#9799) --- 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 413f32606..61e078a95 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -10,7 +10,7 @@ ______ _____ _____ _____ __ __title__ = 'Django REST framework' __version__ = '3.16.1' __author__ = 'Tom Christie' -__license__ = 'BSD 3-Clause' +__license__ = 'BSD-3-Clause' __copyright__ = 'Copyright 2011-2023 Encode OSS Ltd' # Version synonym From f74a44e850a685ac73c819ae7b96b0d68a8f734f Mon Sep 17 00:00:00 2001 From: Mahdi <111646898+mahdighadiriii@users.noreply.github.com> Date: Mon, 20 Oct 2025 19:56:55 +0330 Subject: [PATCH 07/19] Docs: Mention ?page=last in last_page_strings #9193 (#9800) --- docs/api-guide/pagination.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 41887ffd8..e4e5f4979 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -108,7 +108,7 @@ To set these attributes you should override the `PageNumberPagination` class, an * `page_query_param` - A string value indicating the name of the query parameter to use for the pagination control. * `page_size_query_param` - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to `None`, indicating that the client may not control the requested page size. * `max_page_size` - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if `page_size_query_param` is also set. -* `last_page_strings` - A list or tuple of string values indicating values that may be used with the `page_query_param` to request the final page in the set. Defaults to `('last',)` +* `last_page_strings` - A list or tuple of string values indicating values that may be used with the `page_query_param` to request the final page in the set. Defaults to `('last',)`. For example, use `?page=last` to go directly to the last page. * `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`. --- From 653343cf32334a3d6e92872c0a7decdc7d8e9085 Mon Sep 17 00:00:00 2001 From: Pravin <91125540+p-r-a-v-i-n@users.noreply.github.com> Date: Mon, 20 Oct 2025 22:15:11 +0530 Subject: [PATCH 08/19] Add documentation on avoiding N+1 queries using select_related/prefetch_related (#9801) --- docs/api-guide/generic-views.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 70bfa7992..4c81299c5 100644 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -102,6 +102,39 @@ For example: --- +### Avoiding N+1 Queries + +When listing objects (e.g. using `ListAPIView` or `ModelViewSet`), serializers may trigger an N+1 query pattern if related objects are accessed individually for each item. + +To prevent this, optimize the queryset in `get_queryset()` or by setting the `queryset` class attribute using [`select_related()`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#select-related) and [`prefetch_related()`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#prefetch-related), depending on the type of relationship. + +**For ForeignKey and OneToOneField**: + +Use `select_related()` to fetch related objects in the same query: + + def get_queryset(self): + return Order.objects.select_related("customer", "billing_address") + +**For reverse and many-to-many relationships**: + +Use `prefetch_related()` to efficiently load collections of related objects: + + def get_queryset(self): + return Book.objects.prefetch_related("categories", "reviews__user") + +**Combining both**: + + def get_queryset(self): + return ( + Order.objects + .select_related("customer") + .prefetch_related("items__product") + ) + +These optimizations reduce repeated database access and improve list view performance. + +--- + #### `get_object(self)` Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset. From 03f1ecf7f16312082302e91343c281d504d5de39 Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Mon, 20 Oct 2025 19:52:44 +0200 Subject: [PATCH 09/19] Set minimum Python version to 3.10 in pyupgrade pre-commit hook (#9798) * Set min Python version to 3.10 in pyupgrade * Consistent formatting * Update to latest version --- .pre-commit-config.yaml | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a5ea46db1..cfea408e0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -34,13 +34,11 @@ repos: additional_dependencies: # python doesn't come with a toml parser prior to 3.11 - "tomli; python_version < '3.11'" - - repo: https://github.com/asottile/pyupgrade - rev: v3.19.1 + rev: v3.21.0 hooks: - id: pyupgrade - args: ["--py39-plus", "--keep-percent-format"] - + args: ["--py310-plus", "--keep-percent-format"] - repo: https://github.com/tox-dev/pyproject-fmt rev: v2.6.0 hooks: From 5a6f2ae7c92dbc37cd3d37bc67843e4dc570e93e Mon Sep 17 00:00:00 2001 From: Simon Gurcke Date: Tue, 21 Oct 2025 22:50:18 +1000 Subject: [PATCH 10/19] Add Apitally to third-party-packages.md in docs (#9718) --- docs/community/third-party-packages.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/community/third-party-packages.md b/docs/community/third-party-packages.md index a4ad2db1e..5b878e9ee 100644 --- a/docs/community/third-party-packages.md +++ b/docs/community/third-party-packages.md @@ -158,6 +158,7 @@ To submit new content, [create a pull request][drf-create-pr]. * [django-requestlogs] - Providing middleware and other helpers for audit logging for REST framework. * [drf-standardized-errors][drf-standardized-errors] - DRF exception handler to standardize error responses for all API endpoints. * [drf-api-action][drf-api-action] - uses the power of DRF also as a library functions +* [apitally] - A simple API monitoring, analytics, and request logging tool using middleware. For DRF-specific setup guide, [click here](https://docs.apitally.io/frameworks/django-rest-framework). ### Customization @@ -260,4 +261,5 @@ To submit new content, [create a pull request][drf-create-pr]. [drf-redesign]: https://github.com/youzarsiph/drf-redesign [drf-material]: https://github.com/youzarsiph/drf-material [django-pyoidc]: https://github.com/makinacorpus/django_pyoidc +[apitally]: https://github.com/apitally/apitally-py [drf-shapeless-serializers]: https://github.com/khaledsukkar2/drf-shapeless-serializers From 9b3d03a3d257bca3eb99ca82770908adc7486a37 Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Tue, 21 Oct 2025 15:19:47 +0200 Subject: [PATCH 11/19] Update blacken-docs and black to latest versions (#9802) * Update blacken-docs and black to latest versions * Include docs folder for blackend-docs * Run blacken docs on docs folder * Fix broken link on authentication page --- .pre-commit-config.yaml | 5 ++--- README.md | 21 +++++++++++---------- docs/api-guide/authentication.md | 4 ++-- docs/api-guide/viewsets.md | 2 +- docs/community/3.11-announcement.md | 12 ++++-------- 5 files changed, 20 insertions(+), 24 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index cfea408e0..130793f80 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -19,12 +19,11 @@ repos: additional_dependencies: - flake8-tidy-imports - repo: https://github.com/adamchainz/blacken-docs - rev: 1.16.0 + rev: 1.20.0 hooks: - id: blacken-docs - exclude: ^(?!docs).*$ additional_dependencies: - - black==23.1.0 + - black==25.9.0 - repo: https://github.com/codespell-project/codespell # Configuration for codespell is in .codespellrc rev: v2.2.6 diff --git a/README.md b/README.md index b2bada7b4..1594ab0ad 100644 --- a/README.md +++ b/README.md @@ -67,10 +67,11 @@ Install using `pip`... pip install djangorestframework Add `'rest_framework'` to your `INSTALLED_APPS` setting. + ```python INSTALLED_APPS = [ - ... - 'rest_framework', + # ... + "rest_framework", ] ``` @@ -99,7 +100,7 @@ from rest_framework import routers, serializers, viewsets class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User - fields = ['url', 'username', 'email', 'is_staff'] + fields = ["url", "username", "email", "is_staff"] # ViewSets define the view behavior. @@ -110,13 +111,13 @@ class UserViewSet(viewsets.ModelViewSet): # Routers provide a way of automatically determining the URL conf. router = routers.DefaultRouter() -router.register(r'users', UserViewSet) +router.register(r"users", UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ - path('', include(router.urls)), - path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), + path("", include(router.urls)), + path("api-auth/", include("rest_framework.urls", namespace="rest_framework")), ] ``` @@ -126,15 +127,15 @@ Add the following to your `settings.py` module: ```python INSTALLED_APPS = [ - ... # Make sure to include the default installed apps here. - 'rest_framework', + # ... make sure to include the default installed apps here. + "rest_framework", ] REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. - 'DEFAULT_PERMISSION_CLASSES': [ - 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', + "DEFAULT_PERMISSION_CLASSES": [ + "rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly", ] } ``` diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 84e58bf4b..073ddc8f0 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -454,7 +454,7 @@ There are currently two forks of this project. More information can be found in the [Documentation](https://django-rest-durin.readthedocs.io/en/latest/index.html). -## django-pyoidc +## django-pyoidc [dango-pyoidc][django_pyoidc] adds support for OpenID Connect (OIDC) authentication. This allows you to delegate user management to an Identity Provider, which can be used to implement Single-Sign-On (SSO). It provides support for most uses-cases, such as customizing how token info are mapped to user models, using OIDC audiences for access control, etc. @@ -497,4 +497,4 @@ More information can be found in the [Documentation](https://django-pyoidc.readt [django-rest-authemail]: https://github.com/celiao/django-rest-authemail [django-rest-durin]: https://github.com/eshaan7/django-rest-durin [login-required-middleware]: https://docs.djangoproject.com/en/stable/ref/middleware/#django.contrib.auth.middleware.LoginRequiredMiddleware -[django-pyoidc] : https://github.com/makinacorpus/django_pyoidc +[django-pyoidc]: https://github.com/makinacorpus/django_pyoidc diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 22acfe327..102bac40e 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -231,7 +231,7 @@ Using the example from the previous section: Alternatively, you can use the `url_name` attribute set by the `@action` decorator. ```pycon ->>> view.reverse_action(view.set_password.url_name, args=['1']) +>>> view.reverse_action(view.set_password.url_name, args=["1"]) 'http://localhost:8000/api/users/1/set_password' ``` diff --git a/docs/community/3.11-announcement.md b/docs/community/3.11-announcement.md index 2fc37a764..e913d5e0a 100644 --- a/docs/community/3.11-announcement.md +++ b/docs/community/3.11-announcement.md @@ -50,11 +50,9 @@ class DocStringExampleListView(APIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] - def get(self, request, *args, **kwargs): - ... + def get(self, request, *args, **kwargs): ... - def post(self, request, *args, **kwargs): - ... + def post(self, request, *args, **kwargs): ... ``` ## Validator / Default Context @@ -76,8 +74,7 @@ Validator implementations will look like this: class CustomValidator: requires_context = True - def __call__(self, value, serializer_field): - ... + def __call__(self, value, serializer_field): ... ``` Default implementations will look like this: @@ -86,8 +83,7 @@ Default implementations will look like this: class CustomDefault: requires_context = True - def __call__(self, serializer_field): - ... + def __call__(self, serializer_field): ... ``` --- From e045dc465270c18689dba4a970378cd9744e57b6 Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Wed, 22 Oct 2025 14:47:00 +0200 Subject: [PATCH 12/19] Update pre-commit hooks (#9805) * Auto-update pre-commit hooks * Supress new flake8 error * Fix codespell --- .pre-commit-config.yaml | 12 ++++++------ docs/api-guide/metadata.md | 2 +- docs/api-guide/testing.md | 2 +- docs/api-guide/validators.md | 2 +- tests/test_lazy_hyperlinks.py | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 130793f80..28686275a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.5.0 + rev: v6.0.0 hooks: - id: check-added-large-files - id: check-case-conflict @@ -8,12 +8,12 @@ repos: - id: check-merge-conflict - id: check-symlinks - id: check-toml -- repo: https://github.com/pycqa/isort - rev: 5.13.2 +- repo: https://github.com/PyCQA/isort + rev: 7.0.0 hooks: - id: isort - repo: https://github.com/PyCQA/flake8 - rev: 7.0.0 + rev: 7.3.0 hooks: - id: flake8 additional_dependencies: @@ -26,7 +26,7 @@ repos: - black==25.9.0 - repo: https://github.com/codespell-project/codespell # Configuration for codespell is in .codespellrc - rev: v2.2.6 + rev: v2.4.1 hooks: - id: codespell exclude: locale|kickstarter-announcement.md|coreapi-0.1.1.js @@ -39,6 +39,6 @@ repos: - id: pyupgrade args: ["--py310-plus", "--keep-percent-format"] - repo: https://github.com/tox-dev/pyproject-fmt - rev: v2.6.0 + rev: v2.11.0 hooks: - id: pyproject-fmt diff --git a/docs/api-guide/metadata.md b/docs/api-guide/metadata.md index 20708c6e3..f4e8ed2da 100644 --- a/docs/api-guide/metadata.md +++ b/docs/api-guide/metadata.md @@ -66,7 +66,7 @@ The REST framework package only includes a single metadata class implementation, ## Creating schema endpoints -If you have specific requirements for creating schema endpoints that are accessed with regular `GET` requests, you might consider re-using the metadata API for doing so. +If you have specific requirements for creating schema endpoints that are accessed with regular `GET` requests, you might consider reusing the metadata API for doing so. For example, the following additional route could be used on a viewset to provide a linkable schema endpoint. diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index 97b432ddd..a84379eef 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -92,7 +92,7 @@ For example, when forcibly authenticating using a token, you might do something --- -**Note**: `force_authenticate` directly sets `request.user` to the in-memory `user` instance. If you are re-using the same `user` instance across multiple tests that update the saved `user` state, you may need to call [`refresh_from_db()`][refresh_from_db_docs] between tests. +**Note**: `force_authenticate` directly sets `request.user` to the in-memory `user` instance. If you are reusing the same `user` instance across multiple tests that update the saved `user` state, you may need to call [`refresh_from_db()`][refresh_from_db_docs] between tests. --- diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index e3407e8a3..3a122a3c6 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -5,7 +5,7 @@ source: # Validators -> Validators can be useful for re-using validation logic between different types of fields. +> Validators can be useful for reusing validation logic between different types of fields. > > — [Django documentation][cite] diff --git a/tests/test_lazy_hyperlinks.py b/tests/test_lazy_hyperlinks.py index 716d02d2a..db1de3567 100644 --- a/tests/test_lazy_hyperlinks.py +++ b/tests/test_lazy_hyperlinks.py @@ -39,7 +39,7 @@ class TestLazyHyperlinkNames(TestCase): self.example = Example.objects.create(text='foo') def test_lazy_hyperlink_names(self): - global str_called + global str_called # noqa: F824 context = {'request': None} serializer = ExampleSerializer(self.example, context=context) JSONRenderer().render(serializer.data) From 2ca3b7f9c449145156f0b0e2d9ea58a2295f8fbf Mon Sep 17 00:00:00 2001 From: JAEGYUN JUNG Date: Tue, 28 Oct 2025 01:37:27 +0900 Subject: [PATCH 13/19] Remove Transifex mentions from documentation (#9572) Co-authored-by: Bruno Alla --- docs/community/project-management.md | 58 ---------------------------- docs/topics/internationalization.md | 7 ++-- 2 files changed, 4 insertions(+), 61 deletions(-) diff --git a/docs/community/project-management.md b/docs/community/project-management.md index 4c0c93f31..5c7577ec8 100644 --- a/docs/community/project-management.md +++ b/docs/community/project-management.md @@ -51,11 +51,6 @@ The following template should be used for the description of the issue, and serv Release manager is @***. Pull request is #***. - During development cycle: - - - [ ] Upload the new content to be translated to [transifex](https://www.django-rest-framework.org/topics/project-management/#translations). - - Checklist: - [ ] Create pull request for [release notes](https://github.com/encode/django-rest-framework/blob/mains/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/encode/django-rest-framework/milestones/***). @@ -64,7 +59,6 @@ The following template should be used for the description of the issue, and serv - [ ] `pyproject.toml` Python & Django version trove classifiers - [ ] `README` Python & Django versions - [ ] `docs` Python & Django versions - - [ ] Update the translations from [transifex](https://www.django-rest-framework.org/topics/project-management/#translations). - [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/main/rest_framework/__init__.py). - [ ] Ensure documentation validates - Build and serve docs `mkdocs serve` @@ -87,55 +81,6 @@ When pushing the release to PyPI ensure that your environment has been installed --- -## Translations - -The maintenance team are responsible for managing the translation packs include in REST framework. Translating the source strings into multiple languages is managed through the [transifex service][transifex-project]. - -### Managing Transifex - -The [official Transifex client][transifex-client] is used to upload and download translations to Transifex. The client is installed using pip: - - pip install transifex-client - -To use it you'll need a login to Transifex which has a password, and you'll need to have administrative access to the Transifex project. You'll need to create a `~/.transifexrc` file which contains your credentials. - - [https://www.transifex.com] - username = *** - token = *** - password = *** - hostname = https://www.transifex.com - -### Upload new source files - -When any user visible strings are changed, they should be uploaded to Transifex so that the translators can start to translate them. To do this, just run: - - # 1. Update the source django.po file, which is the US English version. - cd rest_framework - django-admin makemessages -l en_US - # 2. Push the source django.po file to Transifex. - cd .. - tx push -s - -When pushing source files, Transifex will update the source strings of a resource to match those from the new source file. - -Here's how differences between the old and new source files will be handled: - -* New strings will be added. -* Modified strings will be added as well. -* Strings which do not exist in the new source file will be removed from the database, along with their translations. If that source strings gets re-added later then [Transifex Translation Memory][translation-memory] will automatically include the translation string. - -### Download translations - -When a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run: - - # 3. Pull the translated django.po files from Transifex. - tx pull -a --minimum-perc 10 - cd rest_framework - # 4. Compile the binary .mo files for all supported languages. - django-admin compilemessages - ---- - ## Project requirements All our test requirements are pinned to exact versions, in order to ensure that our test runs are reproducible. We maintain the requirements in the `requirements` directory. The requirements files are referenced from the `tox.ini` configuration file, ensuring we have a single source of truth for package versions used in testing. @@ -160,7 +105,4 @@ The following issues still need to be addressed: [bus-factor]: https://en.wikipedia.org/wiki/Bus_factor [un-triaged]: https://github.com/encode/django-rest-framework/issues?q=is%3Aopen+no%3Alabel -[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/ -[transifex-client]: https://pypi.org/project/transifex-client/ -[translation-memory]: http://docs.transifex.com/guides/tm#let-tm-automatically-populate-translations [mailing-list]: https://groups.google.com/forum/#!forum/django-rest-framework diff --git a/docs/topics/internationalization.md b/docs/topics/internationalization.md index b7387f772..5f4b719b5 100644 --- a/docs/topics/internationalization.md +++ b/docs/topics/internationalization.md @@ -60,11 +60,12 @@ If you only wish to support a subset of the available languages, use Django's st ## Adding new translations -REST framework translations are managed online using [Transifex][transifex-project]. You can use the Transifex service to add new translation languages. The maintenance team will then ensure that these translation strings are included in the REST framework package. +REST framework translations are managed on GitHub. You can contribute new translation languages or update existing ones +by following the guidelines in the [Contributing to REST Framework] section and submitting a pull request. Sometimes you may need to add translation strings to your project locally. You may need to do this if: -* You want to use REST Framework in a language which has not been translated yet on Transifex. +* You want to use REST Framework in a language which is not supported by the project. * Your project includes custom error messages, which are not part of REST framework's default translation strings. #### Translating a new language locally @@ -103,9 +104,9 @@ You can find more information on how the language preference is determined in th For API clients the most appropriate of these will typically be to use the `Accept-Language` header; Sessions and cookies will not be available unless using session authentication, and generally better practice to prefer an `Accept-Language` header for API clients rather than using language URL prefixes. [cite]: https://youtu.be/Wa0VfS2q94Y +[Contributing to REST Framework]: ../community/contributing.md#development [django-translation]: https://docs.djangoproject.com/en/stable/topics/i18n/translation [custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling -[transifex-project]: https://explore.transifex.com/django-rest-framework-1/django-rest-framework/ [django-po-source]: https://raw.githubusercontent.com/encode/django-rest-framework/main/rest_framework/locale/en_US/LC_MESSAGES/django.po [django-language-preference]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#how-django-discovers-language-preference [django-locale-paths]: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-LOCALE_PATHS From 0653a63e6db88b16821e65b51c274d116972b1aa Mon Sep 17 00:00:00 2001 From: Huy Nguyen <49433085+huynguyengl99@users.noreply.github.com> Date: Mon, 27 Oct 2025 23:38:04 +0700 Subject: [PATCH 14/19] Add drf-auth-kit to Third Party Authentication Packages (#9785) Co-authored-by: Bruno Alla --- docs/api-guide/authentication.md | 6 ++++++ docs/community/third-party-packages.md | 2 ++ 2 files changed, 8 insertions(+) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 073ddc8f0..2f4d42959 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -426,6 +426,11 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a [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. +## DRF Auth Kit + +[DRF Auth Kit][drf-auth-kit] library provides a modern REST authentication solution with JWT cookies, social login, multi-factor authentication, and comprehensive user management. The package offers full type safety, automatic OpenAPI schema generation with DRF Spectacular. It supports multiple authentication types (JWT, DRF Token, or Custom) and includes built-in internationalization for 50+ languages. + + ## django-rest-auth / dj-rest-auth This library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management. @@ -498,3 +503,4 @@ More information can be found in the [Documentation](https://django-pyoidc.readt [django-rest-durin]: https://github.com/eshaan7/django-rest-durin [login-required-middleware]: https://docs.djangoproject.com/en/stable/ref/middleware/#django.contrib.auth.middleware.LoginRequiredMiddleware [django-pyoidc]: https://github.com/makinacorpus/django_pyoidc +[drf-auth-kit]: https://github.com/huynguyengl99/drf-auth-kit diff --git a/docs/community/third-party-packages.md b/docs/community/third-party-packages.md index 5b878e9ee..70f4f3e51 100644 --- a/docs/community/third-party-packages.md +++ b/docs/community/third-party-packages.md @@ -58,6 +58,7 @@ To submit new content, [create a pull request][drf-create-pr]. * [hawkrest][hawkrest] - Provides Hawk HTTP Authorization. * [djangorestframework-httpsignature][djangorestframework-httpsignature] - Provides an easy to use HTTP Signature Authentication mechanism. * [djoser][djoser] - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. +* [DRF Auth Kit][drf-auth-kit] - Provides complete REST authentication with JWT cookies, social login, MFA, and user management. Features full type safety and automatic OpenAPI schema generation. * [dj-rest-auth][dj-rest-auth] - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. * [drf-oidc-auth][drf-oidc-auth] - Implements OpenID Connect token authentication for DRF. * [drfpasswordless][drfpasswordless] - Adds (Medium, Square Cash inspired) passwordless logins and signups via email and mobile numbers. @@ -181,6 +182,7 @@ To submit new content, [create a pull request][drf-create-pr]. [permissions]: ../api-guide/permissions.md [third-party-packages]: #existing-third-party-packages [discussion-group]: https://groups.google.com/forum/#!forum/django-rest-framework +[drf-auth-kit]: https://github.com/huynguyengl99/drf-auth-kit [djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth [django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit [djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt From ade172e1d5db87dc86bc616cbb4df7ccd2eb2fd3 Mon Sep 17 00:00:00 2001 From: Pravin <91125540+p-r-a-v-i-n@users.noreply.github.com> Date: Mon, 27 Oct 2025 22:14:48 +0530 Subject: [PATCH 15/19] Standardize spelling to American English in documentation (#9804) * Standardize spelling to American English (only in .md files) * Update remaining British english spell words to American english style * Configures the codespell pre-commit hook to enforce US English consistency changes: - Activates the `en-GB_to_en-US` built-in dictionary to flag British spellings - Created codespell-ignore-words.txt file to ignore specific words - include `code` and `names` for comprehensive typo checking in technical contexts. - changed the 'lets' to 'let's'. --- .pre-commit-config.yaml | 5 ++++ codespell-ignore-words.txt | 6 ++++ docs/api-guide/authentication.md | 2 +- docs/api-guide/fields.md | 4 +-- docs/api-guide/relations.md | 6 ++-- docs/api-guide/renderers.md | 2 +- docs/api-guide/responses.md | 2 +- docs/api-guide/schemas.md | 2 +- docs/api-guide/serializers.md | 8 ++--- docs/api-guide/testing.md | 10 +++---- docs/api-guide/validators.md | 2 +- docs/community/3.0-announcement.md | 2 +- docs/community/3.12-announcement.md | 4 +-- docs/community/3.13-announcement.md | 2 +- docs/community/3.15-announcement.md | 4 +-- docs/community/3.16-announcement.md | 4 +-- docs/community/3.4-announcement.md | 2 +- docs/community/3.5-announcement.md | 16 +++++----- docs/community/3.7-announcement.md | 2 +- docs/community/3.8-announcement.md | 4 +-- docs/community/3.9-announcement.md | 2 +- docs/community/release-notes.md | 30 +++++++++---------- docs/index.md | 2 +- docs/topics/browsable-api.md | 2 +- docs/topics/rest-hypermedia-hateoas.md | 2 +- rest_framework/generics.py | 2 +- rest_framework/mixins.py | 2 +- rest_framework/schemas/coreapi.py | 4 +-- rest_framework/schemas/openapi.py | 2 +- rest_framework/serializers.py | 2 +- tests/browsable_api/test_browsable_api.py | 4 +-- .../test_browsable_nested_api.py | 2 +- tests/test_fields.py | 2 +- tests/test_serializer_lists.py | 6 ++-- 34 files changed, 82 insertions(+), 71 deletions(-) create mode 100644 codespell-ignore-words.txt diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 28686275a..244d670b8 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -29,6 +29,11 @@ repos: rev: v2.4.1 hooks: - id: codespell + args: [ + "--builtin", "clear,rare,code,names,en-GB_to_en-US", + "--ignore-words", "codespell-ignore-words.txt", + "--skip", "*.css", + ] exclude: locale|kickstarter-announcement.md|coreapi-0.1.1.js additional_dependencies: # python doesn't come with a toml parser prior to 3.11 diff --git a/codespell-ignore-words.txt b/codespell-ignore-words.txt new file mode 100644 index 000000000..7670fb785 --- /dev/null +++ b/codespell-ignore-words.txt @@ -0,0 +1,6 @@ +Tim +assertIn +IAM +endcode +deque +thead \ No newline at end of file diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 2f4d42959..f41481310 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -416,7 +416,7 @@ JSON Web Token is a fairly new standard which can be used for token-based authen ## Hawk HTTP Authentication -The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let you work with [Hawk][hawk] signed requests and responses in your API. [Hawk][hawk] lets two parties securely communicate with each other using messages signed by a shared key. It is based on [HTTP MAC access authentication][mac] (which was based on parts of [OAuth 1.0][oauth-1.0a]). +The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let you work with [Hawk][hawk] signed requests and responses in your API. [Hawk][hawk] let's two parties securely communicate with each other using messages signed by a shared key. It is based on [HTTP MAC access authentication][mac] (which was based on parts of [OAuth 1.0][oauth-1.0a]). ## HTTP Signature Authentication diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 8278e2a2f..c5682c179 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -180,7 +180,7 @@ The `allow_null` option is also available for string fields, although its usage ## EmailField -A text representation, validates the text to be a valid e-mail address. +A text representation, validates the text to be a valid email address. Corresponds to `django.db.models.fields.EmailField` @@ -762,7 +762,7 @@ suitable for updating our target object. With `source='*'`, the return from ('y_coordinate', 4), ('x_coordinate', 3)]) -For completeness lets do the same thing again but with the nested serializer +For completeness let's do the same thing again but with the nested serializer approach suggested above: class NestedCoordinateSerializer(serializers.Serializer): diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 7c4eece4b..b6d9918b0 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -300,7 +300,7 @@ For example, the following serializer: Would serialize to a nested representation like this: - >>> album = Album.objects.create(album_name="The Grey Album", artist='Danger Mouse') + >>> album = Album.objects.create(album_name="The Gray Album", artist='Danger Mouse') >>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245) >>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264) @@ -310,7 +310,7 @@ Would serialize to a nested representation like this: >>> serializer = AlbumSerializer(instance=album) >>> serializer.data { - 'album_name': 'The Grey Album', + 'album_name': 'The Gray Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, @@ -344,7 +344,7 @@ By default nested serializers are read-only. If you want to support write-operat return album >>> data = { - 'album_name': 'The Grey Album', + 'album_name': 'The Gray Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 7a6bd39f4..2801c53da 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -134,7 +134,7 @@ An example of a view that uses `TemplateHTMLRenderer`: You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint. -If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers. +If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritized first even for browsers that send poorly formed `ACCEPT:` headers. See the [_HTML & Forms_ Topic Page][html-and-forms] for further examples of `TemplateHTMLRenderer` usage. diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md index dbdc8ff2c..00fe95196 100644 --- a/docs/api-guide/responses.md +++ b/docs/api-guide/responses.md @@ -11,7 +11,7 @@ source: REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request. -The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` objects are initialised with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content. +The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` objects are initialized with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content. There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` or `StreamingHttpResponse` objects from your views if required. Using the `Response` class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats. diff --git a/docs/api-guide/schemas.md b/docs/api-guide/schemas.md index c74d00cb7..5208929a6 100644 --- a/docs/api-guide/schemas.md +++ b/docs/api-guide/schemas.md @@ -20,7 +20,7 @@ package and then subsequently retired over the next releases. As a full-fledged replacement, we recommend the [drf-spectacular] package. It has extensive support for generating OpenAPI 3 schemas from -REST framework APIs, with both automatic and customisable options available. +REST framework APIs, with both automatic and customizable options available. For further information please refer to [Documenting your API](../topics/documenting-your-api.md#drf-spectacular). diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 3ce8f887f..e73257381 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -48,7 +48,7 @@ We can now use `CommentSerializer` to serialize a comment, or list of comments. serializer.data # {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'} -At this point we've translated the model instance into Python native datatypes. To finalise the serialization process we render the data into `json`. +At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`. from rest_framework.renderers import JSONRenderer @@ -155,7 +155,7 @@ When deserializing data, you always need to call `is_valid()` before attempting serializer.is_valid() # False serializer.errors - # {'email': ['Enter a valid e-mail address.'], 'created': ['This field is required.']} + # {'email': ['Enter a valid email address.'], 'created': ['This field is required.']} Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The `non_field_errors` key may also be present, and will list any general validation errors. The name of the `non_field_errors` key may be customized using the `NON_FIELD_ERRORS_KEY` REST framework setting. @@ -298,7 +298,7 @@ When dealing with nested representations that support deserializing the data, an serializer.is_valid() # False serializer.errors - # {'user': {'email': ['Enter a valid e-mail address.']}, 'created': ['This field is required.']} + # {'user': {'email': ['Enter a valid email address.']}, 'created': ['This field is required.']} Similarly, the `.validated_data` property will include nested data structures. @@ -430,7 +430,7 @@ The context dictionary can be used within any serializer field logic, such as a Often you'll want serializer classes that map closely to Django model definitions. -The `ModelSerializer` class provides a shortcut that lets you automatically create a `Serializer` class with fields that correspond to the Model fields. +The `ModelSerializer` class provides a shortcut that let's you automatically create a `Serializer` class with fields that correspond to the Model fields. **The `ModelSerializer` class is the same as a regular `Serializer` class, except that**: diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index a84379eef..13019737c 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -264,7 +264,7 @@ For example... csrftoken = response.cookies['csrftoken'] # Interact with the API. - response = client.post('http://testserver/organisations/', json={ + response = client.post('http://testserver/organizations/', json={ 'name': 'MegaCorp', 'status': 'active' }, headers={'X-CSRFToken': csrftoken}) @@ -292,12 +292,12 @@ The CoreAPIClient allows you to interact with your API using the Python client = CoreAPIClient() schema = client.get('http://testserver/schema/') - # Create a new organisation + # Create a new organization params = {'name': 'MegaCorp', 'status': 'active'} - client.action(schema, ['organisations', 'create'], params) + client.action(schema, ['organizations', 'create'], params) - # Ensure that the organisation exists in the listing - data = client.action(schema, ['organisations', 'list']) + # Ensure that the organization exists in the listing + data = client.action(schema, ['organizations', 'list']) assert(len(data) == 1) assert(data == [{'name': 'MegaCorp', 'status': 'active'}]) diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index 3a122a3c6..a0ceaf12d 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -175,7 +175,7 @@ If you want the date field to be entirely hidden from the user, then use `Hidden Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that *is* available as input to the validator. For this purposes use `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation. -**Note:** Using a `read_only=True` field is excluded from writable fields so it won't use a `default=…` argument. Look [3.8 announcement](https://www.django-rest-framework.org/community/3.8-announcement/#altered-the-behaviour-of-read_only-plus-default-on-field). +**Note:** Using a `read_only=True` field is excluded from writable fields so it won't use a `default=…` argument. Look [3.8 announcement](https://www.django-rest-framework.org/community/3.8-announcement/#altered-the-behavior-of-read_only-plus-default-on-field). REST framework includes a couple of defaults that may be useful in this context. diff --git a/docs/community/3.0-announcement.md b/docs/community/3.0-announcement.md index cec61f337..52acd10e2 100644 --- a/docs/community/3.0-announcement.md +++ b/docs/community/3.0-announcement.md @@ -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 behavior 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 customize the behavior in a way that did not simply lookup the field value from the object. For example... def field_to_native(self, obj, field_name): """A custom read-only field that returns the class name.""" diff --git a/docs/community/3.12-announcement.md b/docs/community/3.12-announcement.md index b192f7290..5264ddd85 100644 --- a/docs/community/3.12-announcement.md +++ b/docs/community/3.12-announcement.md @@ -50,7 +50,7 @@ See [the schema documentation](https://www.django-rest-framework.org/api-guide/s ## Customizing the operation ID. REST framework automatically determines operation IDs to use in OpenAPI -schemas. The latest version provides more control for overriding the behaviour +schemas. The latest version provides more control for overriding the behavior used to generate the operation IDs. See [the schema documentation](https://www.django-rest-framework.org/api-guide/schemas/#operationid) for more information. @@ -96,7 +96,7 @@ for details on using custom `AutoSchema` subclasses. ## Support for JSONField. Django 3.1 deprecated the existing `django.contrib.postgres.fields.JSONField` -in favour of a new database-agnositic `JSONField`. +in favor of a new database-agnositic `JSONField`. REST framework 3.12 now supports this new model field, and `ModelSerializer` classes will correctly map the model field. diff --git a/docs/community/3.13-announcement.md b/docs/community/3.13-announcement.md index e2c1fefa6..10d31b764 100644 --- a/docs/community/3.13-announcement.md +++ b/docs/community/3.13-announcement.md @@ -50,6 +50,6 @@ They must now use the more explicit keyword argument style... aliases = serializers.ListField(child=serializers.CharField()) ``` -This change has been made because using positional arguments here *does not* result in the expected behaviour. +This change has been made because using positional arguments here *does not* result in the expected behavior. See Pull Request [#7632](https://github.com/encode/django-rest-framework/pull/7632) for more details. diff --git a/docs/community/3.15-announcement.md b/docs/community/3.15-announcement.md index 848d534b2..fbe0c759b 100644 --- a/docs/community/3.15-announcement.md +++ b/docs/community/3.15-announcement.md @@ -39,12 +39,12 @@ By default the URLs created by `SimpleRouter` use regular expressions. This beha Dependency on pytz has been removed and deprecation warnings have been added, Django will provide ZoneInfo instances as long as USE_DEPRECATED_PYTZ is not enabled. More info on the migration can be found [in this guide](https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html). -## Align `SearchFilter` behaviour to `django.contrib.admin` search +## Align `SearchFilter` behavior to `django.contrib.admin` search Searches now may contain _quoted phrases_ with spaces, each phrase is considered as a single search term, and it will raise a validation error if any null-character is provided in search. See the [Filtering API guide](../api-guide/filtering.md) for more information. ## Other fixes and improvements -There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behaviour. +There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behavior. See the [release notes](release-notes.md) page for a complete listing. diff --git a/docs/community/3.16-announcement.md b/docs/community/3.16-announcement.md index b8f460ae7..97e102c09 100644 --- a/docs/community/3.16-announcement.md +++ b/docs/community/3.16-announcement.md @@ -29,7 +29,7 @@ The current minimum versions of Django is now 4.2 and Python 3.9. ## Django LoginRequiredMiddleware -The new `LoginRequiredMiddleware` introduced by Django 5.1 can now be used alongside Django REST Framework, however it is not honored for API views as an equivalent behaviour can be configured via `DEFAULT_AUTHENTICATION_CLASSES`. See [our dedicated section](../api-guide/authentication.md#django-51-loginrequiredmiddleware) in the docs for more information. +The new `LoginRequiredMiddleware` introduced by Django 5.1 can now be used alongside Django REST Framework, however it is not honored for API views as an equivalent behavior can be configured via `DEFAULT_AUTHENTICATION_CLASSES`. See [our dedicated section](../api-guide/authentication.md#django-51-loginrequiredmiddleware) in the docs for more information. ## Improved support for UniqueConstraint @@ -37,6 +37,6 @@ The generation of validators for [UniqueConstraint](https://docs.djangoproject.c ## Other fixes and improvements -There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behaviour. +There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behavior. See the [release notes](release-notes.md) page for a complete listing. diff --git a/docs/community/3.4-announcement.md b/docs/community/3.4-announcement.md index 03ef6fc41..2c68b178a 100644 --- a/docs/community/3.4-announcement.md +++ b/docs/community/3.4-announcement.md @@ -157,7 +157,7 @@ will result in a list of the available choices being returned in the response. In cases where there is a relational field, the previous behavior would be to return a list of available instances to choose from for that relational field. -In order to minimise exposed information the behavior now is to *not* return +In order to minimize exposed information the behavior now is to *not* return choices information for relational fields. If you want to override this new behavior you'll need to [implement a custom diff --git a/docs/community/3.5-announcement.md b/docs/community/3.5-announcement.md index de558fead..eb3bf7fd5 100644 --- a/docs/community/3.5-announcement.md +++ b/docs/community/3.5-announcement.md @@ -81,7 +81,7 @@ a dynamic client library to interact with your API. Finally, we're also now exposing the schema generation as a [publicly documented API][schema-generation-api], allowing you to more easily -override the behaviour. +override the behavior. ## Requests test client @@ -106,12 +106,12 @@ client library. client = CoreAPIClient() schema = client.get('http://testserver/schema/') - # Create a new organisation + # Create a new organization params = {'name': 'MegaCorp', 'status': 'active'} - client.action(schema, ['organisations', 'create'], params) + client.action(schema, ['organizations', 'create'], params) - # Ensure that the organisation exists in the listing - data = client.action(schema, ['organisations', 'list']) + # Ensure that the organization exists in the listing + data = client.action(schema, ['organizations', 'list']) assert(len(data) == 1) assert(data == [{'name': 'MegaCorp', 'status': 'active'}]) @@ -204,10 +204,10 @@ The `'pk'` identifier in schema paths is now mapped onto the actually model fiel name by default. This will typically be `'id'`. This gives a better external representation for schemas, with less implementation -detail being exposed. It also reflects the behaviour of using a ModelSerializer +detail being exposed. It also reflects the behavior of using a ModelSerializer class with `fields = '__all__'`. -You can revert to the previous behaviour by setting `'SCHEMA_COERCE_PATH_PK': False` +You can revert to the previous behavior by setting `'SCHEMA_COERCE_PATH_PK': False` in the REST framework settings. ### Schema action name representations @@ -215,7 +215,7 @@ in the REST framework settings. The internal `retrieve()` and `destroy()` method names are now coerced to an external representation of `read` and `delete`. -You can revert to the previous behaviour by setting `'SCHEMA_COERCE_METHOD_NAMES': {}` +You can revert to the previous behavior by setting `'SCHEMA_COERCE_METHOD_NAMES': {}` in the REST framework settings. ### DjangoFilterBackend diff --git a/docs/community/3.7-announcement.md b/docs/community/3.7-announcement.md index d1a39fa60..49f68ead2 100644 --- a/docs/community/3.7-announcement.md +++ b/docs/community/3.7-announcement.md @@ -53,7 +53,7 @@ In order to try to address this we're now adding the ability for per-view custom Let's take a quick look at using the new functionality... -The `APIView` class has a `schema` attribute, that is used to control how the Schema for that particular view is generated. The default behaviour is to use the `AutoSchema` class. +The `APIView` class has a `schema` attribute, that is used to control how the Schema for that particular view is generated. The default behavior is to use the `AutoSchema` class. from rest_framework.views import APIView from rest_framework.schemas import AutoSchema diff --git a/docs/community/3.8-announcement.md b/docs/community/3.8-announcement.md index f33b220fd..eef3ae0c9 100644 --- a/docs/community/3.8-announcement.md +++ b/docs/community/3.8-announcement.md @@ -36,7 +36,7 @@ If you use REST framework commercially and would like to see this work continue, ## Breaking Changes -### Altered the behaviour of `read_only` plus `default` on Field. +### Altered the behavior of `read_only` plus `default` on Field. [#5886][gh5886] `read_only` fields will now **always** be excluded from writable fields. @@ -44,7 +44,7 @@ Previously `read_only` fields when combined with a `default` value would use the operations. This was counter-intuitive in some circumstances and led to difficulties supporting dotted `source` attributes on nullable relations. -In order to maintain the old behaviour you may need to pass the value of `read_only` fields when calling `save()` in +In order to maintain the old behavior you may need to pass the value of `read_only` fields when calling `save()` in the view: def perform_create(self, serializer): diff --git a/docs/community/3.9-announcement.md b/docs/community/3.9-announcement.md index 6bc5e3cc3..bd886482c 100644 --- a/docs/community/3.9-announcement.md +++ b/docs/community/3.9-announcement.md @@ -152,7 +152,7 @@ See [#5990][gh5990]. ### `action` decorator replaces `list_route` and `detail_route` -Both `list_route` and `detail_route` are now deprecated in favour of the single `action` decorator. +Both `list_route` and `detail_route` are now deprecated in favor of the single `action` decorator. They will be removed entirely in 3.10. The `action` decorator takes a boolean `detail` argument. diff --git a/docs/community/release-notes.md b/docs/community/release-notes.md index ae59ae000..86cab8e2b 100644 --- a/docs/community/release-notes.md +++ b/docs/community/release-notes.md @@ -105,7 +105,7 @@ This release fixes a few bugs, clean-up some old code paths for unsupported Pyth **Date**: 28th March 2025 -This release is considered a significant release to improve upstream support with Django and Python. Some of these may change the behaviour of existing features and pre-existing behaviour. Specifically, some fixes were added to around the support of `UniqueConstraint` with nullable fields which will improve built-in serializer validation. +This release is considered a significant release to improve upstream support with Django and Python. Some of these may change the behavior of existing features and pre-existing behavior. Specifically, some fixes were added to around the support of `UniqueConstraint` with nullable fields which will improve built-in serializer validation. #### Features @@ -215,7 +215,7 @@ Date: 15th March 2024 * Partial serializer should not have required fields [[#7563](https://github.com/encode/django-rest-framework/pull/7563)] * Propagate 'default' from model field to serializer field. [[#9030](https://github.com/encode/django-rest-framework/pull/9030)] * Allow to override child.run_validation call in ListSerializer [[#8035](https://github.com/encode/django-rest-framework/pull/8035)] -* Align SearchFilter behaviour to django.contrib.admin search [[#9017](https://github.com/encode/django-rest-framework/pull/9017)] +* Align SearchFilter behavior to django.contrib.admin search [[#9017](https://github.com/encode/django-rest-framework/pull/9017)] * Class name added to unknown field error [[#9019](https://github.com/encode/django-rest-framework/pull/9019)] * Fix: Pagination response schemas. [[#9049](https://github.com/encode/django-rest-framework/pull/9049)] * Fix choices in ChoiceField to support IntEnum [[#8955](https://github.com/encode/django-rest-framework/pull/8955)] @@ -369,7 +369,7 @@ Date: 28th September 2020 * Add `--file` option to `generateschema` command. [#7130] * Support `tags` for OpenAPI schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#grouping-operations-with-tags). [#7184] -* Support customising the operation ID for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#operationid). [#7190] +* Support customizing the operation ID for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#operationid). [#7190] * Support OpenAPI components for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#components). [#7124] * The following methods on `AutoSchema` become public API: `get_path_parameters`, `get_pagination_parameters`, `get_filter_parameters`, `get_request_body`, `get_responses`, `get_serializer`, `get_paginator`, `map_serializer`, `map_field`, `map_choice_field`, `map_field_validators`, `allows_filters`. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#autoschema) * Add support for Django 3.1's database-agnositic `JSONField`. [#7467] @@ -407,7 +407,7 @@ Date: 28th September 2020 * Fix `PrimaryKeyRelatedField` and `HyperlinkedRelatedField` when source field is actually a property. [#7142] * `Token.generate_key` is now a class method. [#7502] * `@action` warns if method is wrapped in a decorator that does not preserve information using `@functools.wraps`. [#7098] -* Deprecate `serializers.NullBooleanField` in favour of `serializers.BooleanField` with `allow_null=True` [#7122] +* Deprecate `serializers.NullBooleanField` in favor of `serializers.BooleanField` with `allow_null=True` [#7122] --- @@ -417,7 +417,7 @@ Date: 28th September 2020 **Date**: 30th September 2020 -* **Security**: Drop `urlize_quoted_links` template tag in favour of Django's built-in `urlize`. Removes a XSS vulnerability for some kinds of content in the browsable API. +* **Security**: Drop `urlize_quoted_links` template tag in favor of Django's built-in `urlize`. Removes a XSS vulnerability for some kinds of content in the browsable API. ### 3.11.1 @@ -429,7 +429,7 @@ Date: 28th September 2020 **Date**: 12th December 2019 -* Drop `.set_context` API [in favour of a `requires_context` marker](3.11-announcement.md#validator-default-context). +* Drop `.set_context` API [in favor of a `requires_context` marker](3.11-announcement.md#validator-default-context). * Changed default widget for TextField with choices to select box. [#6892][gh6892] * Supported nested writes on non-relational fields, such as JSONField. [#6916][gh6916] * Include request/response media types in OpenAPI schemas, based on configured parsers/renderers. [#6865][gh6865] @@ -621,13 +621,13 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10. **Date**: [3rd April 2018][3.8.0-milestone] -* **Breaking Change**: Alter `read_only` plus `default` behaviour. [#5886][gh5886] +* **Breaking Change**: Alter `read_only` plus `default` behavior. [#5886][gh5886] `read_only` fields will now **always** be excluded from writable fields. Previously `read_only` fields with a `default` value would use the `default` for create and update operations. - In order to maintain the old behaviour you may need to pass the value of `read_only` fields when calling `save()` in + In order to maintain the old behavior you may need to pass the value of `read_only` fields when calling `save()` in the view: def perform_create(self, serializer): @@ -635,13 +635,13 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10. Alternatively you may override `save()` or `create()` or `update()` on the serializer as appropriate. -* Correct allow_null behaviour when required=False [#5888][gh5888] +* Correct allow_null behavior when required=False [#5888][gh5888] Without an explicit `default`, `allow_null` implies a default of `null` for outgoing serialization. Previously such fields were being skipped when read-only or otherwise not required. **Possible backwards compatibility break** if you were relying on such fields being excluded from the outgoing - representation. In order to restore the old behaviour you can override `data` to exclude the field when `None`. + representation. In order to restore the old behavior you can override `data` to exclude the field when `None`. For example: @@ -698,7 +698,7 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10. * Add HStoreField, postgres fields tests [#5654][gh5654] * Always fully qualify ValidationError in docs [#5751][gh5751] * Remove unreachable code from ManualSchema [#5766][gh5766] -* Allowed customising API documentation code samples [#5752][gh5752] +* Allowed customizing API documentation code samples [#5752][gh5752] * Updated docs to use `pip show` [#5757][gh5757] * Load 'static' instead of 'staticfiles' in templates [#5773][gh5773] * Fixed a typo in `fields` docs [#5783][gh5783] @@ -761,7 +761,7 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10. * Schema: Extract method for `manual_fields` processing [#5633][gh5633] - Allows for easier customisation of `manual_fields` processing, for example + Allows for easier customization of `manual_fields` processing, for example to provide per-method manual fields. `AutoSchema` adds `get_manual_fields`, as the intended override point, and a utility method `update_fields`, to handle by-name field replacement from a list, which, in general, you are not @@ -883,7 +883,7 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10. * Don't strip microseconds from `time` when encoding. Makes consistent with `datetime`. **BC Change**: Previously only milliseconds were encoded. [#5440][gh5440] * Added `STRICT_JSON` setting (default `True`) to raise exception for the extended float values (`nan`, `inf`, `-inf`) accepted by Python's `json` module. - **BC Change**: Previously these values would converted to corresponding strings. Set `STRICT_JSON` to `False` to restore the previous behaviour. [#5265][gh5265] + **BC Change**: Previously these values would converted to corresponding strings. Set `STRICT_JSON` to `False` to restore the previous behavior. [#5265][gh5265] * Add support for `page_size` parameter in CursorPaginator class [#5250][gh5250] * Make `DEFAULT_PAGINATION_CLASS` `None` by default. **BC Change**: If your were **just** setting `PAGE_SIZE` to enable pagination you will need to add `DEFAULT_PAGINATION_CLASS`. @@ -921,10 +921,10 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10. * Fix naming collisions in Schema Generation [#5464][gh5464] * Call Django's authenticate function with the request object [#5295][gh5295] * Update coreapi JS to 0.1.1 [#5479][gh5479] -* Have `is_list_view` recognise RetrieveModel… views [#5480][gh5480] +* Have `is_list_view` recognize RetrieveModel… views [#5480][gh5480] * Remove Django 1.8 & 1.9 compatibility code [#5481][gh5481] * Remove deprecated schema code from DefaultRouter [#5482][gh5482] -* Refactor schema generation to allow per-view customisation. +* Refactor schema generation to allow per-view customization. **BC Change**: `SchemaGenerator.get_serializer_fields` has been refactored as `AutoSchema.get_serializer_fields` and drops the `view` argument [#5354][gh5354] ## 3.6.x series diff --git a/docs/index.md b/docs/index.md index 87330f5af..230aa838c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -53,7 +53,7 @@ Some reasons you might want to use REST framework: * [Serialization][serializers] that supports both [ORM][modelserializer-section] and [non-ORM][serializer-section] data sources. * Customizable all the way down - just use [regular function-based views][functionview-section] if you don't need the [more][generic-views] [powerful][viewsets] [features][routers]. * Extensive documentation, and [great community support][group]. -* Used and trusted by internationally recognised companies including [Mozilla][mozilla], [Red Hat][redhat], [Heroku][heroku], and [Eventbrite][eventbrite]. +* Used and trusted by internationally recognized companies including [Mozilla][mozilla], [Red Hat][redhat], [Heroku][heroku], and [Eventbrite][eventbrite]. --- diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md index 8cf530b7a..dd2da6877 100644 --- a/docs/topics/browsable-api.md +++ b/docs/topics/browsable-api.md @@ -181,7 +181,7 @@ The context that's available to the template: * `FORMAT_PARAM` : The view can accept a format override * `METHOD_PARAM` : The view can accept a method override -You can override the `BrowsableAPIRenderer.get_context()` method to customise the context that gets passed to the template. +You can override the `BrowsableAPIRenderer.get_context()` method to customize the context that gets passed to the template. #### Not using base.html diff --git a/docs/topics/rest-hypermedia-hateoas.md b/docs/topics/rest-hypermedia-hateoas.md index 3498bddd1..c0822b027 100644 --- a/docs/topics/rest-hypermedia-hateoas.md +++ b/docs/topics/rest-hypermedia-hateoas.md @@ -32,7 +32,7 @@ REST framework also includes [serialization] and [parser]/[renderer] components ## What REST framework doesn't provide. -What REST framework doesn't do is give you machine readable hypermedia formats such as [HAL][hal], [Collection+JSON][collection], [JSON API][json-api] or HTML [microformats] by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope. +What REST framework doesn't do is give you machine readable hypermedia formats such as [HAL][hal], [Collection+JSON][collection], [JSON API][json-api] or HTML [microformats] by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labeled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope. [cite]: https://vimeo.com/channels/restfest/49503453 [dissertation]: https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 167303321..ca35dcf15 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -1,5 +1,5 @@ """ -Generic views that provide commonly needed behaviour. +Generic views that provide commonly needed behavior. """ from django.core.exceptions import ValidationError from django.db.models.query import QuerySet diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index 7fa8947cb..00487450b 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -1,7 +1,7 @@ """ Basic building blocks for generic class based views. -We don't bind behaviour to http method handlers yet, +We don't bind behavior to http method handlers yet, which allows mixin classes to be composed in interesting ways. """ from rest_framework import status diff --git a/rest_framework/schemas/coreapi.py b/rest_framework/schemas/coreapi.py index 657178304..1397f9842 100644 --- a/rest_framework/schemas/coreapi.py +++ b/rest_framework/schemas/coreapi.py @@ -50,7 +50,7 @@ Position conflicts with coreapi.Link for URL path {target_url}. Attempted to insert link with keys: {keys}. Adjust URLs to avoid naming collision or override `SchemaGenerator.get_keys()` -to customise schema structure. +to customize schema structure. """ @@ -513,7 +513,7 @@ class AutoSchema(ViewInspector): Default implementation looks for ModelViewSet or GenericAPIView actions/methods that cause filtering on the default implementation. - Override to adjust behaviour for your view. + Override to adjust behavior for your view. Note: Introduced in v3.7: Initially "private" (i.e. with leading underscore) to allow changes based on user experience. diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py index e569e2501..a048f9324 100644 --- a/rest_framework/schemas/openapi.py +++ b/rest_framework/schemas/openapi.py @@ -86,7 +86,7 @@ class SchemaGenerator(BaseSchemaGenerator): components_schemas.update(components) - # Normalise path for any provided mount url. + # Normalize path for any provided mount url. if path.startswith('/'): path = path[1:] path = urljoin(self.url or '/', path) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 290534300..ea2daffd5 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -7,7 +7,7 @@ Serialization in REST framework is a two-phase process: 1. Serializers marshal between complex types like model instances, and python primitives. -2. The process of marshalling between python primitives and request and +2. The process of marshaling between python primitives and request and response content is handled by parsers and renderers. """ diff --git a/tests/browsable_api/test_browsable_api.py b/tests/browsable_api/test_browsable_api.py index 758e3d1a4..9df4b2f5f 100644 --- a/tests/browsable_api/test_browsable_api.py +++ b/tests/browsable_api/test_browsable_api.py @@ -33,7 +33,7 @@ class AnonymousUserTests(TestCase): @override_settings(ROOT_URLCONF='tests.browsable_api.auth_urls') class DropdownWithAuthTests(TestCase): - """Tests correct dropdown behaviour with Auth views enabled.""" + """Tests correct dropdown behavior with Auth views enabled.""" def setUp(self): self.client = APIClient(enforce_csrf_checks=True) self.username = 'john' @@ -74,7 +74,7 @@ class DropdownWithAuthTests(TestCase): @override_settings(ROOT_URLCONF='tests.browsable_api.no_auth_urls') class NoDropdownWithoutAuthTests(TestCase): - """Tests correct dropdown behaviour with Auth views NOT enabled.""" + """Tests correct dropdown behavior with Auth views NOT enabled.""" def setUp(self): self.client = APIClient(enforce_csrf_checks=True) self.username = 'john' diff --git a/tests/browsable_api/test_browsable_nested_api.py b/tests/browsable_api/test_browsable_nested_api.py index a6c2ee6bd..9ef7605d6 100644 --- a/tests/browsable_api/test_browsable_nested_api.py +++ b/tests/browsable_api/test_browsable_nested_api.py @@ -28,7 +28,7 @@ urlpatterns = [ class DropdownWithAuthTests(TestCase): - """Tests correct dropdown behaviour with Auth views enabled.""" + """Tests correct dropdown behavior with Auth views enabled.""" @override_settings(ROOT_URLCONF='tests.browsable_api.test_browsable_nested_api') def test_login(self): diff --git a/tests/test_fields.py b/tests/test_fields.py index b52442a2c..03ff366ae 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -332,7 +332,7 @@ class TestInitialWithCallable: def test_initial_should_accept_callable(self): """ - Follows the default ``Field.initial`` behaviour where they accept a + Follows the default ``Field.initial`` behavior where they accept a callable to produce the initial value""" assert self.serializer.data == { 'initial_field': 123, diff --git a/tests/test_serializer_lists.py b/tests/test_serializer_lists.py index 42ebf4771..f76451a5a 100644 --- a/tests/test_serializer_lists.py +++ b/tests/test_serializer_lists.py @@ -287,7 +287,7 @@ class TestNestedListSerializer: class TestNestedListSerializerAllowEmpty: - """Tests the behaviour of allow_empty=False when a ListSerializer is used as a field.""" + """Tests the behavior of allow_empty=False when a ListSerializer is used as a field.""" @pytest.mark.parametrize('partial', (False, True)) def test_allow_empty_true(self, partial): @@ -643,7 +643,7 @@ class TestSerializerPartialUsage: class TestEmptyListSerializer: """ - Tests the behaviour of ListSerializers when there is no data passed to it + Tests the behavior of ListSerializers when there is no data passed to it """ def setup_method(self): @@ -672,7 +672,7 @@ class TestEmptyListSerializer: class TestMaxMinLengthListSerializer: """ - Tests the behaviour of ListSerializers when max_length and min_length are used + Tests the behavior of ListSerializers when max_length and min_length are used """ def setup_method(self): From 01659c075a9dedb6cb6d29ba23012d447aff0c8b Mon Sep 17 00:00:00 2001 From: Marcelo Galigniana Date: Thu, 30 Oct 2025 05:23:54 -0500 Subject: [PATCH 16/19] Fixed #5363 -- HTML5 datetime-local valid format HTMLFormRenderer (#9365) * Fixed #5363 -- HTML5 datetime-local valid format HTMLFormRenderer Co-authored-by: Peter Thomassen * Add condition to make code cleanable by pyupgrade --------- Co-authored-by: Bruno Alla --- rest_framework/renderers.py | 30 ++++++++++++-- tests/test_renderers.py | 81 +++++++++++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 4 deletions(-) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index b81f9ab46..6d7218bbc 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -10,6 +10,7 @@ REST framework also provides an HTML renderer that renders the browsable API. import base64 import contextlib import datetime +import sys from urllib import parse from django import forms @@ -22,7 +23,7 @@ from django.utils.html import mark_safe from django.utils.http import parse_header_parameters from django.utils.safestring import SafeString -from rest_framework import VERSION, exceptions, serializers, status +from rest_framework import ISO_8601, VERSION, exceptions, serializers, status from rest_framework.compat import ( INDENT_SEPARATORS, LONG_SEPARATORS, SHORT_SEPARATORS, coreapi, coreschema, pygments_css, yaml @@ -339,11 +340,32 @@ class HTMLFormRenderer(BaseRenderer): style['template_pack'] = parent_style.get('template_pack', self.template_pack) style['renderer'] = self - # Get a clone of the field with text-only value representation. + # Get a clone of the field with text-only value representation ('' if None or False). field = field.as_form_field() - if style.get('input_type') == 'datetime-local' and isinstance(field.value, str): - field.value = field.value.rstrip('Z') + if style.get('input_type') == 'datetime-local': + try: + format_ = field._field.format + except AttributeError: + format_ = api_settings.DATETIME_FORMAT + + if format_ is not None: + # field.value is expected to be a string + # https://www.django-rest-framework.org/api-guide/fields/#datetimefield + field_value = field.value + if format_ == ISO_8601 and sys.version_info < (3, 11): + # We can drop this branch once we drop support for Python < 3.11 + # https://docs.python.org/3/whatsnew/3.11.html#datetime + field_value = field_value.rstrip('Z') + field.value = ( + datetime.datetime.fromisoformat(field_value) if format_ == ISO_8601 + else datetime.datetime.strptime(field_value, format_) + ) + + # The format of an input type="datetime-local" is "yyyy-MM-ddThh:mm" + # followed by optional ":ss" or ":ss.SSS", so keep only the first three + # digits of milliseconds to avoid browser console error. + field.value = field.value.replace(tzinfo=None).isoformat(timespec="milliseconds") if 'template' in style: template_name = style['template'] diff --git a/tests/test_renderers.py b/tests/test_renderers.py index 1b396575d..e5c33e6b4 100644 --- a/tests/test_renderers.py +++ b/tests/test_renderers.py @@ -1,5 +1,7 @@ import re from collections.abc import MutableMapping +from datetime import datetime +from zoneinfo import ZoneInfo import pytest from django.core.cache import cache @@ -488,6 +490,85 @@ class TestHiddenFieldHTMLFormRenderer(TestCase): assert rendered == '' +class TestDateTimeFieldHTMLFormRender(TestCase): + """ + Default USE_TZ is True. + Default TIME_ZONE is 'America/Chicago'. + """ + + def _assert_datetime_rendering(self, appointment, expected, datetimefield_kwargs=None): + datetimefield_kwargs = datetimefield_kwargs or {} + + class TestSerializer(serializers.Serializer): + appointment = serializers.DateTimeField(**datetimefield_kwargs) + + serializer = TestSerializer(data={"appointment": appointment}) + serializer.is_valid() + renderer = HTMLFormRenderer() + field = serializer['appointment'] + rendered = renderer.render_field(field, {}) + expected_html = ( + '' + ) + + self.assertInHTML(expected_html, rendered) + + def test_datetime_field_rendering_milliseconds(self): + self._assert_datetime_rendering( + datetime(2024, 12, 24, 0, 55, 30, 345678), "2024-12-24T00:55:30.345" + ) + + def test_datetime_field_rendering_no_seconds_and_no_milliseconds(self): + self._assert_datetime_rendering( + datetime(2024, 12, 24, 0, 55, 0, 0), "2024-12-24T00:55:00.000" + ) + + def test_datetime_field_rendering_with_format_as_none(self): + self._assert_datetime_rendering( + datetime(2024, 12, 24, 0, 55, 30, 345678), + "2024-12-24T00:55:30.345", + {"format": None} + ) + + def test_datetime_field_rendering_with_format(self): + self._assert_datetime_rendering( + datetime(2024, 12, 24, 0, 55, 30, 345678), + "2024-12-24T00:55:00.000", + {"format": "%a %d %b %Y, %I:%M%p"} + ) + + # New project templates default to 'UTC'. + @override_settings(TIME_ZONE='UTC') + def test_datetime_field_rendering_utc(self): + self._assert_datetime_rendering( + datetime(2024, 12, 24, 0, 55, 30, 345678), + "2024-12-24T00:55:30.345" + ) + + @override_settings(REST_FRAMEWORK={'DATETIME_FORMAT': '%a %d %b %Y, %I:%M%p'}) + def test_datetime_field_rendering_with_custom_datetime_format(self): + self._assert_datetime_rendering( + datetime(2024, 12, 24, 0, 55, 30, 345678), + "2024-12-24T00:55:00.000" + ) + + @override_settings(REST_FRAMEWORK={'DATETIME_FORMAT': None}) + def test_datetime_field_rendering_datetime_format_is_none(self): + self._assert_datetime_rendering( + datetime(2024, 12, 24, 0, 55, 30, 345678), + "2024-12-24T00:55:30.345" + ) + + # Enforce it in True because in Django versions under 4.2 was False by default. + @override_settings(USE_TZ=True) + def test_datetime_field_rendering_timezone_aware_datetime(self): + self._assert_datetime_rendering( + datetime(2024, 12, 24, 0, 55, 30, 345678, tzinfo=ZoneInfo('Asia/Tokyo')), # +09:00 + "2024-12-23T09:55:30.345" # Rendered in -06:00 + ) + + class TestHTMLFormRenderer(TestCase): def setUp(self): class TestSerializer(serializers.Serializer): From ad0fea04de0b51657adc1cbc677034f562727684 Mon Sep 17 00:00:00 2001 From: Corentin Garcia Date: Thu, 30 Oct 2025 11:27:20 +0100 Subject: [PATCH 17/19] Add support for ipaddress objects in JSONEncoder (#9087) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add support for ipaddress objects in JSONEncoder * Update tests/test_encoders.py * Update assertions to be more explicit --------- Co-authored-by: Asif Saif Uddin {"Auvi":"অভি"} Co-authored-by: Bruno Alla --- rest_framework/utils/encoders.py | 10 ++++++++ tests/test_encoders.py | 43 ++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index aa4542286..63811b839 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -5,6 +5,7 @@ Helper classes for parsers. import contextlib import datetime import decimal +import ipaddress import json # noqa import uuid @@ -45,6 +46,15 @@ class JSONEncoder(json.JSONEncoder): return float(obj) elif isinstance(obj, uuid.UUID): return str(obj) + elif isinstance(obj, ( + ipaddress.IPv4Address, + ipaddress.IPv6Address, + ipaddress.IPv4Network, + ipaddress.IPv6Network, + ipaddress.IPv4Interface, + ipaddress.IPv6Interface) + ): + return str(obj) elif isinstance(obj, QuerySet): return tuple(obj) elif isinstance(obj, bytes): diff --git a/tests/test_encoders.py b/tests/test_encoders.py index 953e5564b..4ba653143 100644 --- a/tests/test_encoders.py +++ b/tests/test_encoders.py @@ -1,3 +1,4 @@ +import ipaddress from datetime import date, datetime, timedelta, timezone from decimal import Decimal from uuid import uuid4 @@ -78,6 +79,48 @@ class JSONEncoderTests(TestCase): unique_id = uuid4() assert self.encoder.default(unique_id) == str(unique_id) + def test_encode_ipaddress_ipv4address(self): + """ + Tests encoding ipaddress IPv4Address object + """ + obj = ipaddress.IPv4Address("192.168.1.1") + assert self.encoder.default(obj) == "192.168.1.1" + + def test_encode_ipaddress_ipv6address(self): + """ + Tests encoding ipaddress IPv6Address object + """ + obj = ipaddress.IPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") + assert self.encoder.default(obj) == "2001:db8:85a3::8a2e:370:7334" + + def test_encode_ipaddress_ipv4network(self): + """ + Tests encoding ipaddress IPv4Network object + """ + obj = ipaddress.IPv4Network("192.0.2.8/29") + assert self.encoder.default(obj) == "192.0.2.8/29" + + def test_encode_ipaddress_ipv6network(self): + """ + Tests encoding ipaddress IPv4Network object + """ + obj = ipaddress.IPv6Network("2001:4860:0000::0000/32") + assert self.encoder.default(obj) == "2001:4860::/32" + + def test_encode_ipaddress_ipv4interface(self): + """ + Tests encoding ipaddress IPv4Interface object + """ + obj = ipaddress.IPv4Interface("192.0.2.8/29") + assert self.encoder.default(obj) == "192.0.2.8/29" + + def test_encode_ipaddress_ipv6interface(self): + """ + Tests encoding ipaddress IPv4Network object + """ + obj = ipaddress.IPv6Interface("2001:4860:4860::8888/32") + assert self.encoder.default(obj) == "2001:4860:4860::8888/32" + @pytest.mark.skipif(not coreapi, reason='coreapi is not installed') def test_encode_coreapi_raises_error(self): """ From 648ded9574f0f3d3688d49694cd25f5ae40476bd Mon Sep 17 00:00:00 2001 From: Quaylyn Rimer <31830590+killerdevildog@users.noreply.github.com> Date: Thu, 30 Oct 2025 10:07:24 -0600 Subject: [PATCH 18/19] Fix mutable default arguments in OrderingFilter methods (#9742) * Install and configure flake8-bugbear to spot mutable default arguments * Fix mutable default arguments in OrderingFilter methods - Fixed get_default_valid_fields() and get_valid_fields() methods in filters.py - Changed context={} default parameter to context=None to prevent mutable default anti-pattern - Added proper None checking with context = {} assignment inside methods Why this fix is important: - Mutable default arguments (context={}) create shared state across function calls - Same dict object gets reused, potentially causing unexpected side effects - This is a well-known Python anti-pattern that can lead to bugs What was changed: - Line 249: get_default_valid_fields(self, queryset, view, context=None) - Line 285: get_valid_fields(self, queryset, view, context=None) - Added 'if context is None: context = {}' in both methods Testing results: - All existing filter tests pass (pytest tests/test_filters.py) - Custom verification script confirms fix works correctly - Maintains backward compatibility - No breaking changes to API Addresses GitHub issue #9741 --------- Co-authored-by: Bruno Alla --- .pre-commit-config.yaml | 1 + rest_framework/filters.py | 8 ++++++-- setup.cfg | 3 ++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 244d670b8..5780c8e31 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,6 +18,7 @@ repos: - id: flake8 additional_dependencies: - flake8-tidy-imports + - flake8-bugbear - repo: https://github.com/adamchainz/blacken-docs rev: 1.20.0 hooks: diff --git a/rest_framework/filters.py b/rest_framework/filters.py index 3f4730da8..010c87374 100644 --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -249,7 +249,9 @@ class OrderingFilter(BaseFilterBackend): return (ordering,) return ordering - def get_default_valid_fields(self, queryset, view, context={}): + def get_default_valid_fields(self, queryset, view, context=None): + if context is None: + context = {} # If `ordering_fields` is not specified, then we determine a default # based on the serializer class, if one exists on the view. if hasattr(view, 'get_serializer_class'): @@ -286,7 +288,9 @@ class OrderingFilter(BaseFilterBackend): ) ] - def get_valid_fields(self, queryset, view, context={}): + def get_valid_fields(self, queryset, view, context=None): + if context is None: + context = {} valid_fields = getattr(view, 'ordering_fields', self.ordering_fields) if valid_fields is None: diff --git a/setup.cfg b/setup.cfg index aebdf5362..6553bfcd5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,3 +1,4 @@ [flake8] -ignore = E501,W503,W504 +extend-ignore = E501,W503,W504,B +extend-select = B006 banned-modules = json = use from rest_framework.utils import json! From 1660c22f3ad80f08c4a6eaecf2344b22d520078e Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Thu, 30 Oct 2025 18:02:24 +0000 Subject: [PATCH 19/19] Delay CoreAPI deprecation until DRF 3.18 (#9810) --- pyproject.toml | 2 +- rest_framework/__init__.py | 2 +- rest_framework/filters.py | 8 ++++---- rest_framework/pagination.py | 10 +++++----- rest_framework/schemas/coreapi.py | 10 +++++----- tests/schemas/test_coreapi.py | 24 ++++++++++++------------ 6 files changed, 28 insertions(+), 28 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index f5551d80a..c89b6a002 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,7 +63,7 @@ max_supported_python = "3.14" [tool.pytest.ini_options] addopts = "--tb=short --strict-markers -ra" testpaths = [ "tests" ] -filterwarnings = [ "ignore:CoreAPI compatibility is deprecated*:rest_framework.RemovedInDRF317Warning" ] +filterwarnings = [ "ignore:CoreAPI compatibility is deprecated*:rest_framework.RemovedInDRF318Warning" ] [tool.coverage.run] # NOTE: source is ignored with pytest-cov (but uses the same). diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py index 61e078a95..d7e4060ff 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -24,5 +24,5 @@ ISO_8601 = 'iso-8601' DJANGO_DURATION_FORMAT = 'django' -class RemovedInDRF317Warning(PendingDeprecationWarning): +class RemovedInDRF318Warning(DeprecationWarning): pass diff --git a/rest_framework/filters.py b/rest_framework/filters.py index 010c87374..ea8c5ff19 100644 --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -14,7 +14,7 @@ from django.utils.encoding import force_str from django.utils.text import smart_split, unescape_string_literal from django.utils.translation import gettext_lazy as _ -from rest_framework import RemovedInDRF317Warning +from rest_framework import RemovedInDRF318Warning from rest_framework.compat import coreapi, coreschema from rest_framework.fields import CharField from rest_framework.settings import api_settings @@ -51,7 +51,7 @@ class BaseFilterBackend: def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' if coreapi is not None: - warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning) assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' return [] @@ -189,7 +189,7 @@ class SearchFilter(BaseFilterBackend): def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' if coreapi is not None: - warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning) assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' return [ coreapi.Field( @@ -355,7 +355,7 @@ class OrderingFilter(BaseFilterBackend): def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' if coreapi is not None: - warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning) assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' return [ coreapi.Field( diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index a543ceeb5..b6329b8c3 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -15,7 +15,7 @@ from django.template import loader from django.utils.encoding import force_str from django.utils.translation import gettext_lazy as _ -from rest_framework import RemovedInDRF317Warning +from rest_framework import RemovedInDRF318Warning from rest_framework.compat import coreapi, coreschema from rest_framework.exceptions import NotFound from rest_framework.response import Response @@ -154,7 +154,7 @@ class BasePagination: def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' if coreapi is not None: - warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning) return [] def get_schema_operation_parameters(self, view): @@ -316,7 +316,7 @@ class PageNumberPagination(BasePagination): def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' if coreapi is not None: - warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning) assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' fields = [ coreapi.Field( @@ -533,7 +533,7 @@ class LimitOffsetPagination(BasePagination): def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' if coreapi is not None: - warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning) assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' return [ coreapi.Field( @@ -936,7 +936,7 @@ class CursorPagination(BasePagination): def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' if coreapi is not None: - warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning) assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' fields = [ coreapi.Field( diff --git a/rest_framework/schemas/coreapi.py b/rest_framework/schemas/coreapi.py index 1397f9842..b56c2ecae 100644 --- a/rest_framework/schemas/coreapi.py +++ b/rest_framework/schemas/coreapi.py @@ -5,7 +5,7 @@ from urllib import parse from django.db import models from django.utils.encoding import force_str -from rest_framework import RemovedInDRF317Warning, exceptions, serializers +from rest_framework import RemovedInDRF318Warning, exceptions, serializers from rest_framework.compat import coreapi, coreschema, uritemplate from rest_framework.settings import api_settings @@ -119,7 +119,7 @@ class SchemaGenerator(BaseSchemaGenerator): def __init__(self, title=None, url=None, description=None, patterns=None, urlconf=None, version=None): assert coreapi, '`coreapi` must be installed for schema support.' if coreapi is not None: - warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning) assert coreschema, '`coreschema` must be installed for schema support.' super().__init__(title, url, description, patterns, urlconf) @@ -354,7 +354,7 @@ class AutoSchema(ViewInspector): """ super().__init__() if coreapi is not None: - warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning) if manual_fields is None: manual_fields = [] @@ -598,7 +598,7 @@ class ManualSchema(ViewInspector): """ super().__init__() if coreapi is not None: - warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning) assert all(isinstance(f, coreapi.Field) for f in fields), "`fields` must be a list of coreapi.Field instances" self._fields = fields @@ -622,5 +622,5 @@ class ManualSchema(ViewInspector): def is_enabled(): """Is CoreAPI Mode enabled?""" if coreapi is not None: - warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning) return issubclass(api_settings.DEFAULT_SCHEMA_CLASS, AutoSchema) diff --git a/tests/schemas/test_coreapi.py b/tests/schemas/test_coreapi.py index a97b02fe1..6e76447c6 100644 --- a/tests/schemas/test_coreapi.py +++ b/tests/schemas/test_coreapi.py @@ -7,7 +7,7 @@ from django.test import TestCase, override_settings from django.urls import include, path from rest_framework import ( - RemovedInDRF317Warning, filters, generics, pagination, permissions, + RemovedInDRF318Warning, filters, generics, pagination, permissions, serializers ) from rest_framework.compat import coreapi, coreschema @@ -1445,42 +1445,42 @@ def test_schema_handles_exception(): @pytest.mark.skipif(not coreapi, reason='coreapi is not installed') def test_coreapi_deprecation(): - with pytest.warns(RemovedInDRF317Warning): + with pytest.warns(RemovedInDRF318Warning): SchemaGenerator() - with pytest.warns(RemovedInDRF317Warning): + with pytest.warns(RemovedInDRF318Warning): AutoSchema() - with pytest.warns(RemovedInDRF317Warning): + with pytest.warns(RemovedInDRF318Warning): ManualSchema({}) - with pytest.warns(RemovedInDRF317Warning): + with pytest.warns(RemovedInDRF318Warning): deprecated_filter = OrderingFilter() deprecated_filter.get_schema_fields({}) - with pytest.warns(RemovedInDRF317Warning): + with pytest.warns(RemovedInDRF318Warning): deprecated_filter = BaseFilterBackend() deprecated_filter.get_schema_fields({}) - with pytest.warns(RemovedInDRF317Warning): + with pytest.warns(RemovedInDRF318Warning): deprecated_filter = SearchFilter() deprecated_filter.get_schema_fields({}) - with pytest.warns(RemovedInDRF317Warning): + with pytest.warns(RemovedInDRF318Warning): paginator = BasePagination() paginator.get_schema_fields({}) - with pytest.warns(RemovedInDRF317Warning): + with pytest.warns(RemovedInDRF318Warning): paginator = PageNumberPagination() paginator.get_schema_fields({}) - with pytest.warns(RemovedInDRF317Warning): + with pytest.warns(RemovedInDRF318Warning): paginator = LimitOffsetPagination() paginator.get_schema_fields({}) - with pytest.warns(RemovedInDRF317Warning): + with pytest.warns(RemovedInDRF318Warning): paginator = CursorPagination() paginator.get_schema_fields({}) - with pytest.warns(RemovedInDRF317Warning): + with pytest.warns(RemovedInDRF318Warning): is_enabled()