Merge branch 'main' into main

This commit is contained in:
Bruno Alla 2025-10-21 15:21:44 +02:00 committed by GitHub
commit a2cba19322
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
36 changed files with 1344 additions and 963 deletions

View File

@ -14,18 +14,19 @@ jobs:
strategy: strategy:
matrix: matrix:
python-version: python-version:
- '3.9'
- '3.10' - '3.10'
- '3.11' - '3.11'
- '3.12' - '3.12'
- '3.13' - '3.13'
- '3.14'
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v5
- uses: actions/setup-python@v5 - uses: actions/setup-python@v6
with: with:
python-version: ${{ matrix.python-version }} python-version: ${{ matrix.python-version }}
allow-prereleases: true
cache: 'pip' cache: 'pip'
cache-dependency-path: 'requirements/*.txt' cache-dependency-path: 'requirements/*.txt'
@ -39,7 +40,7 @@ jobs:
run: tox run -f py$(echo ${{ matrix.python-version }} | tr -d . | cut -f 1 -d '-') run: tox run -f py$(echo ${{ matrix.python-version }} | tr -d . | cut -f 1 -d '-')
- name: Run extra tox targets - name: Run extra tox targets
if: ${{ matrix.python-version == '3.9' }} if: ${{ matrix.python-version == '3.13' }}
run: | run: |
tox -e base,dist,docs tox -e base,dist,docs
@ -54,9 +55,9 @@ jobs:
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v5
- uses: actions/setup-python@v5 - uses: actions/setup-python@v6
with: with:
python-version: '3.9' python-version: '3.13'
- name: Install dependencies - name: Install dependencies
run: pip install -r requirements/requirements-documentation.txt run: pip install -r requirements/requirements-documentation.txt

View File

@ -22,7 +22,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v5
- run: git fetch --no-tags --prune --depth=1 origin gh-pages - run: git fetch --no-tags --prune --depth=1 origin gh-pages
- uses: actions/setup-python@v5 - uses: actions/setup-python@v6
with: with:
python-version: 3.x python-version: 3.x
- run: pip install -r requirements/requirements-documentation.txt - run: pip install -r requirements/requirements-documentation.txt

View File

@ -15,7 +15,7 @@ jobs:
with: with:
fetch-depth: 0 fetch-depth: 0
- uses: actions/setup-python@v5 - uses: actions/setup-python@v6
with: with:
python-version: "3.10" python-version: "3.10"

View File

@ -19,21 +19,26 @@ repos:
additional_dependencies: additional_dependencies:
- flake8-tidy-imports - flake8-tidy-imports
- repo: https://github.com/adamchainz/blacken-docs - repo: https://github.com/adamchainz/blacken-docs
rev: 1.16.0 rev: 1.20.0
hooks: hooks:
- id: blacken-docs - id: blacken-docs
exclude: ^(?!docs).*$
additional_dependencies: additional_dependencies:
- black==23.1.0 - black==25.9.0
- repo: https://github.com/codespell-project/codespell - repo: https://github.com/codespell-project/codespell
# Configuration for codespell is in .codespellrc # Configuration for codespell is in .codespellrc
rev: v2.2.6 rev: v2.2.6
hooks: hooks:
- id: codespell - id: codespell
exclude: locale|kickstarter-announcement.md|coreapi-0.1.1.js exclude: locale|kickstarter-announcement.md|coreapi-0.1.1.js
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 - repo: https://github.com/asottile/pyupgrade
rev: v3.19.1 rev: v3.21.0
hooks: hooks:
- id: pyupgrade - 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:
- id: pyproject-fmt

View File

@ -54,7 +54,7 @@ Some reasons you might want to use REST framework:
# Requirements # Requirements
* Python 3.9+ * Python 3.10+
* Django 4.2, 5.0, 5.1, 5.2 * Django 4.2, 5.0, 5.1, 5.2
We **highly recommend** and only officially support the latest patch release of We **highly recommend** and only officially support the latest patch release of
@ -67,10 +67,11 @@ Install using `pip`...
pip install djangorestframework pip install djangorestframework
Add `'rest_framework'` to your `INSTALLED_APPS` setting. Add `'rest_framework'` to your `INSTALLED_APPS` setting.
```python ```python
INSTALLED_APPS = [ INSTALLED_APPS = [
... # ...
'rest_framework', "rest_framework",
] ]
``` ```
@ -99,7 +100,7 @@ from rest_framework import routers, serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer): class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = User model = User
fields = ['url', 'username', 'email', 'is_staff'] fields = ["url", "username", "email", "is_staff"]
# ViewSets define the view behavior. # ViewSets define the view behavior.
@ -110,13 +111,13 @@ class UserViewSet(viewsets.ModelViewSet):
# Routers provide a way of automatically determining the URL conf. # Routers provide a way of automatically determining the URL conf.
router = routers.DefaultRouter() router = routers.DefaultRouter()
router.register(r'users', UserViewSet) router.register(r"users", UserViewSet)
# Wire up our API using automatic URL routing. # Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API. # Additionally, we include login URLs for the browsable API.
urlpatterns = [ urlpatterns = [
path('', include(router.urls)), path("", include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
] ]
``` ```
@ -126,15 +127,15 @@ Add the following to your `settings.py` module:
```python ```python
INSTALLED_APPS = [ INSTALLED_APPS = [
... # Make sure to include the default installed apps here. # ... make sure to include the default installed apps here.
'rest_framework', "rest_framework",
] ]
REST_FRAMEWORK = { REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions, # Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users. # or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [ "DEFAULT_PERMISSION_CLASSES": [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', "rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly",
] ]
} }
``` ```

View File

@ -459,7 +459,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). 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. [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.

View File

@ -235,7 +235,7 @@ For example:
search_fields = ['=username', '=email'] 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: 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) ![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: For example, to order users by username:

View File

@ -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)` #### `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. Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.
@ -374,8 +407,6 @@ Allowing `PUT` as create operations is problematic, as it necessarily exposes in
Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious. Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.
If you need to generic PUT-as-create behavior you may want to include something like [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views.
--- ---
# Third party packages # Third party packages

View File

@ -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_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. * `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. * `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"`. * `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"`.
--- ---

View File

@ -186,8 +186,13 @@ The available decorators are:
* `@authentication_classes(...)` * `@authentication_classes(...)`
* `@throttle_classes(...)` * `@throttle_classes(...)`
* `@permission_classes(...)` * `@permission_classes(...)`
* `@content_negotiation_class(...)`
* `@metadata_class(...)`
* `@versioning_class(...)`
Each of these decorators takes a single argument which must be a list or tuple of classes. Each of these decorators is equivalent to setting their respective [api policy attributes][api-policy-attributes].
All decorators take a single argument. The ones that end with `_class` expect a single class while the ones ending in `_classes` expect a list or tuple of classes.
## View schema decorator ## View schema decorator
@ -224,4 +229,5 @@ You may pass `None` in order to exclude the view from schema generation.
[throttling]: throttling.md [throttling]: throttling.md
[schemas]: schemas.md [schemas]: schemas.md
[classy-drf]: http://www.cdrf.co [classy-drf]: http://www.cdrf.co
[api-policy-attributes]: views.md#api-policy-attributes

View File

@ -231,7 +231,7 @@ Using the example from the previous section:
Alternatively, you can use the `url_name` attribute set by the `@action` decorator. Alternatively, you can use the `url_name` attribute set by the `@action` decorator.
```pycon ```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' 'http://localhost:8000/api/users/1/set_password'
``` ```

View File

@ -50,11 +50,9 @@ class DocStringExampleListView(APIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly] 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 ## Validator / Default Context
@ -76,8 +74,7 @@ Validator implementations will look like this:
class CustomValidator: class CustomValidator:
requires_context = True requires_context = True
def __call__(self, value, serializer_field): def __call__(self, value, serializer_field): ...
...
``` ```
Default implementations will look like this: Default implementations will look like this:
@ -86,8 +83,7 @@ Default implementations will look like this:
class CustomDefault: class CustomDefault:
requires_context = True requires_context = True
def __call__(self, serializer_field): def __call__(self, serializer_field): ...
...
``` ```
--- ---

View File

@ -81,12 +81,45 @@ To run the tests, clone the repository, and then:
# Run the tests # Run the tests
./runtests.py ./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 ### Test options
Run using a more concise output style. Run using a more concise output style.
./runtests.py -q ./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. Run the tests for a given test case.
./runtests.py MyTestCase ./runtests.py MyTestCase
@ -99,6 +132,7 @@ Shorter form to run the tests for a given test method.
./runtests.py test_this_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. 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 ### Running against multiple environments

View File

@ -60,8 +60,8 @@ The following template should be used for the description of the issue, and serv
- [ ] 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/***). - [ ] 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/***).
- [ ] Update supported versions: - [ ] Update supported versions:
- [ ] `setup.py` `python_requires` list - [ ] `pyproject.toml` `python_requires` list
- [ ] `setup.py` Python & Django version trove classifiers - [ ] `pyproject.toml` Python & Django version trove classifiers
- [ ] `README` Python & Django versions - [ ] `README` Python & Django versions
- [ ] `docs` Python & Django versions - [ ] `docs` Python & Django versions
- [ ] Update the translations from [transifex](https://www.django-rest-framework.org/topics/project-management/#translations). - [ ] Update the translations from [transifex](https://www.django-rest-framework.org/topics/project-management/#translations).
@ -72,7 +72,9 @@ The following template should be used for the description of the issue, and serv
- [ ] Confirm with @tomchristie that release is finalized and ready to go. - [ ] Confirm with @tomchristie that release is finalized and ready to go.
- [ ] Ensure that release date is included in pull request. - [ ] Ensure that release date is included in pull request.
- [ ] Merge the release pull request. - [ ] Merge the release pull request.
- [ ] Push the package to PyPI with `./setup.py publish`. - [ ] Install the release tools: `pip install build twine`
- [ ] Build the package: `python -m build`
- [ ] Push the package to PyPI with `twine upload dist/*`
- [ ] Tag the release, with `git tag -a *.*.* -m 'version *.*.*'; git push --tags`. - [ ] Tag the release, with `git tag -a *.*.* -m 'version *.*.*'; git push --tags`.
- [ ] Deploy the documentation with `mkdocs gh-deploy`. - [ ] Deploy the documentation with `mkdocs gh-deploy`.
- [ ] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework). - [ ] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).

View File

@ -159,6 +159,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. * [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-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 * [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 ### Customization
@ -262,4 +263,5 @@ To submit new content, [create a pull request][drf-create-pr].
[drf-redesign]: https://github.com/youzarsiph/drf-redesign [drf-redesign]: https://github.com/youzarsiph/drf-redesign
[drf-material]: https://github.com/youzarsiph/drf-material [drf-material]: https://github.com/youzarsiph/drf-material
[django-pyoidc]: https://github.com/makinacorpus/django_pyoidc [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 [drf-shapeless-serializers]: https://github.com/khaledsukkar2/drf-shapeless-serializers

View File

@ -88,7 +88,7 @@ continued development by **[signing up for a paid plan][funding]**.
REST framework requires the following: REST framework requires the following:
* Django (4.2, 5.0, 5.1, 5.2) * Django (4.2, 5.0, 5.1, 5.2)
* Python (3.9, 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 We **highly recommend** and only officially support the latest patch release of
each Python and Django series. each Python and Django series.

View File

@ -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. 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 ```bash
source env/bin/activate python3 -m venv env
source env/bin/activate
```
Now that we're inside a virtual environment, we can install our package requirements. Now that we're inside a virtual environment, we can install our package requirements.
pip install django ```bash
pip install djangorestframework pip install django
pip install pygments # We'll be using this for the code highlighting 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]. **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. Okay, we're ready to get coding.
To get started, let's create a new project to work with. To get started, let's create a new project to work with.
cd ~ ```bash
django-admin startproject tutorial cd ~
cd tutorial 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. 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: 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 = [ ```text
... INSTALLED_APPS = [
'rest_framework', ...
'snippets', 'rest_framework',
] 'snippets',
]
```
Okay, we're ready to roll. 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. 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 ```python
from pygments.lexers import get_all_lexers from django.db import models
from pygments.styles import get_all_styles 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]] LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()]) STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
class Snippet(models.Model): class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='') title = models.CharField(max_length=100, blank=True, default="")
code = models.TextField() code = models.TextField()
linenos = models.BooleanField(default=False) linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) language = models.CharField(
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) choices=LANGUAGE_CHOICES, default="python", max_length=100
)
style = models.CharField(choices=STYLE_CHOICES, default="friendly", max_length=100)
class Meta: class Meta:
ordering = ['created'] ordering = ["created"]
```
We'll also need to create an initial migration for our snippet model, and sync the database for the first time. 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 ```bash
python manage.py migrate snippets python manage.py makemigrations snippets
python manage.py migrate snippets
```
## Creating a Serializer class ## 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. 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 ```python
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
class SnippetSerializer(serializers.Serializer): class SnippetSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True) id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False, allow_blank=True, max_length=100) title = serializers.CharField(required=False, allow_blank=True, max_length=100)
code = serializers.CharField(style={'base_template': 'textarea.html'}) code = serializers.CharField(style={"base_template": "textarea.html"})
linenos = serializers.BooleanField(required=False) linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default="python")
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') style = serializers.ChoiceField(choices=STYLE_CHOICES, default="friendly")
def create(self, validated_data): def create(self, validated_data):
""" """
Create and return a new `Snippet` instance, given the validated data. Create and return a new `Snippet` instance, given the validated data.
""" """
return Snippet.objects.create(**validated_data) return Snippet.objects.create(**validated_data)
def update(self, instance, validated_data): def update(self, instance, validated_data):
""" """
Update and return an existing `Snippet` instance, given the validated data. Update and return an existing `Snippet` instance, given the validated data.
""" """
instance.title = validated_data.get('title', instance.title) instance.title = validated_data.get("title", instance.title)
instance.code = validated_data.get('code', instance.code) instance.code = validated_data.get("code", instance.code)
instance.linenos = validated_data.get('linenos', instance.linenos) instance.linenos = validated_data.get("linenos", instance.linenos)
instance.language = validated_data.get('language', instance.language) instance.language = validated_data.get("language", instance.language)
instance.style = validated_data.get('style', instance.style) instance.style = validated_data.get("style", instance.style)
instance.save() instance.save()
return instance 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()` 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. 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. 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 ```pycon
from snippets.serializers import SnippetSerializer >>> from snippets.models import Snippet
from rest_framework.renderers import JSONRenderer >>> from snippets.serializers import SnippetSerializer
from rest_framework.parsers import JSONParser >>> from rest_framework.renderers import JSONRenderer
>>> from rest_framework.parsers import JSONParser
snippet = Snippet(code='foo = "bar"\n') >>> snippet = Snippet(code='foo = "bar"\n')
snippet.save() >>> snippet.save()
snippet = Snippet(code='print("hello, world")\n') >>> snippet = Snippet(code='print("hello, world")\n')
snippet.save() >>> snippet.save()
```
We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances. 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) ```pycon
serializer.data >>> serializer = SnippetSerializer(snippet)
# {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'} >>> 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`. 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) ```pycon
content >>> content = JSONRenderer().render(serializer.data)
# b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}' >>> 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... Deserialization is similar. First we parse a stream into Python native datatypes...
import io ```pycon
>>> import io
stream = io.BytesIO(content) >>> stream = io.BytesIO(content)
data = JSONParser().parse(stream) >>> data = JSONParser().parse(stream)
```
...then we restore those native datatypes into a fully populated object instance. ...then we restore those native datatypes into a fully populated object instance.
serializer = SnippetSerializer(data=data) ```pycon
serializer.is_valid() >>> serializer = SnippetSerializer(data=data)
# True >>> serializer.is_valid()
serializer.validated_data True
# {'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'} >>> serializer.validated_data
serializer.save() {'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}
# <Snippet: Snippet object> >>> serializer.save()
<Snippet: Snippet object>
```
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. 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. 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) ```pycon
serializer.data >>> serializer = SnippetSerializer(Snippet.objects.all(), many=True)
# [{'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'}] >>> 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 ## 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. 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. Open the file `snippets/serializers.py` again, and replace the `SnippetSerializer` class with the following.
class SnippetSerializer(serializers.ModelSerializer): ```python
class Meta: class SnippetSerializer(serializers.ModelSerializer):
model = Snippet class Meta:
fields = ['id', 'title', 'code', 'linenos', 'language', 'style'] 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: 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 ```pycon
serializer = SnippetSerializer() >>> from snippets.serializers import SnippetSerializer
print(repr(serializer))
# SnippetSerializer(): >>> serializer = SnippetSerializer()
# id = IntegerField(label='ID', read_only=True) >>> print(repr(serializer))
# title = CharField(allow_blank=True, max_length=100, required=False) SnippetSerializer():
# code = CharField(style={'base_template': 'textarea.html'}) id = IntegerField(label='ID', read_only=True)
# linenos = BooleanField(required=False) title = CharField(allow_blank=True, max_length=100, required=False)
# language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... code = CharField(style={'base_template': 'textarea.html'})
# style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')... 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: 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. Edit the `snippets/views.py` file, and add the following.
from django.http import HttpResponse, JsonResponse ```python
from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, JsonResponse
from rest_framework.parsers import JSONParser from django.views.decorators.csrf import csrf_exempt
from snippets.models import Snippet from rest_framework.parsers import JSONParser
from snippets.serializers import SnippetSerializer 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. 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 ```python
def snippet_list(request): @csrf_exempt
""" def snippet_list(request):
List all code snippets, or create a new snippet. """
""" List all code snippets, or create a new snippet.
if request.method == 'GET': """
snippets = Snippet.objects.all() if request.method == "GET":
serializer = SnippetSerializer(snippets, many=True) snippets = Snippet.objects.all()
return JsonResponse(serializer.data, safe=False) serializer = SnippetSerializer(snippets, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST': elif request.method == "POST":
data = JSONParser().parse(request) data = JSONParser().parse(request)
serializer = SnippetSerializer(data=data) serializer = SnippetSerializer(data=data)
if serializer.is_valid(): if serializer.is_valid():
serializer.save() serializer.save()
return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400) 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. 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. 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 ```python
def snippet_detail(request, pk): @csrf_exempt
""" def snippet_detail(request, pk):
Retrieve, update or delete a code snippet. """
""" Retrieve, update or delete a code snippet.
try: """
snippet = Snippet.objects.get(pk=pk) try:
except Snippet.DoesNotExist: snippet = Snippet.objects.get(pk=pk)
return HttpResponse(status=404) except Snippet.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET': if request.method == "GET":
serializer = SnippetSerializer(snippet) 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.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'PUT': elif request.method == "DELETE":
data = JSONParser().parse(request) snippet.delete()
serializer = SnippetSerializer(snippet, data=data) return HttpResponse(status=204)
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)
Finally we need to wire these views up. Create the `snippets/urls.py` file: Finally we need to wire these views up. Create the `snippets/urls.py` file:
from django.urls import path ```python
from snippets import views from django.urls import path
from snippets import views
urlpatterns = [ urlpatterns = [
path('snippets/', views.snippet_list), path("snippets/", views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail), path("snippets/<int:pk>/", 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. 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 = [ urlpatterns = [
path('', include('snippets.urls')), 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. 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 out of the shell...
quit() ```pycon
>>> quit()
```
...and start up Django's development server. ...and start up Django's development server.
python manage.py runserver ```bash
python manage.py runserver
Validating models... Validating models...
0 errors found 0 errors found
Django version 5.0, using settings 'tutorial.settings' Django version 5.0, using settings 'tutorial.settings'
Starting Development server at http://127.0.0.1:8000/ Starting Development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C. Quit the server with CONTROL-C.
```
In another terminal window, we can test the server. 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: You can install httpie using pip:
pip install httpie ```bash
pip install httpie
```
Finally, we can get a list of all of the snippets: 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 HTTP/1.1 200 OK
... ...
[ [
{ {
"id": 1, "id": 1,
"title": "", "title": "",
"code": "foo = \"bar\"\n", "code": "foo = \"bar\"\n",
"linenos": false, "linenos": false,
"language": "python", "language": "python",
"style": "friendly" "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
...
{ {
"id": 2, "id": 2,
"title": "", "title": "",
@ -365,7 +395,34 @@ Or we can get a particular snippet by referencing its id:
"linenos": false, "linenos": false,
"language": "python", "language": "python",
"style": "friendly" "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. Similarly, you can have the same json displayed by visiting these URLs in a web browser.

View File

@ -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. 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. ```python
request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods. 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 ## 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. 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 ## 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. Okay, let's go ahead and start using these new components to refactor our views slightly.
from rest_framework import status ```python
from rest_framework.decorators import api_view from rest_framework import status
from rest_framework.response import Response from rest_framework.decorators import api_view
from snippets.models import Snippet from rest_framework.response import Response
from snippets.serializers import SnippetSerializer from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
@api_view(['GET', 'POST']) @api_view(["GET", "POST"])
def snippet_list(request): def snippet_list(request):
""" """
List all code snippets, or create a new snippet. List all code snippets, or create a new snippet.
""" """
if request.method == 'GET': if request.method == "GET":
snippets = Snippet.objects.all() snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True) serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data) return Response(serializer.data)
elif request.method == 'POST': elif request.method == "POST":
serializer = SnippetSerializer(data=request.data) serializer = SnippetSerializer(data=request.data)
if serializer.is_valid(): if serializer.is_valid():
serializer.save() serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 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. 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. Here is the view for an individual snippet, in the `views.py` module.
@api_view(['GET', 'PUT', 'DELETE']) ```python
def snippet_detail(request, pk): @api_view(["GET", "PUT", "DELETE"])
""" def snippet_detail(request, pk):
Retrieve, update or delete a code snippet. """
""" Retrieve, update or delete a code snippet.
try: """
snippet = Snippet.objects.get(pk=pk) try:
except Snippet.DoesNotExist: snippet = Snippet.objects.get(pk=pk)
return Response(status=status.HTTP_404_NOT_FOUND) except Snippet.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET': if request.method == "GET":
serializer = SnippetSerializer(snippet) 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.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'PUT': elif request.method == "DELETE":
serializer = SnippetSerializer(snippet, data=request.data) snippet.delete()
if serializer.is_valid(): return Response(status=status.HTTP_204_NO_CONTENT)
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)
This should all feel very familiar - it is not a lot different from working with regular Django views. 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 ## 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 [<http://example.com/api/items/4.json>][json-url].
Start by adding a `format` keyword argument to both of the views, like so. 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 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. 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 ```python
from rest_framework.urlpatterns import format_suffix_patterns from django.urls import path
from snippets import views from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
urlpatterns = [ urlpatterns = [
path('snippets/', views.snippet_list), path("snippets/", views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail), path("snippets/<int:pk>/", 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. 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. 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 HTTP/1.1 200 OK
... ...
[ [
{ {
"id": 1, "id": 1,
"title": "", "title": "",
"code": "foo = \"bar\"\n", "code": "foo = \"bar\"\n",
"linenos": false, "linenos": false,
"language": "python", "language": "python",
"style": "friendly" "style": "friendly"
}, },
{ {
"id": 2, "id": 2,
"title": "", "title": "",
"code": "print(\"hello, world\")\n", "code": "print(\"hello, world\")\n",
"linenos": false, "linenos": false,
"language": "python", "language": "python",
"style": "friendly" "style": "friendly"
} }
] ]
```
We can control the format of the response that we get back, either by using the `Accept` header: 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 ```bash
http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML 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: Or by appending a format suffix:
http http://127.0.0.1:8000/snippets.json # JSON suffix ```bash
http http://127.0.0.1:8000/snippets.api # Browsable API suffix 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. Similarly, we can control the format of the request that we send, using the `Content-Type` header.
# POST using form data ```bash
http --form POST http://127.0.0.1:8000/snippets/ code="print(123)" # POST using form data
http --form POST http://127.0.0.1:8000/snippets/ code="print(123)"
{ {
"id": 3, "id": 3,
"title": "", "title": "",
"code": "print(123)", "code": "print(123)",
"linenos": false, "linenos": false,
"language": "python", "language": "python",
"style": "friendly" "style": "friendly"
} }
# POST using JSON # POST using JSON
http --json POST http://127.0.0.1:8000/snippets/ code="print(456)" http --json POST http://127.0.0.1:8000/snippets/ code="print(456)"
{ {
"id": 4, "id": 4,
"title": "", "title": "",
"code": "print(456)", "code": "print(456)",
"linenos": false, "linenos": false,
"language": "python", "language": "python",
"style": "friendly" "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. 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 [<http://127.0.0.1:8000/snippets/>][devserver].
### Browsability ### Browsability

View File

@ -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`. 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 ```python
from snippets.serializers import SnippetSerializer from snippets.models import Snippet
from django.http import Http404 from snippets.serializers import SnippetSerializer
from rest_framework.views import APIView from django.http import Http404
from rest_framework.response import Response from rest_framework.views import APIView
from rest_framework import status from rest_framework.response import Response
from rest_framework import status
class SnippetList(APIView): class SnippetList(APIView):
""" """
List all snippets, or create a new snippet. 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)
def post(self, request, format=None): def get(self, request, format=None):
serializer = SnippetSerializer(data=request.data) snippets = Snippet.objects.all()
if serializer.is_valid(): serializer = SnippetSerializer(snippets, many=True)
serializer.save() return Response(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 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`. 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): ```python
""" class SnippetDetail(APIView):
Retrieve, update or delete a snippet instance. """
""" Retrieve, update or delete a snippet instance.
def get_object(self, pk): """
try:
return Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
raise Http404
def get(self, request, pk, format=None): def get_object(self, pk):
snippet = self.get_object(pk) try:
serializer = SnippetSerializer(snippet) 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.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk, format=None): def delete(self, request, pk, format=None):
snippet = self.get_object(pk) snippet = self.get_object(pk)
serializer = SnippetSerializer(snippet, data=request.data) snippet.delete()
if serializer.is_valid(): return Response(status=status.HTTP_204_NO_CONTENT)
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)
That's looking good. Again, it's still pretty similar to the function based view right now. 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. We'll also need to refactor our `snippets/urls.py` slightly now that we're using class-based views.
from django.urls import path ```python
from rest_framework.urlpatterns import format_suffix_patterns from django.urls import path
from snippets import views from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
urlpatterns = [ urlpatterns = [
path('snippets/', views.SnippetList.as_view()), path("snippets/", views.SnippetList.as_view()),
path('snippets/<int:pk>/', views.SnippetDetail.as_view()), path("snippets/<int:pk>/", 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. 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. 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 ```python
from snippets.serializers import SnippetSerializer from snippets.models import Snippet
from rest_framework import mixins from snippets.serializers import SnippetSerializer
from rest_framework import generics 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): class SnippetList(
return self.list(request, *args, **kwargs) mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView
):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def post(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
return self.create(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`. 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. 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, ```python
mixins.UpdateModelMixin, class SnippetDetail(
mixins.DestroyModelMixin, mixins.RetrieveModelMixin,
generics.GenericAPIView): mixins.UpdateModelMixin,
queryset = Snippet.objects.all() mixins.DestroyModelMixin,
serializer_class = SnippetSerializer generics.GenericAPIView,
):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs) return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs): def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs) return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs): def delete(self, request, *args, **kwargs):
return self.destroy(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. 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. 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 ```python
from snippets.serializers import SnippetSerializer from snippets.models import Snippet
from rest_framework import generics from snippets.serializers import SnippetSerializer
from rest_framework import generics
class SnippetList(generics.ListCreateAPIView): class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all() queryset = Snippet.objects.all()
serializer_class = SnippetSerializer serializer_class = SnippetSerializer
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all() queryset = Snippet.objects.all()
serializer_class = SnippetSerializer 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. Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.

View File

@ -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`. Add the following two fields to the `Snippet` model in `models.py`.
owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE) ```python
highlighted = models.TextField() 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'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: We'll need some extra imports:
from pygments.lexers import get_lexer_by_name ```python
from pygments.formatters.html import HtmlFormatter from pygments.lexers import get_lexer_by_name
from pygments import highlight from pygments.formatters.html import HtmlFormatter
from pygments import highlight
```
And now we can add a `.save()` method to our model class: And now we can add a `.save()` method to our model class:
def save(self, *args, **kwargs): ```python
""" def save(self, *args, **kwargs):
Use the `pygments` library to create a highlighted HTML """
representation of the code snippet. 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 lexer = get_lexer_by_name(self.language)
options = {'title': self.title} if self.title else {} linenos = "table" if self.linenos else False
formatter = HtmlFormatter(style=self.style, linenos=linenos, options = {"title": self.title} if self.title else {}
full=True, **options) formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter) self.highlighted = highlight(self.code, lexer, formatter)
super().save(*args, **kwargs) super().save(*args, **kwargs)
```
When that's all done we'll need to update our database tables. 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. 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 ```bash
rm -r snippets/migrations rm -f db.sqlite3
python manage.py makemigrations snippets rm -r snippets/migrations
python manage.py migrate 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. 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 ## 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: 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: class UserSerializer(serializers.ModelSerializer):
model = User snippets = serializers.PrimaryKeyRelatedField(
fields = ['id', 'username', 'snippets'] 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. 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. 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): class UserList(generics.ListAPIView):
queryset = User.objects.all() queryset = User.objects.all()
serializer_class = UserSerializer serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView): class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all() queryset = User.objects.all()
serializer_class = UserSerializer serializer_class = UserSerializer
```
Make sure to also import the `UserSerializer` class 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`. 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()), ```python
path('users/<int:pk>/', views.UserDetail.as_view()), path("users/", views.UserList.as_view()),
path("users/<int:pk>/", views.UserDetail.as_view()),
```
## Associating Snippets with Users ## 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: On the `SnippetList` view class, add the following method:
def perform_create(self, serializer): ```python
serializer.save(owner=self.request.user) 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. 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`: 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. **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 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. 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 ## 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: 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. And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
urlpatterns += [ ```python
path('api-auth/', include('rest_framework.urls')), urlpatterns += [
] path("api-auth/", include("rest_framework.urls")),
]
```
The `'api-auth/'` part of pattern can actually be whatever URL you want to use. 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` 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): class IsOwnerOrReadOnly(permissions.BasePermission):
""" """
Custom permission to only allow owners of an object to edit it. Custom permission to only allow owners of an object to edit it.
""" """
def has_object_permission(self, request, view, obj): def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request, # Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests. # so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS: if request.method in permissions.SAFE_METHODS:
return True return True
# Write permissions are only allowed to the owner of the snippet. # Write permissions are only allowed to the owner of the snippet.
return obj.owner == request.user 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: 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, ```python
IsOwnerOrReadOnly] permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
```
Make sure to also import the `IsOwnerOrReadOnly` class. 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. 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: 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. 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, "id": 1,
"owner": "admin", "owner": "admin",
"title": "foo", "title": "foo",
"code": "print(789)", "code": "print(789)",
"linenos": false, "linenos": false,
"language": "python", "language": "python",
"style": "friendly" "style": "friendly"
} }
```
## Summary ## Summary

View File

@ -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: 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 ```python
from rest_framework.response import Response from rest_framework.decorators import api_view
from rest_framework.reverse import reverse from rest_framework.response import Response
from rest_framework.reverse import reverse
@api_view(['GET']) @api_view(["GET"])
def api_root(request, format=None): def api_root(request, format=None):
return Response({ return Response(
'users': reverse('user-list', request=request, format=format), {
'snippets': reverse('snippet-list', request=request, format=format) "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`. 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: 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): class SnippetHighlight(generics.GenericAPIView):
snippet = self.get_object() queryset = Snippet.objects.all()
return Response(snippet.highlighted) 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. 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`: 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: And then add a url pattern for the snippet highlights:
path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view()), ```python
path("snippets/<int:pk>/highlight/", views.SnippetHighlight.as_view()),
```
## Hyperlinking our API ## 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: We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add:
class SnippetSerializer(serializers.HyperlinkedModelSerializer): ```python
owner = serializers.ReadOnlyField(source='owner.username') class SnippetSerializer(serializers.HyperlinkedModelSerializer):
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') owner = serializers.ReadOnlyField(source="owner.username")
highlight = serializers.HyperlinkedIdentityField(
view_name="snippet-highlight", format="html"
)
class Meta: class Meta:
model = Snippet model = Snippet
fields = ['url', 'id', 'highlight', 'owner', fields = [
'title', 'code', 'linenos', 'language', 'style'] "url",
"id",
"highlight",
"owner",
"title",
"code",
"linenos",
"language",
"style",
]
class UserSerializer(serializers.HyperlinkedModelSerializer): class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True) snippets = serializers.HyperlinkedRelatedField(
many=True, view_name="snippet-detail", read_only=True
)
class Meta: class Meta:
model = User model = User
fields = ['url', 'id', 'username', 'snippets'] 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. 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: 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: 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. 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: After adding all those names into our URLconf, our final `snippets/urls.py` file should look like this:
from django.urls import path ```python
from rest_framework.urlpatterns import format_suffix_patterns from django.urls import path
from snippets import views from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
# API endpoints # API endpoints
urlpatterns = format_suffix_patterns([ urlpatterns = format_suffix_patterns(
path('', views.api_root), [
path('snippets/', path("", views.api_root),
views.SnippetList.as_view(), path("snippets/", views.SnippetList.as_view(), name="snippet-list"),
name='snippet-list'), path(
path('snippets/<int:pk>/', "snippets/<int:pk>/", views.SnippetDetail.as_view(), name="snippet-detail"
views.SnippetDetail.as_view(), ),
name='snippet-detail'), path(
path('snippets/<int:pk>/highlight/', "snippets/<int:pk>/highlight/",
views.SnippetHighlight.as_view(), views.SnippetHighlight.as_view(),
name='snippet-highlight'), name="snippet-highlight",
path('users/', ),
views.UserList.as_view(), path("users/", views.UserList.as_view(), name="user-list"),
name='user-list'), path("users/<int:pk>/", views.UserDetail.as_view(), name="user-detail"),
path('users/<int:pk>/', ]
views.UserDetail.as_view(), )
name='user-detail') ```
])
## Adding pagination ## 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: We can change the default list style to use pagination, by modifying our `tutorial/settings.py` file slightly. Add the following setting:
REST_FRAMEWORK = { ```python
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', REST_FRAMEWORK = {
'PAGE_SIZE': 10 "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. 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.

View File

@ -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: 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): class UserViewSet(viewsets.ReadOnlyModelViewSet):
""" """
This viewset automatically provides `list` and `retrieve` actions. This viewset automatically provides `list` and `retrieve` actions.
""" """
queryset = User.objects.all()
serializer_class = UserSerializer 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. 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. 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 ```python
from rest_framework import renderers from rest_framework import permissions
from rest_framework.decorators import action from rest_framework import renderers
from rest_framework.response import Response from rest_framework.decorators import action
from rest_framework.response import Response
class SnippetViewSet(viewsets.ModelViewSet): class SnippetViewSet(viewsets.ModelViewSet):
""" """
This ViewSet automatically provides `list`, `create`, `retrieve`, This ViewSet automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions. `update` and `destroy` actions.
Additionally we also provide an extra `highlight` action. Additionally we also provide an extra `highlight` action.
""" """
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly]
@action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer]) queryset = Snippet.objects.all()
def highlight(self, request, *args, **kwargs): serializer_class = SnippetSerializer
snippet = self.get_object() permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
return Response(snippet.highlighted)
def perform_create(self, serializer): @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer])
serializer.save(owner=self.request.user) 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. 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. 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({ snippet_list = SnippetViewSet.as_view({"get": "list", "post": "create"})
'get': 'list', snippet_detail = SnippetViewSet.as_view(
'post': 'create' {"get": "retrieve", "put": "update", "patch": "partial_update", "delete": "destroy"}
}) )
snippet_detail = SnippetViewSet.as_view({ snippet_highlight = SnippetViewSet.as_view(
'get': 'retrieve', {"get": "highlight"}, renderer_classes=[renderers.StaticHTMLRenderer]
'put': 'update', )
'patch': 'partial_update', user_list = UserViewSet.as_view({"get": "list"})
'delete': 'destroy' user_detail = UserViewSet.as_view({"get": "retrieve"})
}) ```
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. 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. 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([ ```python
path('', api_root), urlpatterns = format_suffix_patterns(
path('snippets/', snippet_list, name='snippet-list'), [
path('snippets/<int:pk>/', snippet_detail, name='snippet-detail'), path("", api_root),
path('snippets/<int:pk>/highlight/', snippet_highlight, name='snippet-highlight'), path("snippets/", snippet_list, name="snippet-list"),
path('users/', user_list, name='user-list'), path("snippets/<int:pk>/", snippet_detail, name="snippet-detail"),
path('users/<int:pk>/', user_detail, name='user-detail') path(
]) "snippets/<int:pk>/highlight/", snippet_highlight, name="snippet-highlight"
),
path("users/", user_list, name="user-list"),
path("users/<int:pk>/", user_detail, name="user-detail"),
]
)
```
## Using Routers ## 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. Here's our re-wired `snippets/urls.py` file.
from django.urls import path, include ```python
from rest_framework.routers import DefaultRouter 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. # Create a router and register our ViewSets with it.
router = DefaultRouter() router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet, basename='snippet') router.register(r"snippets", views.SnippetViewSet, basename="snippet")
router.register(r'users', views.UserViewSet, basename='user') router.register(r"users", views.UserViewSet, basename="user")
# The API URLs are now determined automatically by the router. # The API URLs are now determined automatically by the router.
urlpatterns = [ urlpatterns = [
path('', include(router.urls)), 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. 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.

View File

@ -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 a new Django project named `tutorial`, then start a new app called `quickstart`.
# Create the project directory ```bash
mkdir tutorial # Create the project directory
cd tutorial mkdir tutorial
cd tutorial
# Create a virtual environment to isolate our package dependencies locally # Create a virtual environment to isolate our package dependencies locally
python3 -m venv env python3 -m venv env
source env/bin/activate # On Windows use `env\Scripts\activate` source env/bin/activate # On Windows use `env\Scripts\activate`
# Install Django and Django REST framework into the virtual environment # Install Django and Django REST framework into the virtual environment
pip install djangorestframework pip install djangorestframework
# Set up a new project with a single application # Set up a new project with a single application
django-admin startproject tutorial . # Note the trailing '.' character django-admin startproject tutorial . # Note the trailing '.' character
cd tutorial cd tutorial
django-admin startapp quickstart django-admin startapp quickstart
cd .. cd ..
```
The project layout should look like: The project layout should look like:
$ pwd ```bash
<some path>/tutorial $ pwd
$ find . <some path>/tutorial
. $ find .
./tutorial .
./tutorial/asgi.py ./tutorial
./tutorial/__init__.py ./tutorial/asgi.py
./tutorial/quickstart ./tutorial/__init__.py
./tutorial/quickstart/migrations ./tutorial/quickstart
./tutorial/quickstart/migrations/__init__.py ./tutorial/quickstart/migrations
./tutorial/quickstart/models.py ./tutorial/quickstart/migrations/__init__.py
./tutorial/quickstart/__init__.py ./tutorial/quickstart/models.py
./tutorial/quickstart/apps.py ./tutorial/quickstart/__init__.py
./tutorial/quickstart/admin.py ./tutorial/quickstart/apps.py
./tutorial/quickstart/tests.py ./tutorial/quickstart/admin.py
./tutorial/quickstart/views.py ./tutorial/quickstart/tests.py
./tutorial/settings.py ./tutorial/quickstart/views.py
./tutorial/urls.py ./tutorial/settings.py
./tutorial/wsgi.py ./tutorial/urls.py
./env ./tutorial/wsgi.py
./env/... ./env
./manage.py ./env/...
./manage.py
```
It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart). It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart).
Now sync your database for the first time: 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. 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... 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. 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 ```python
from rest_framework import serializers from django.contrib.auth.models import Group, User
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer): class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = User model = User
fields = ['url', 'username', 'email', 'groups'] fields = ["url", "username", "email", "groups"]
class GroupSerializer(serializers.HyperlinkedModelSerializer): class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = Group model = Group
fields = ['url', 'name'] 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. 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. Right, we'd better write some views then. Open `tutorial/quickstart/views.py` and get typing.
from django.contrib.auth.models import Group, User ```python
from rest_framework import permissions, viewsets 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): class UserViewSet(viewsets.ModelViewSet):
""" """
API endpoint that allows users to be viewed or edited. API endpoint that allows users to be viewed or edited.
""" """
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer queryset = User.objects.all().order_by("-date_joined")
permission_classes = [permissions.IsAuthenticated] serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class GroupViewSet(viewsets.ModelViewSet): class GroupViewSet(viewsets.ModelViewSet):
""" """
API endpoint that allows groups to be viewed or edited. API endpoint that allows groups to be viewed or edited.
""" """
queryset = Group.objects.all().order_by('name')
serializer_class = GroupSerializer queryset = Group.objects.all().order_by("name")
permission_classes = [permissions.IsAuthenticated] serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticated]
```
Rather than write multiple views we're grouping together all the common behavior into classes called `ViewSets`. 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`... Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
from django.urls import include, path ```python
from rest_framework import routers 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 = routers.DefaultRouter()
router.register(r'users', views.UserViewSet) router.register(r"users", views.UserViewSet)
router.register(r'groups', views.GroupViewSet) router.register(r"groups", views.GroupViewSet)
# Wire up our API using automatic URL routing. # Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API. # Additionally, we include login URLs for the browsable API.
urlpatterns = [ urlpatterns = [
path('', include(router.urls)), path("", include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) 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. 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. 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
Pagination allows you to control how many objects per page are returned. To enable it add the following lines to `tutorial/settings.py` 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 = { ```python
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', REST_FRAMEWORK = {
'PAGE_SIZE': 10 "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
} "PAGE_SIZE": 10,
}
```
## Settings ## Settings
Add `'rest_framework'` to `INSTALLED_APPS`. The settings module will be in `tutorial/settings.py` Add `'rest_framework'` to `INSTALLED_APPS`. The settings module will be in `tutorial/settings.py`
INSTALLED_APPS = [ ```text
... INSTALLED_APPS = [
'rest_framework', ...
] 'rest_framework',
]
```
Okay, we're done. 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. 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`... 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/ ```bash
Enter host password for user 'admin': 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, "count": 1,
"previous": null, "next": null,
"results": [ "previous": null,
{ "results": [
"url": "http://127.0.0.1:8000/users/1/", {
"username": "admin", "url": "http://127.0.0.1:8000/users/1/",
"email": "admin@example.com", "username": "admin",
"groups": [] "email": "admin@example.com",
} "groups": []
] }
} ]
}
```
Or using the [httpie][httpie], command line tool... Or using the [httpie][httpie], command line tool...
bash: http -a admin http://127.0.0.1:8000/users/ ```bash
http: password for admin@127.0.0.1:8000:: bash: http -a admin http://127.0.0.1:8000/users/
$HTTP/1.1 200 OK http: password for admin@127.0.0.1:8000::
... $HTTP/1.1 200 OK
{ ...
"count": 1, {
"next": null, "count": 1,
"previous": null, "next": null,
"results": [ "previous": null,
{ "results": [
"email": "admin@example.com", {
"groups": [], "email": "admin@example.com",
"url": "http://127.0.0.1:8000/users/1/", "groups": [],
"username": "admin" "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/`... Or directly through the browser, by going to the URL `http://127.0.0.1:8000/users/`...

79
pyproject.toml Normal file
View File

@ -0,0 +1,79 @@
[build-system]
build-backend = "setuptools.build_meta"
requires = [ "setuptools>=77.0.3" ]
[project]
name = "djangorestframework"
description = "Web APIs for Django, made easy."
readme = "README.md"
license = "BSD-3-Clause"
authors = [ { name = "Tom Christie", email = "tom@tomchristie.com" } ]
requires-python = ">=3.10"
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Django",
"Framework :: Django :: 4.2",
"Framework :: Django :: 5.0",
"Framework :: Django :: 5.1",
"Framework :: Django :: 5.2",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.10",
"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" ]
dependencies = [ "django>=4.2" ]
urls.Changelog = "https://www.django-rest-framework.org/community/release-notes/"
urls.Funding = "https://fund.django-rest-framework.org/topics/funding/"
urls.Homepage = "https://www.django-rest-framework.org"
urls.Source = "https://github.com/encode/django-rest-framework"
[tool.setuptools]
[tool.setuptools.dynamic]
version = { attr = "rest_framework.__version__" }
[tool.setuptools.packages.find]
include = [ "rest_framework*" ]
[tool.isort]
skip = [ ".tox" ]
atomic = true
multi_line_output = 5
extra_standard_library = [ "types" ]
known_third_party = [ "pytest", "_pytest", "django", "pytz", "uritemplate" ]
known_first_party = [ "rest_framework", "tests" ]
[tool.codespell]
# Ref: https://github.com/codespell-project/codespell#using-a-config-file
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" ]
filterwarnings = [ "ignore:CoreAPI compatibility is deprecated*:rest_framework.RemovedInDRF317Warning" ]
[tool.coverage.run]
# NOTE: source is ignored with pytest-cov (but uses the same).
source = [ "." ]
include = [ "rest_framework/*", "tests/*" ]
branch = true
[tool.coverage.report]
include = [ "rest_framework/*", "tests/*" ]
exclude_lines = [
"pragma: no cover",
"raise NotImplementedError",
]

View File

@ -10,7 +10,7 @@ ______ _____ _____ _____ __
__title__ = 'Django REST framework' __title__ = 'Django REST framework'
__version__ = '3.16.1' __version__ = '3.16.1'
__author__ = 'Tom Christie' __author__ = 'Tom Christie'
__license__ = 'BSD 3-Clause' __license__ = 'BSD-3-Clause'
__copyright__ = 'Copyright 2011-2023 Encode OSS Ltd' __copyright__ = 'Copyright 2011-2023 Encode OSS Ltd'
# Version synonym # Version synonym

View File

@ -70,6 +70,15 @@ def api_view(http_method_names=None):
WrappedAPIView.permission_classes = getattr(func, 'permission_classes', WrappedAPIView.permission_classes = getattr(func, 'permission_classes',
APIView.permission_classes) APIView.permission_classes)
WrappedAPIView.content_negotiation_class = getattr(func, 'content_negotiation_class',
APIView.content_negotiation_class)
WrappedAPIView.metadata_class = getattr(func, 'metadata_class',
APIView.metadata_class)
WrappedAPIView.versioning_class = getattr(func, "versioning_class",
APIView.versioning_class)
WrappedAPIView.schema = getattr(func, 'schema', WrappedAPIView.schema = getattr(func, 'schema',
APIView.schema) APIView.schema)
@ -113,6 +122,27 @@ def permission_classes(permission_classes):
return decorator return decorator
def content_negotiation_class(content_negotiation_class):
def decorator(func):
func.content_negotiation_class = content_negotiation_class
return func
return decorator
def metadata_class(metadata_class):
def decorator(func):
func.metadata_class = metadata_class
return func
return decorator
def versioning_class(versioning_class):
def decorator(func):
func.versioning_class = versioning_class
return func
return decorator
def schema(view_inspector): def schema(view_inspector):
def decorator(func): def decorator(func):
func.schema = view_inspector func.schema = view_inspector

View File

@ -1,21 +1,21 @@
# SOME DESCRIPTIVE TITLE. # SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package. # This file is distributed under the same license as the PACKAGE package.
# #
# Translators: # Translators:
# Erwann Mest <m+transifex@kud.io>, 2019 # Erwann Mest <m+transifex@kud.io>, 2019
# Etienne Desgagné <etienne.desgagne@evimbec.ca>, 2015 # Etienne Desgagné <etienne.desgagne@evimbec.ca>, 2015
# Martin Maillard <martin.maillard@gmail.com>, 2015 # Martin Maillard <martin.maillard@gmail.com>, 2015
# Martin Maillard <martin.maillard@gmail.com>, 2015
# Stéphane Raimbault <stephane.raimbault@gmail.com>, 2019 # Stéphane Raimbault <stephane.raimbault@gmail.com>, 2019
# Xavier Ordoquy <xordoquy@linovia.com>, 2015-2016 # Xavier Ordoquy <xordoquy@linovia.com>, 2015-2016
# Sébastien Corbin <seb.corbin@gmail.com>, 2025
msgid "" msgid ""
msgstr "" msgstr ""
"Project-Id-Version: Django REST framework\n" "Project-Id-Version: Django REST framework\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-10-13 21:45+0200\n" "POT-Creation-Date: 2020-10-13 21:45+0200\n"
"PO-Revision-Date: 2020-10-13 19:45+0000\n" "PO-Revision-Date: 2025-08-17 20:30+0200\n"
"Last-Translator: Xavier Ordoquy <xordoquy@linovia.com>\n" "Last-Translator: Sébastien Corbin <seb.corbin@gmail.com>\n"
"Language-Team: French (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/fr/)\n" "Language-Team: French (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/fr/)\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n" "Content-Type: text/plain; charset=UTF-8\n"
@ -52,8 +52,7 @@ msgid "Invalid token header. Token string should not contain spaces."
msgstr "En-tête « token » non valide. Un token ne doit pas contenir d'espaces." msgstr "En-tête « token » non valide. Un token ne doit pas contenir d'espaces."
#: authentication.py:193 #: authentication.py:193
msgid "" msgid "Invalid token header. Token string should not contain invalid characters."
"Invalid token header. Token string should not contain invalid characters."
msgstr "En-tête « token » non valide. Un token ne doit pas contenir de caractères invalides." msgstr "En-tête « token » non valide. Un token ne doit pas contenir de caractères invalides."
#: authentication.py:203 #: authentication.py:203
@ -106,11 +105,11 @@ msgstr "Une erreur du serveur est survenue."
#: exceptions.py:142 #: exceptions.py:142
msgid "Invalid input." msgid "Invalid input."
msgstr "" msgstr "Entrée invalide."
#: exceptions.py:161 #: exceptions.py:161
msgid "Malformed request." msgid "Malformed request."
msgstr "Requête malformée" msgstr "Requête malformée."
#: exceptions.py:167 #: exceptions.py:167
msgid "Incorrect authentication credentials." msgid "Incorrect authentication credentials."
@ -149,12 +148,12 @@ msgstr "Requête ralentie."
#: exceptions.py:224 #: exceptions.py:224
#, python-brace-format #, python-brace-format
msgid "Expected available in {wait} second." msgid "Expected available in {wait} second."
msgstr "" msgstr "Disponible à nouveau dans {wait} seconde."
#: exceptions.py:225 #: exceptions.py:225
#, python-brace-format #, python-brace-format
msgid "Expected available in {wait} seconds." msgid "Expected available in {wait} seconds."
msgstr "" msgstr "Disponible à nouveau dans {wait} secondes."
#: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: fields.py:316 relations.py:245 relations.py:279 validators.py:90
#: validators.py:183 #: validators.py:183
@ -167,11 +166,11 @@ msgstr "Ce champ ne peut être nul."
#: fields.py:701 #: fields.py:701
msgid "Must be a valid boolean." msgid "Must be a valid boolean."
msgstr "" msgstr "Doit être un booléen valide."
#: fields.py:766 #: fields.py:766
msgid "Not a valid string." msgid "Not a valid string."
msgstr "" msgstr "Chaîne de charactère invalide."
#: fields.py:767 #: fields.py:767
msgid "This field may not be blank." msgid "This field may not be blank."
@ -196,16 +195,12 @@ msgid "This value does not match the required pattern."
msgstr "Cette valeur ne satisfait pas le motif imposé." msgstr "Cette valeur ne satisfait pas le motif imposé."
#: fields.py:838 #: fields.py:838
msgid "" msgid "Enter a valid \"slug\" consisting of letters, numbers, underscores or hyphens."
"Enter a valid \"slug\" consisting of letters, numbers, underscores or "
"hyphens."
msgstr "Ce champ ne doit contenir que des lettres, des nombres, des tirets bas _ et des traits d'union." msgstr "Ce champ ne doit contenir que des lettres, des nombres, des tirets bas _ et des traits d'union."
#: fields.py:839 #: fields.py:839
msgid "" msgid "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, or hyphens."
"Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " msgstr "Ce champ ne doit contenir que des lettres Unicode, des nombres, des tirets bas _ et des traits d'union."
"or hyphens."
msgstr ""
#: fields.py:854 #: fields.py:854
msgid "Enter a valid URL." msgid "Enter a valid URL."
@ -213,7 +208,7 @@ msgstr "Saisissez une URL valide."
#: fields.py:867 #: fields.py:867
msgid "Must be a valid UUID." msgid "Must be a valid UUID."
msgstr "" msgstr "Doit être un UUID valide."
#: fields.py:903 #: fields.py:903
msgid "Enter a valid IPv4 or IPv6 address." msgid "Enter a valid IPv4 or IPv6 address."
@ -226,7 +221,7 @@ msgstr "Un nombre entier valide est requis."
#: fields.py:932 fields.py:969 fields.py:1005 fields.py:1366 #: fields.py:932 fields.py:969 fields.py:1005 fields.py:1366
#, python-brace-format #, python-brace-format
msgid "Ensure this value is less than or equal to {max_value}." msgid "Ensure this value is less than or equal to {max_value}."
msgstr "Assurez-vous que cette valeur est inférieure ou égale à {max_value}." msgstr "Assurez-vous que cette valeur est inférieure ou égale à {max_value}."
#: fields.py:933 fields.py:970 fields.py:1006 fields.py:1367 #: fields.py:933 fields.py:970 fields.py:1006 fields.py:1367
#, python-brace-format #, python-brace-format
@ -248,15 +243,12 @@ msgstr "Assurez-vous qu'il n'y a pas plus de {max_digits} chiffres au total."
#: fields.py:1008 #: fields.py:1008
#, python-brace-format #, python-brace-format
msgid "" msgid "Ensure that there are no more than {max_decimal_places} decimal places."
"Ensure that there are no more than {max_decimal_places} decimal places."
msgstr "Assurez-vous qu'il n'y a pas plus de {max_decimal_places} chiffres après la virgule." msgstr "Assurez-vous qu'il n'y a pas plus de {max_decimal_places} chiffres après la virgule."
#: fields.py:1009 #: fields.py:1009
#, python-brace-format #, python-brace-format
msgid "" msgid "Ensure that there are no more than {max_whole_digits} digits before the decimal point."
"Ensure that there are no more than {max_whole_digits} digits before the "
"decimal point."
msgstr "Assurez-vous qu'il n'y a pas plus de {max_whole_digits} chiffres avant la virgule." msgstr "Assurez-vous qu'il n'y a pas plus de {max_whole_digits} chiffres avant la virgule."
#: fields.py:1148 #: fields.py:1148
@ -271,11 +263,11 @@ msgstr "Attendait une date + heure mais a reçu une date."
#: fields.py:1150 #: fields.py:1150
#, python-brace-format #, python-brace-format
msgid "Invalid datetime for the timezone \"{timezone}\"." msgid "Invalid datetime for the timezone \"{timezone}\"."
msgstr "" msgstr "Date et heure non valides pour le fuseau horaire \"{timezone}\"."
#: fields.py:1151 #: fields.py:1151
msgid "Datetime value out of range." msgid "Datetime value out of range."
msgstr "" msgstr "Valeur de date et heure hors de l'intervalle."
#: fields.py:1236 #: fields.py:1236
#, python-brace-format #, python-brace-format
@ -325,8 +317,7 @@ msgid "No file was submitted."
msgstr "Aucun fichier n'a été soumis." msgstr "Aucun fichier n'a été soumis."
#: fields.py:1515 #: fields.py:1515
msgid "" msgid "The submitted data was not a file. Check the encoding type on the form."
"The submitted data was not a file. Check the encoding type on the form."
msgstr "La donnée soumise n'est pas un fichier. Vérifiez le type d'encodage du formulaire." msgstr "La donnée soumise n'est pas un fichier. Vérifiez le type d'encodage du formulaire."
#: fields.py:1516 #: fields.py:1516
@ -339,14 +330,11 @@ msgstr "Le fichier soumis est vide."
#: fields.py:1518 #: fields.py:1518
#, python-brace-format #, python-brace-format
msgid "" msgid "Ensure this filename has at most {max_length} characters (it has {length})."
"Ensure this filename has at most {max_length} characters (it has {length})."
msgstr "Assurez-vous que le nom de fichier comporte au plus {max_length} caractères (il en comporte {length})." msgstr "Assurez-vous que le nom de fichier comporte au plus {max_length} caractères (il en comporte {length})."
#: fields.py:1566 #: fields.py:1566
msgid "" msgid "Upload a valid image. The file you uploaded was either not an image or a corrupted image."
"Upload a valid image. The file you uploaded was either not an image or a "
"corrupted image."
msgstr "Transférez une image valide. Le fichier que vous avez transféré n'est pas une image, ou il est corrompu." msgstr "Transférez une image valide. Le fichier que vous avez transféré n'est pas une image, ou il est corrompu."
#: fields.py:1604 relations.py:486 serializers.py:571 #: fields.py:1604 relations.py:486 serializers.py:571
@ -356,12 +344,12 @@ msgstr "Cette liste ne peut pas être vide."
#: fields.py:1605 #: fields.py:1605
#, python-brace-format #, python-brace-format
msgid "Ensure this field has at least {min_length} elements." msgid "Ensure this field has at least {min_length} elements."
msgstr "" msgstr "Vérifier que ce champ a au moins {min_length} éléments."
#: fields.py:1606 #: fields.py:1606
#, python-brace-format #, python-brace-format
msgid "Ensure this field has no more than {max_length} elements." msgid "Ensure this field has no more than {max_length} elements."
msgstr "" msgstr "Vérifier que ce champ n'a pas plus de {max_length} éléments."
#: fields.py:1682 #: fields.py:1682
#, python-brace-format #, python-brace-format
@ -370,7 +358,7 @@ msgstr "Attendait un dictionnaire d'éléments mais a reçu « {input_type} »
#: fields.py:1683 #: fields.py:1683
msgid "This dictionary may not be empty." msgid "This dictionary may not be empty."
msgstr "" msgstr "Ce dictionnaire ne peut être vide."
#: fields.py:1755 #: fields.py:1755
msgid "Value must be valid JSON." msgid "Value must be valid JSON."
@ -382,7 +370,7 @@ msgstr "Recherche"
#: filters.py:50 #: filters.py:50
msgid "A search term." msgid "A search term."
msgstr "" msgstr "Un terme de recherche."
#: filters.py:180 templates/rest_framework/filters/ordering.html:3 #: filters.py:180 templates/rest_framework/filters/ordering.html:3
msgid "Ordering" msgid "Ordering"
@ -390,7 +378,7 @@ msgstr "Ordre"
#: filters.py:181 #: filters.py:181
msgid "Which field to use when ordering the results." msgid "Which field to use when ordering the results."
msgstr "" msgstr "Quel champ utiliser pour classer les résultats."
#: filters.py:287 #: filters.py:287
msgid "ascending" msgid "ascending"
@ -402,11 +390,11 @@ msgstr "décroissant"
#: pagination.py:174 #: pagination.py:174
msgid "A page number within the paginated result set." msgid "A page number within the paginated result set."
msgstr "" msgstr "Un numéro de page de l'ensemble des résultats."
#: pagination.py:179 pagination.py:372 pagination.py:590 #: pagination.py:179 pagination.py:372 pagination.py:590
msgid "Number of results to return per page." msgid "Number of results to return per page."
msgstr "" msgstr "Nombre de résultats à retourner par page."
#: pagination.py:189 #: pagination.py:189
msgid "Invalid page." msgid "Invalid page."
@ -414,11 +402,11 @@ msgstr "Page non valide."
#: pagination.py:374 #: pagination.py:374
msgid "The initial index from which to return the results." msgid "The initial index from which to return the results."
msgstr "" msgstr "L'index initial depuis lequel retourner les résultats."
#: pagination.py:581 #: pagination.py:581
msgid "The pagination cursor value." msgid "The pagination cursor value."
msgstr "" msgstr "La valeur du curseur de pagination."
#: pagination.py:583 #: pagination.py:583
msgid "Invalid cursor" msgid "Invalid cursor"
@ -454,7 +442,7 @@ msgstr "Type incorrect. Attendait une URL, a reçu {data_type}."
#: relations.py:448 #: relations.py:448
#, python-brace-format #, python-brace-format
msgid "Object with {slug_name}={value} does not exist." msgid "Object with {slug_name}={value} does not exist."
msgstr "L'object avec {slug_name}={value} n'existe pas." msgstr "L'objet avec {slug_name}={value} n'existe pas."
#: relations.py:449 #: relations.py:449
msgid "Invalid value." msgid "Invalid value."
@ -462,20 +450,20 @@ msgstr "Valeur non valide."
#: schemas/utils.py:32 #: schemas/utils.py:32
msgid "unique integer value" msgid "unique integer value"
msgstr "" msgstr "valeur entière unique"
#: schemas/utils.py:34 #: schemas/utils.py:34
msgid "UUID string" msgid "UUID string"
msgstr "" msgstr "Chaîne UUID"
#: schemas/utils.py:36 #: schemas/utils.py:36
msgid "unique value" msgid "unique value"
msgstr "" msgstr "valeur unique"
#: schemas/utils.py:38 #: schemas/utils.py:38
#, python-brace-format #, python-brace-format
msgid "A {value_type} identifying this {name}." msgid "A {value_type} identifying this {name}."
msgstr "" msgstr "Un(une) {value_type} identifiant ce(cette) {name}."
#: serializers.py:337 #: serializers.py:337
#, python-brace-format #, python-brace-format
@ -485,7 +473,7 @@ msgstr "Donnée non valide. Attendait un dictionnaire, a reçu {datatype}."
#: templates/rest_framework/admin.html:116 #: templates/rest_framework/admin.html:116
#: templates/rest_framework/base.html:136 #: templates/rest_framework/base.html:136
msgid "Extra Actions" msgid "Extra Actions"
msgstr "" msgstr "Actions supplémentaires"
#: templates/rest_framework/admin.html:130 #: templates/rest_framework/admin.html:130
#: templates/rest_framework/base.html:150 #: templates/rest_framework/base.html:150
@ -494,27 +482,27 @@ msgstr "Filtres"
#: templates/rest_framework/base.html:37 #: templates/rest_framework/base.html:37
msgid "navbar" msgid "navbar"
msgstr "" msgstr "barre de navigation"
#: templates/rest_framework/base.html:75 #: templates/rest_framework/base.html:75
msgid "content" msgid "content"
msgstr "" msgstr "contenu"
#: templates/rest_framework/base.html:78 #: templates/rest_framework/base.html:78
msgid "request form" msgid "request form"
msgstr "" msgstr "formulaire de requête"
#: templates/rest_framework/base.html:157 #: templates/rest_framework/base.html:157
msgid "main content" msgid "main content"
msgstr "" msgstr "contenu principal"
#: templates/rest_framework/base.html:173 #: templates/rest_framework/base.html:173
msgid "request info" msgid "request info"
msgstr "" msgstr "information de la requête"
#: templates/rest_framework/base.html:177 #: templates/rest_framework/base.html:177
msgid "response info" msgid "response info"
msgstr "" msgstr "information de la réponse"
#: templates/rest_framework/horizontal/radio.html:4 #: templates/rest_framework/horizontal/radio.html:4
#: templates/rest_framework/inline/radio.html:3 #: templates/rest_framework/inline/radio.html:3
@ -540,7 +528,7 @@ msgstr "Les champs {field_names} doivent former un ensemble unique."
#: validators.py:171 #: validators.py:171
#, python-brace-format #, python-brace-format
msgid "Surrogate characters are not allowed: U+{code_point:X}." msgid "Surrogate characters are not allowed: U+{code_point:X}."
msgstr "" msgstr "Les caractères de substitution ne sont pas autorisés : U+{code_point:X}."
#: validators.py:243 #: validators.py:243
#, python-brace-format #, python-brace-format

View File

@ -1090,6 +1090,13 @@ class ModelSerializer(Serializer):
# Determine the fields that should be included on the serializer. # Determine the fields that should be included on the serializer.
fields = {} 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: for field_name in field_names:
# If the field is explicitly declared on the class then use that. # If the field is explicitly declared on the class then use that.
if field_name in declared_fields: if field_name in declared_fields:
@ -1569,6 +1576,17 @@ class ModelSerializer(Serializer):
self.get_unique_for_date_validators() 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): def get_unique_together_validators(self):
""" """
Determine a default set of validators for any unique_together constraints. Determine a default set of validators for any unique_together constraints.
@ -1595,6 +1613,13 @@ class ModelSerializer(Serializer):
for name, source in field_sources.items(): for name, source in field_sources.items():
source_map[source].append(name) 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 # Note that we make sure to check `unique_together` both on the
# base model class, but also on any parent classes. # base model class, but also on any parent classes.
validators = [] validators = []
@ -1621,11 +1646,17 @@ class ModelSerializer(Serializer):
) )
field_names = tuple(source_map[f][0] for f in unique_together) 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( validator = UniqueTogetherValidator(
queryset=queryset, queryset=queryset,
fields=field_names, fields=field_names,
condition_fields=tuple(source_map[f][0] for f in condition_fields), condition_fields=tuple(source_map[f][0] for f in condition_fields),
condition=condition, condition=condition,
message=violation_error_message,
code=getattr(constraint, 'violation_error_code', None),
) )
validators.append(validator) validators.append(validator)
return validators return validators

View File

@ -111,13 +111,15 @@ class UniqueTogetherValidator:
message = _('The fields {field_names} must make a unique set.') message = _('The fields {field_names} must make a unique set.')
missing_message = _('This field is required.') missing_message = _('This field is required.')
requires_context = True 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.queryset = queryset
self.fields = fields self.fields = fields
self.message = message or self.message self.message = message or self.message
self.condition_fields = [] if condition_fields is None else condition_fields self.condition_fields = [] if condition_fields is None else condition_fields
self.condition = condition self.condition = condition
self.code = code or self.code
def enforce_required_fields(self, attrs, serializer): 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): if checked_values and None not in checked_values and qs_exists_with_condition(queryset, self.condition, condition_kwargs):
field_names = ', '.join(self.fields) field_names = ', '.join(self.fields)
message = self.message.format(field_names=field_names) message = self.message.format(field_names=field_names)
raise ValidationError(message, code='unique') raise ValidationError(message, code=self.code)
def __repr__(self): def __repr__(self):
return '<{}({})>'.format( return '<{}({})>'.format(
@ -217,6 +219,7 @@ class UniqueTogetherValidator:
and self.missing_message == other.missing_message and self.missing_message == other.missing_message
and self.queryset == other.queryset and self.queryset == other.queryset
and self.fields == other.fields and self.fields == other.fields
and self.code == other.code
) )

View File

@ -1,36 +1,3 @@
[metadata]
license_files = LICENSE.md
[tool:pytest]
addopts=--tb=short --strict-markers -ra
testpaths = tests
filterwarnings = ignore:CoreAPI compatibility is deprecated*:rest_framework.RemovedInDRF317Warning
[flake8] [flake8]
ignore = E501,W503,W504 ignore = E501,W503,W504
banned-modules = json = use from rest_framework.utils import json! banned-modules = json = use from rest_framework.utils import json!
[isort]
skip=.tox
atomic=true
multi_line_output=5
extra_standard_library=types
known_third_party=pytest,_pytest,django,pytz,uritemplate
known_first_party=rest_framework,tests
[coverage:run]
# NOTE: source is ignored with pytest-cov (but uses the same).
source = .
include = rest_framework/*,tests/*
branch = 1
[coverage:report]
include = rest_framework/*,tests/*
exclude_lines =
pragma: no cover
raise NotImplementedError
[codespell]
# Ref: https://github.com/codespell-project/codespell#using-a-config-file
skip = */kickstarter-announcement.md,*.js,*.map,*.po
ignore-words-list = fo,malcom,ser

119
setup.py
View File

@ -1,119 +0,0 @@
import os
import re
import shutil
import sys
from setuptools import find_packages, setup
CURRENT_PYTHON = sys.version_info[:2]
REQUIRED_PYTHON = (3, 9)
# This check and everything above must remain compatible with Python 2.7.
if CURRENT_PYTHON < REQUIRED_PYTHON:
sys.stderr.write("""
==========================
Unsupported Python version
==========================
This version of Django REST Framework requires Python {}.{}, but you're trying
to install it on Python {}.{}.
This may be because you are using a version of pip that doesn't
understand the python_requires classifier. Make sure you
have pip >= 9.0 and setuptools >= 24.2, then try again:
$ python -m pip install --upgrade pip setuptools
$ python -m pip install djangorestframework
This will install the latest version of Django REST Framework which works on
your version of Python. If you can't upgrade your pip (or Python), request
an older version of Django REST Framework:
$ python -m pip install "djangorestframework<3.10"
""".format(*(REQUIRED_PYTHON + CURRENT_PYTHON)))
sys.exit(1)
def read(f):
with open(f, encoding='utf-8') as file:
return file.read()
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = open(os.path.join(package, '__init__.py')).read()
return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
version = get_version('rest_framework')
if sys.argv[-1] == 'publish':
if os.system("pip freeze | grep twine"):
print("twine not installed.\nUse `pip install twine`.\nExiting.")
sys.exit()
os.system("python setup.py sdist bdist_wheel")
if os.system("twine check dist/*"):
print("twine check failed. Packages might be outdated.")
print("Try using `pip install -U twine wheel`.\nExiting.")
sys.exit()
os.system("twine upload dist/*")
print("You probably want to also tag the version now:")
print(" git tag -a %s -m 'version %s'" % (version, version))
print(" git push --tags")
shutil.rmtree('dist')
shutil.rmtree('build')
shutil.rmtree('djangorestframework.egg-info')
sys.exit()
setup(
name='djangorestframework',
version=version,
url='https://www.django-rest-framework.org/',
license='BSD',
description='Web APIs for Django, made easy.',
long_description=read('README.md'),
long_description_content_type='text/markdown',
author='Tom Christie',
author_email='tom@tomchristie.com', # SEE NOTE BELOW (*)
packages=find_packages(exclude=['tests*']),
include_package_data=True,
install_requires=["django>=4.2"],
python_requires=">=3.9",
zip_safe=False,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 4.2',
'Framework :: Django :: 5.0',
'Framework :: Django :: 5.1',
'Framework :: Django :: 5.2',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12',
'Programming Language :: Python :: 3.13',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Internet :: WWW/HTTP',
],
project_urls={
'Funding': 'https://fund.django-rest-framework.org/topics/funding/',
'Source': 'https://github.com/encode/django-rest-framework',
'Changelog': 'https://www.django-rest-framework.org/community/release-notes/',
},
)
# (*) Please direct queries to the discussion group, rather than to me directly
# Doing so helps ensure your question is helpful to other users.
# Queries directly to my email are likely to receive a canned response.
#
# Many thanks for your understanding.

View File

@ -6,9 +6,11 @@ from django.test import TestCase
from rest_framework import status from rest_framework import status
from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import BasicAuthentication
from rest_framework.decorators import ( from rest_framework.decorators import (
action, api_view, authentication_classes, parser_classes, action, api_view, authentication_classes, content_negotiation_class,
permission_classes, renderer_classes, schema, throttle_classes metadata_class, parser_classes, permission_classes, renderer_classes,
schema, throttle_classes, versioning_class
) )
from rest_framework.negotiation import BaseContentNegotiation
from rest_framework.parsers import JSONParser from rest_framework.parsers import JSONParser
from rest_framework.permissions import IsAuthenticated from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import JSONRenderer from rest_framework.renderers import JSONRenderer
@ -16,6 +18,7 @@ from rest_framework.response import Response
from rest_framework.schemas import AutoSchema from rest_framework.schemas import AutoSchema
from rest_framework.test import APIRequestFactory from rest_framework.test import APIRequestFactory
from rest_framework.throttling import UserRateThrottle from rest_framework.throttling import UserRateThrottle
from rest_framework.versioning import QueryParameterVersioning
from rest_framework.views import APIView from rest_framework.views import APIView
@ -150,6 +153,43 @@ class DecoratorTestCase(TestCase):
response = view(request) response = view(request)
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
def test_versioning_class(self):
@api_view(["GET"])
@versioning_class(QueryParameterVersioning)
def view(request):
return Response({"version": request.version})
request = self.factory.get("/?version=1.2.3")
response = view(request)
assert response.data == {"version": "1.2.3"}
def test_metadata_class(self):
# From TestMetadata.test_none_metadata()
@api_view()
@metadata_class(None)
def view(request):
return Response({})
request = self.factory.options('/')
response = view(request)
assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
assert response.data == {'detail': 'Method "OPTIONS" not allowed.'}
def test_content_negotiation(self):
class CustomContentNegotiation(BaseContentNegotiation):
def select_renderer(self, request, renderers, format_suffix):
assert request.META['HTTP_ACCEPT'] == 'custom/type'
return (renderers[0], renderers[0].media_type)
@api_view(["GET"])
@content_negotiation_class(CustomContentNegotiation)
def view(request):
return Response({})
request = self.factory.get('/', HTTP_ACCEPT='custom/type')
response = view(request)
assert response.status_code == status.HTTP_200_OK
def test_schema(self): def test_schema(self):
""" """
Checks CustomSchema class is set on view Checks CustomSchema class is set on view

View File

@ -6,12 +6,14 @@ from collections.abc import Mapping
import pytest import pytest
from django.db import models from django.db import models
from django.test import TestCase
from rest_framework import exceptions, fields, relations, serializers from rest_framework import exceptions, fields, relations, serializers
from rest_framework.fields import Field from rest_framework.fields import Field
from .models import ( from .models import (
ForeignKeyTarget, NestedForeignKeySource, NullableForeignKeySource ForeignKeyTarget, ManyToManySource, ManyToManyTarget,
NestedForeignKeySource, NullableForeignKeySource
) )
from .utils import MockObject from .utils import MockObject
@ -64,6 +66,7 @@ class TestSerializer:
class ExampleSerializer(serializers.Serializer): class ExampleSerializer(serializers.Serializer):
char = serializers.CharField() char = serializers.CharField()
integer = serializers.IntegerField() integer = serializers.IntegerField()
self.Serializer = ExampleSerializer self.Serializer = ExampleSerializer
def test_valid_serializer(self): def test_valid_serializer(self):
@ -774,3 +777,35 @@ class TestSetValueMethod:
ret = {'a': 1} ret = {'a': 1}
self.s.set_value(ret, ['x', 'y'], 2) self.s.set_value(ret, ['x', 'y'], 2)
assert ret == {'a': 1, '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

View File

@ -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 UniqueConstraintSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = UniqueConstraintModel model = UniqueConstraintModel
@ -628,6 +648,12 @@ class UniqueConstraintNullableSerializer(serializers.ModelSerializer):
fields = ('title', 'age', 'tag') fields = ('title', 'age', 'tag')
class UniqueConstraintCustomMessageCodeSerializer(serializers.ModelSerializer):
class Meta:
model = UniqueConstraintCustomMessageCodeModel
fields = ('username', 'company_id', 'role')
class TestUniqueConstraintValidation(TestCase): class TestUniqueConstraintValidation(TestCase):
def setUp(self): def setUp(self):
self.instance = UniqueConstraintModel.objects.create( self.instance = UniqueConstraintModel.objects.create(
@ -778,6 +804,31 @@ class TestUniqueConstraintValidation(TestCase):
) )
assert serializer.is_valid() 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` # Tests for `UniqueForDateValidator`
# ---------------------------------- # ----------------------------------

View File

@ -1,10 +1,10 @@
[tox] [tox]
envlist = envlist =
{py39}-{django42}
{py310}-{django42,django51,django52} {py310}-{django42,django51,django52}
{py311}-{django42,django51,django52} {py311}-{django42,django51,django52}
{py312}-{django42,django51,django52,djangomain} {py312}-{django42,django51,django52,djangomain}
{py313}-{django51,django52,djangomain} {py313}-{django51,django52,djangomain}
{py314}-{django52,djangomain}
base base
dist dist
docs docs
@ -50,3 +50,6 @@ ignore_outcome = true
[testenv:py313-djangomain] [testenv:py313-djangomain]
ignore_outcome = true ignore_outcome = true
[testenv:py314-djangomain]
ignore_outcome = true