Merge branch 'main' into fix/token-auth-username-or-email-login

This commit is contained in:
Asif Saif Uddin {"Auvi":"অভি"} 2025-12-14 15:05:07 +00:00 committed by GitHub
commit eb02ff8940
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
159 changed files with 3854 additions and 2622 deletions

View File

@ -1,17 +0,0 @@
---
name: Issue
about: Please only raise an issue if you've been advised to do so after discussion. Thanks! 🙏
---
## Checklist
<!--
Note: REST framework is considered feature-complete. New functionality should be implemented outside the core REST framework. For details, please check the docs: https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages
-->
- [ ] Raised initially as discussion #...
- [ ] This is not a feature request suitable for implementation outside this project. Please elaborate what it is:
- [ ] compatibility fix for new Django/Python version ...
- [ ] other type of bug fix
- [ ] other type of improvement that does not touch existing code or change existing behavior (e.g. wrapper for new Django field)
- [ ] I have reduced the issue to the simplest possible case.

View File

@ -4,3 +4,4 @@ contact_links:
url: https://github.com/encode/django-rest-framework/discussions
about: >
The "Discussions" forum is where you want to start. 💖
Please note that at this point in its lifespan, we consider Django REST framework to be feature-complete.

View File

@ -3,29 +3,30 @@ name: CI
on:
push:
branches:
- master
- main
pull_request:
jobs:
tests:
name: Python ${{ matrix.python-version }}
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
strategy:
matrix:
python-version:
- '3.9'
- '3.10'
- '3.11'
- '3.12'
- '3.13'
- '3.14'
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- uses: actions/setup-python@v5
- uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
allow-prereleases: true
cache: 'pip'
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 '-')
- name: Run extra tox targets
if: ${{ matrix.python-version == '3.9' }}
if: ${{ matrix.python-version == '3.13' }}
run: |
tox -e base,dist,docs
@ -50,13 +51,13 @@ jobs:
test-docs:
name: Test documentation links
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- uses: actions/setup-python@v5
- uses: actions/setup-python@v6
with:
python-version: '3.9'
python-version: '3.13'
- name: Install dependencies
run: pip install -r requirements/requirements-documentation.txt

29
.github/workflows/mkdocs-deploy.yml vendored Normal file
View File

@ -0,0 +1,29 @@
name: mkdocs
on:
push:
branches:
- main
paths:
- docs/**
- docs_theme/**
- requirements/requirements-documentation.txt
- mkdocs.yml
- .github/workflows/mkdocs-deploy.yml
jobs:
deploy:
runs-on: ubuntu-latest
environment: github-pages
permissions:
contents: write
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
steps:
- uses: actions/checkout@v6
- run: git fetch --no-tags --prune --depth=1 origin gh-pages
- uses: actions/setup-python@v6
with:
python-version: 3.x
- run: pip install -r requirements/requirements-documentation.txt
- run: mkdocs gh-deploy

View File

@ -3,7 +3,7 @@ name: pre-commit
on:
push:
branches:
- master
- main
pull_request:
jobs:
@ -11,11 +11,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: actions/setup-python@v5
- uses: actions/setup-python@v6
with:
python-version: "3.10"

View File

@ -1,6 +1,6 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
rev: v6.0.0
hooks:
- id: check-added-large-files
- id: check-case-conflict
@ -8,26 +8,43 @@ repos:
- id: check-merge-conflict
- id: check-symlinks
- id: check-toml
- repo: https://github.com/pycqa/isort
rev: 5.13.2
- repo: https://github.com/PyCQA/isort
rev: 7.0.0
hooks:
- id: isort
- repo: https://github.com/PyCQA/flake8
rev: 7.0.0
rev: 7.3.0
hooks:
- id: flake8
additional_dependencies:
- flake8-tidy-imports
- flake8-bugbear
- repo: https://github.com/adamchainz/blacken-docs
rev: 1.16.0
rev: 1.20.0
hooks:
- id: blacken-docs
exclude: ^(?!docs).*$
additional_dependencies:
- black==23.1.0
- black==25.9.0
- repo: https://github.com/codespell-project/codespell
# Configuration for codespell is in .codespellrc
rev: v2.2.6
rev: v2.4.1
hooks:
- id: codespell
args: [
"--builtin", "clear,rare,code,names,en-GB_to_en-US",
"--ignore-words", "codespell-ignore-words.txt",
"--skip", "*.css",
]
exclude: locale|kickstarter-announcement.md|coreapi-0.1.1.js
additional_dependencies:
# python doesn't come with a toml parser prior to 3.11
- "tomli; python_version < '3.11'"
- repo: https://github.com/asottile/pyupgrade
rev: v3.21.0
hooks:
- id: pyupgrade
args: ["--py310-plus", "--keep-percent-format"]
- repo: https://github.com/tox-dev/pyproject-fmt
rev: v2.11.0
hooks:
- id: pyproject-fmt

View File

@ -2,6 +2,6 @@
At this point in its lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes.
Apart from minor documentation changes, the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Please only raise an issue or pull request if you've been recommended to do so after discussion.
Apart from minor documentation changes, the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Please only open a pull request if you've been recommended to do so **after discussion**.
The [Contributing guide in the documentation](https://www.django-rest-framework.org/community/contributing/) gives some more information on our process and code of conduct.

View File

@ -1,8 +1,3 @@
include README.md
include LICENSE.md
recursive-include tests/ *
recursive-include rest_framework/static *.js *.css *.map *.png *.ico *.eot *.svg *.ttf *.woff *.woff2
recursive-include rest_framework/templates *.html schema.js
recursive-include rest_framework/locale *.mo
global-exclude __pycache__
global-exclude *.py[co]

View File

@ -10,30 +10,6 @@ Full documentation for the project is available at [https://www.django-rest-fram
---
# Funding
REST framework is a *collaboratively funded project*. If you use
REST framework commercially we strongly encourage you to invest in its
continued development by [signing up for a paid plan][funding].
The initial aim is to provide a single full-time position on REST framework.
*Every single sign-up makes a significant impact towards making that possible.*
[![][sentry-img]][sentry-url]
[![][stream-img]][stream-url]
[![][spacinov-img]][spacinov-url]
[![][retool-img]][retool-url]
[![][bitio-img]][bitio-url]
[![][posthog-img]][posthog-url]
[![][cryptapi-img]][cryptapi-url]
[![][fezto-img]][fezto-url]
[![][svix-img]][svix-url]
[![][zuplo-img]][zuplo-url]
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Spacinov][spacinov-url], [Retool][retool-url], [bit.io][bitio-url], [PostHog][posthog-url], [CryptAPI][cryptapi-url], [FEZTO][fezto-url], [Svix][svix-url], and [Zuplo][zuplo-url].
---
# Overview
Django REST framework is a powerful and flexible toolkit for building Web APIs.
@ -54,8 +30,8 @@ Some reasons you might want to use REST framework:
# Requirements
* Python 3.9+
* Django 4.2, 5.0, 5.1, 5.2
* Python 3.10+
* Django 4.2, 5.0, 5.1, 5.2, 6.0
We **highly recommend** and only officially support the latest patch release of
each Python and Django series.
@ -67,10 +43,11 @@ Install using `pip`...
pip install djangorestframework
Add `'rest_framework'` to your `INSTALLED_APPS` setting.
```python
INSTALLED_APPS = [
...
'rest_framework',
# ...
"rest_framework",
]
```
@ -99,7 +76,7 @@ from rest_framework import routers, serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'is_staff']
fields = ["url", "username", "email", "is_staff"]
# ViewSets define the view behavior.
@ -110,13 +87,13 @@ class UserViewSet(viewsets.ModelViewSet):
# Routers provide a way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r"users", UserViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path("", include(router.urls)),
path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
]
```
@ -126,15 +103,15 @@ Add the following to your `settings.py` module:
```python
INSTALLED_APPS = [
... # Make sure to include the default installed apps here.
'rest_framework',
# ... make sure to include the default installed apps here.
"rest_framework",
]
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly",
]
}
```
@ -179,8 +156,8 @@ Please see the [security policy][security-policy].
[build-status-image]: https://github.com/encode/django-rest-framework/actions/workflows/main.yml/badge.svg
[build-status]: https://github.com/encode/django-rest-framework/actions/workflows/main.yml
[coverage-status-image]: https://img.shields.io/codecov/c/github/encode/django-rest-framework/master.svg
[codecov]: https://codecov.io/github/encode/django-rest-framework?branch=master
[coverage-status-image]: https://img.shields.io/codecov/c/github/encode/django-rest-framework/main.svg
[codecov]: https://codecov.io/github/encode/django-rest-framework?branch=main
[pypi-version]: https://img.shields.io/pypi/v/djangorestframework.svg
[pypi]: https://pypi.org/project/djangorestframework/
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
@ -188,28 +165,6 @@ Please see the [security policy][security-policy].
[funding]: https://fund.django-rest-framework.org/topics/funding/
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[sentry-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/sentry-readme.png
[stream-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/stream-readme.png
[spacinov-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/spacinov-readme.png
[retool-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/retool-readme.png
[bitio-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/bitio-readme.png
[posthog-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/posthog-readme.png
[cryptapi-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cryptapi-readme.png
[fezto-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/fezto-readme.png
[svix-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/svix-premium.png
[zuplo-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/zuplo-readme.png
[sentry-url]: https://getsentry.com/welcome/
[stream-url]: https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage
[spacinov-url]: https://www.spacinov.com/
[retool-url]: https://retool.com/?utm_source=djangorest&utm_medium=sponsorship
[bitio-url]: https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship
[posthog-url]: https://posthog.com?utm_source=drf&utm_medium=sponsorship&utm_campaign=open-source-sponsorship
[cryptapi-url]: https://cryptapi.io
[fezto-url]: https://www.fezto.xyz/?utm_source=DjangoRESTFramework
[svix-url]: https://www.svix.com/?utm_source=django-REST&utm_medium=sponsorship
[zuplo-url]: https://zuplo.link/django-gh
[oauth1-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth
[oauth2-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit
[serializer-section]: https://www.django-rest-framework.org/api-guide/serializers/#serializers

View File

@ -0,0 +1,7 @@
Tim
assertIn
IAM
endcode
deque
thead
lets

View File

@ -19,13 +19,10 @@ The `request.user` property will typically be set to an instance of the `contrib
The `request.auth` property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.
---
!!! note
Don't forget that **authentication by itself won't allow or disallow an incoming request**, it simply identifies the credentials that the request was made with.
**Note:** Don't forget that **authentication by itself won't allow or disallow an incoming request**, it simply identifies the credentials that the request was made with.
For information on how to set up the permission policies for your API please see the [permissions documentation][permission].
---
For information on how to set up the permission policies for your API please see the [permissions documentation][permission].
## How authentication is determined
@ -122,17 +119,15 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
WWW-Authenticate: Basic realm="api"
**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https`. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
!!! note
If you use `BasicAuthentication` in production you must ensure that your API is only available over `https`. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
## TokenAuthentication
---
!!! note
The token authentication provided by Django REST framework is a fairly simple implementation.
**Note:** The token authentication provided by Django REST framework is a fairly simple implementation.
For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the [Django REST Knox][django-rest-knox] third party package.
---
For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the [Django REST Knox][django-rest-knox] third party package.
This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
@ -173,11 +168,8 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
---
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https`.
---
!!! note
If you use `TokenAuthentication` in production you must ensure that your API is only available over `https`.
### Generating Tokens
@ -293,7 +285,8 @@ Unauthenticated responses that are denied permission will result in an `HTTP 403
If you're using an AJAX-style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
!!! warning
Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behavior is not suitable for login views, which should always have CSRF validation applied.
@ -334,11 +327,8 @@ You *may* also override the `.authenticate_header(self, request)` method. If im
If the `.authenticate_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access.
---
**Note:** When your custom authenticator is invoked by the request object's `.user` or `.auth` properties, you may see an `AttributeError` re-raised as a `WrappedAttributeError`. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from your custom authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. These errors should be fixed or otherwise handled by your authenticator.
---
!!! note
When your custom authenticator is invoked by the request object's `.user` or `.auth` properties, you may see an `AttributeError` re-raised as a `WrappedAttributeError`. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from your custom authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. These errors should be fixed or otherwise handled by your authenticator.
## Example
@ -426,6 +416,11 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.
## DRF Auth Kit
[DRF Auth Kit][drf-auth-kit] library provides a modern REST authentication solution with JWT cookies, social login, multi-factor authentication, and comprehensive user management. The package offers full type safety, automatic OpenAPI schema generation with DRF Spectacular. It supports multiple authentication types (JWT, DRF Token, or Custom) and includes built-in internationalization for 50+ languages.
## django-rest-auth / dj-rest-auth
This library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.
@ -454,9 +449,9 @@ There are currently two forks of this project.
More information can be found in the [Documentation](https://django-rest-durin.readthedocs.io/en/latest/index.html).
## django-pyoidc
## django-pyoidc
[dango-pyoidc][django_pyoidc] adds support for OpenID Connect (OIDC) authentication. This allows you to delegate user management to an Identity Provider, which can be used to implement Single-Sign-On (SSO). It provides support for most uses-cases, such as customizing how token info are mapped to user models, using OIDC audiences for access control, etc.
[django_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.
More information can be found in the [Documentation](https://django-pyoidc.readthedocs.io/latest/index.html).
@ -497,4 +492,5 @@ More information can be found in the [Documentation](https://django-pyoidc.readt
[django-rest-authemail]: https://github.com/celiao/django-rest-authemail
[django-rest-durin]: https://github.com/eshaan7/django-rest-durin
[login-required-middleware]: https://docs.djangoproject.com/en/stable/ref/middleware/#django.contrib.auth.middleware.LoginRequiredMiddleware
[django-pyoidc] : https://github.com/makinacorpus/django_pyoidc
[django-pyoidc]: https://github.com/makinacorpus/django_pyoidc
[drf-auth-kit]: https://github.com/huynguyengl99/drf-auth-kit

View File

@ -82,10 +82,10 @@ def get_user_list(request):
```
**NOTE:** The [`cache_page`][page] decorator only caches the
`GET` and `HEAD` responses with status 200.
!!! note
The [`cache_page`][page] decorator only caches the `GET` and `HEAD` responses with status 200.
[page]: https://docs.djangoproject.com/en/dev/topics/cache/#the-per-view-cache
[cookie]: https://docs.djangoproject.com/en/dev/topics/http/decorators/#django.views.decorators.vary.vary_on_cookie
[headers]: https://docs.djangoproject.com/en/dev/topics/http/decorators/#django.views.decorators.vary.vary_on_headers
[decorator]: https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-the-class
[page]: https://docs.djangoproject.com/en/stable/topics/cache/#the-per-view-cache
[cookie]: https://docs.djangoproject.com/en/stable/topics/http/decorators/#django.views.decorators.vary.vary_on_cookie
[headers]: https://docs.djangoproject.com/en/stable/topics/http/decorators/#django.views.decorators.vary.vary_on_headers
[decorator]: https://docs.djangoproject.com/en/stable/topics/class-based-views/intro/#decorating-the-class

View File

@ -34,13 +34,11 @@ If the requested view was only configured with renderers for `YAML` and `HTML`,
For more information on the `HTTP Accept` header, see [RFC 2616][accept-header]
---
**Note**: "q" values are not taken into account by REST framework when determining preference. The use of "q" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation.
!!! note
"q" values are not taken into account by REST framework when determining preference. The use of "q" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation.
This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences.
---
This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences.
# Custom content negotiation

View File

@ -269,5 +269,5 @@ The [drf-standardized-errors][drf-standardized-errors] package provides an excep
[cite]: https://doughellmann.com/blog/2009/06/19/python-exception-handling-techniques/
[authentication]: authentication.md
[django-custom-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
[django-custom-error-views]: https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors

View File

@ -11,11 +11,8 @@ source:
Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
---
**Note:** The serializer fields are declared in `fields.py`, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
---
!!! note
The serializer fields are declared in `fields.py`, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
## Core arguments
@ -42,7 +39,7 @@ Set to false if this field is not required to be present during deserialization.
Setting this to `False` also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.
Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer) default value will be `False` if you have specified `blank=True` or `default` or `null=True` at your field in your `Model`.
Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer), the default value will be `False` when you have specified a `default`, or when the corresponding `Model` field has `blank=True` or `null=True` and is not part of a unique constraint at the same time. (Note that without a `default` value, [unique constraints will cause the field to be required](https://www.django-rest-framework.org/api-guide/validators/#optional-fields).)
### `default`
@ -180,7 +177,7 @@ The `allow_null` option is also available for string fields, although its usage
## EmailField
A text representation, validates the text to be a valid e-mail address.
A text representation, validates the text to be a valid email address.
Corresponds to `django.db.models.fields.EmailField`
@ -269,6 +266,18 @@ Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.
* `max_value` Validate that the number provided is no greater than this value.
* `min_value` Validate that the number provided is no less than this value.
## BigIntegerField
A biginteger representation.
Corresponds to `django.db.models.fields.BigIntegerField`.
**Signature**: `BigIntegerField(max_value=None, min_value=None, coerce_to_string=None)`
* `max_value` Validate that the number provided is no greater than this value.
* `min_value` Validate that the number provided is no less than this value.
* `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `BigInteger` objects should be returned. Defaults to the same value as the `COERCE_BIGINT_TO_STRING` settings key, which will be `False` unless overridden. If `BigInteger` objects are returned by the serializer, then the final output format will be determined by the renderer.
## FloatField
A floating point representation.
@ -377,13 +386,16 @@ A Duration representation.
Corresponds to `django.db.models.fields.DurationField`
The `validated_data` for these fields will contain a `datetime.timedelta` instance.
The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu]'`.
**Signature:** `DurationField(max_value=None, min_value=None)`
**Signature:** `DurationField(format=api_settings.DURATION_FORMAT, max_value=None, min_value=None)`
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DURATION_FORMAT` settings key, which will be `'django'` unless set. Formats are described below. Setting this value to `None` indicates that Python `timedelta` objects should be returned by `to_representation`. In this case the date encoding will be determined by the renderer.
* `max_value` Validate that the duration provided is no greater than this value.
* `min_value` Validate that the duration provided is no less than this value.
#### `DurationField` formats
Format may either be the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style intervals should be used (eg `'P4DT1H15M20S'`), or `'django'` which indicates that Django interval format `'[DD] [HH:[MM:]]ss[.uuuuuu]'` should be used (eg: `'4 1:15:20'`).
---
# Choice selection fields
@ -550,11 +562,8 @@ The `HiddenField` class is usually only needed if you have some validation that
For further examples on `HiddenField` see the [validators](validators.md) documentation.
---
**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request). This behavior might change in future, follow updates on [github discussion](https://github.com/encode/django-rest-framework/discussions/8259).
---
!!! note
`HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request).
## ModelField
@ -759,7 +768,7 @@ suitable for updating our target object. With `source='*'`, the return from
('y_coordinate', 4),
('x_coordinate', 3)])
For completeness lets do the same thing again but with the nested serializer
For completeness let's do the same thing again but with the nested serializer
approach suggested above:
class NestedCoordinateSerializer(serializers.Serializer):
@ -857,4 +866,4 @@ The [django-rest-framework-hstore][django-rest-framework-hstore] package provide
[django-hstore]: https://github.com/djangonauts/django-hstore
[python-decimal-rounding-modes]: https://docs.python.org/3/library/decimal.html#rounding-modes
[django-current-timezone]: https://docs.djangoproject.com/en/stable/topics/i18n/timezones/#default-time-zone-and-current-time-zone
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related
[django-docs-select-related]: https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related

View File

@ -235,7 +235,7 @@ For example:
search_fields = ['=username', '=email']
By default, the search parameter is named `'search'`, but this may be overridden with the `SEARCH_PARAM` setting.
By default, the search parameter is named `'search'`, but this may be overridden with the `SEARCH_PARAM` setting in the `REST_FRAMEWORK` configuration.
To dynamically change search fields based on request content, it's possible to subclass the `SearchFilter` and override the `get_search_fields()` function. For example, the following subclass will only search on `title` if the query parameter `title_only` is in the request:
@ -257,7 +257,7 @@ The `OrderingFilter` class supports simple query parameter controlled ordering o
![Ordering Filter](../img/ordering-filter.png)
By default, the query parameter is named `'ordering'`, but this may be overridden with the `ORDERING_PARAM` setting.
By default, the query parameter is named `'ordering'`, but this may be overridden with the `ORDERING_PARAM` setting in the `REST_FRAMEWORK` configuration.
For example, to order users by username:
@ -367,6 +367,6 @@ The [djangorestframework-word-filter][django-rest-framework-word-search-filter]
[django-rest-framework-word-search-filter]: https://github.com/trollknurr/django-rest-framework-word-search-filter
[django-url-filter]: https://github.com/miki725/django-url-filter
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
[HStoreField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#hstorefield
[JSONField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#jsonfield
[HStoreField]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/fields/#hstorefield
[JSONField]: https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.JSONField
[postgres-search]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/search/

View File

@ -96,9 +96,39 @@ For example:
user = self.request.user
return user.accounts.all()
---
!!! tip
If the `serializer_class` used in the generic view spans ORM relations, leading to an N+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about N+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related].
**Note:** If the `serializer_class` used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related].
### 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.
---
@ -374,8 +404,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.
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
@ -395,4 +423,4 @@ The following third party packages provide additional generic view implementatio
[UpdateModelMixin]: #updatemodelmixin
[DestroyModelMixin]: #destroymodelmixin
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related
[django-docs-select-related]: https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related

View File

@ -66,7 +66,7 @@ The REST framework package only includes a single metadata class implementation,
## Creating schema endpoints
If you have specific requirements for creating schema endpoints that are accessed with regular `GET` requests, you might consider re-using the metadata API for doing so.
If you have specific requirements for creating schema endpoints that are accessed with regular `GET` requests, you might consider reusing the metadata API for doing so.
For example, the following additional route could be used on a viewset to provide a linkable schema endpoint.

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_size_query_param` - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to `None`, indicating that the client may not control the requested page size.
* `max_page_size` - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if `page_size_query_param` is also set.
* `last_page_strings` - A list or tuple of string values indicating values that may be used with the `page_query_param` to request the final page in the set. Defaults to `('last',)`
* `last_page_strings` - A list or tuple of string values indicating values that may be used with the `page_query_param` to request the final page in the set. Defaults to `('last',)`. For example, use `?page=last` to go directly to the last page.
* `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`.
---

View File

@ -17,15 +17,12 @@ REST framework includes a number of built-in Parser classes, that allow you to a
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
---
!!! note
When developing client applications always remember to make sure you're setting the `Content-Type` header when sending data in an HTTP request.
**Note**: When developing client applications always remember to make sure you're setting the `Content-Type` header when sending data in an HTTP request.
If you don't set the content type, most clients will default to using `'application/x-www-form-urlencoded'`, which may not be what you want.
If you don't set the content type, most clients will default to using `'application/x-www-form-urlencoded'`, which may not be what you wanted.
As an example, if you are sending `json` encoded data using jQuery with the [.ajax() method][jquery-ajax], you should make sure to include the `contentType: 'application/json'` setting.
---
As an example, if you are sending `json` encoded data using jQuery with the [.ajax() method][jquery-ajax], you should make sure to include the `contentType: 'application/json'` setting.
## Setting the parsers

View File

@ -51,18 +51,15 @@ For example:
self.check_object_permissions(self.request, obj)
return obj
---
!!! note
With the exception of `DjangoObjectPermissions`, the provided
permission classes in `rest_framework.permissions` **do not** implement the
methods necessary to check object permissions.
**Note**: With the exception of `DjangoObjectPermissions`, the provided
permission classes in `rest_framework.permissions` **do not** implement the
methods necessary to check object permissions.
If you wish to use the provided permission classes in order to check object
permissions, **you must** subclass them and implement the
`has_object_permission()` method described in the [_Custom
permissions_](#custom-permissions) section (below).
---
If you wish to use the provided permission classes in order to check object
permissions, **you must** subclass them and implement the
`has_object_permission()` method described in the [_Custom
permissions_](#custom-permissions) section (below).
#### Limitations of object level permissions
@ -118,7 +115,8 @@ Or, if you're using the `@api_view` decorator with function based views.
}
return Response(content)
__Note:__ when you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in the __settings.py__ file.
!!! note
When you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in the ``settings.py`` file.
Provided they inherit from `rest_framework.permissions.BasePermission`, permissions can be composed using standard Python bitwise operators. For example, `IsAuthenticatedOrReadOnly` could be written:
@ -131,7 +129,7 @@ Provided they inherit from `rest_framework.permissions.BasePermission`, permissi
return request.method in SAFE_METHODS
class ExampleView(APIView):
permission_classes = [IsAuthenticated|ReadOnly]
permission_classes = [IsAuthenticated | ReadOnly]
def get(self, request, format=None):
content = {
@ -139,9 +137,8 @@ Provided they inherit from `rest_framework.permissions.BasePermission`, permissi
}
return Response(content)
__Note:__ it supports & (and), | (or) and ~ (not).
---
!!! note
Composition of permissions supports `&` (and), `|` (or) and `~` (not) operators.
# API Reference
@ -185,7 +182,7 @@ To use custom model permissions, override `DjangoModelPermissions` and set the `
Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API.
## DjangoObjectPermissions
## DjangoObjectPermissions
This permission class ties into Django's standard [object permissions framework][objectpermissions] that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as [django-guardian][guardian].
@ -199,11 +196,8 @@ Note that `DjangoObjectPermissions` **does not** require the `django-guardian` p
As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoObjectPermissions` and setting the `.perms_map` property. Refer to the source code for details.
---
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian2` package][django-rest-framework-guardian2]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.
---
!!! note
If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian` package][django-rest-framework-guardian]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.
# Custom permissions
@ -221,11 +215,8 @@ If you need to test if a request is a read operation or a write operation, you s
else:
# Check permissions for write request
---
**Note**: The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default. (Function-based views will need to check object permissions explicitly, raising `PermissionDenied` on failure.)
---
!!! note
The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default. (Function-based views will need to check object permissions explicitly, raising `PermissionDenied` on failure.)
Custom permissions will raise a `PermissionDenied` exception if the test fails. To change the error message associated with the exception, implement a `message` attribute directly on your custom permission. Otherwise the `default_detail` attribute from `PermissionDenied` will be used. Similarly, to change the code identifier associated with the exception, implement a `code` attribute directly on your custom permission - otherwise the `default_code` attribute from `PermissionDenied` will be used.
@ -340,6 +331,10 @@ The [Django Rest Framework Role Filters][django-rest-framework-role-filters] pac
The [Django Rest Framework PSQ][drf-psq] package is an extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.
## Axioms DRF PY
The [Axioms DRF PY][axioms-drf-py] package is an extension that provides support for authentication and claim-based fine-grained authorization (**scopes**, **roles**, **groups**, **permissions**, etc. including object-level checks) using JWT tokens issued by an OAuth2/OIDC Authorization Server including AWS Cognito, Auth0, Okta, Microsoft Entra, etc.
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
[authentication]: authentication.md
@ -356,6 +351,7 @@ The [Django Rest Framework PSQ][drf-psq] package is an extension that gives supp
[rest-framework-roles]: https://github.com/Pithikos/rest-framework-roles
[djangorestframework-api-key]: https://florimondmanca.github.io/djangorestframework-api-key/
[django-rest-framework-role-filters]: https://github.com/allisson/django-rest-framework-role-filters
[django-rest-framework-guardian2]: https://github.com/johnthagen/django-rest-framework-guardian2
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
[drf-access-policy]: https://github.com/rsinger86/drf-access-policy
[drf-psq]: https://github.com/drf-psq/drf-psq
[axioms-drf-py]: https://github.com/abhishektiwari/axioms-drf-py

View File

@ -11,42 +11,36 @@ source:
Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
---
!!! note
The relational fields are declared in `relations.py`, but by convention you should import them from the `serializers` module, using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
**Note:** The relational fields are declared in `relations.py`, but by convention you should import them from the `serializers` module, using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
!!! note
REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of `select_related` and `prefetch_related` since it would be too much magic. A serializer with a field spanning an ORM relation through its source attribute could require an additional database hit to fetch related objects from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer.
---
---
**Note:** REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of `select_related` and `prefetch_related` since it would be too much magic. A serializer with a field spanning an orm relation through its source attribute could require an additional database hit to fetch related objects from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer.
For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched:
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.SlugRelatedField(
many=True,
read_only=True,
slug_field='title'
)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
# For each album object, tracks should be fetched from database
qs = Album.objects.all()
print(AlbumSerializer(qs, many=True).data)
If `AlbumSerializer` is used to serialize a fairly large queryset with `many=True` then it could be a serious performance problem. Optimizing the queryset passed to `AlbumSerializer` with:
qs = Album.objects.prefetch_related('tracks')
# No additional database hits required
print(AlbumSerializer(qs, many=True).data)
would solve the issue.
---
For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched:
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.SlugRelatedField(
many=True,
read_only=True,
slug_field='title'
)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
# For each album object, tracks should be fetched from database
qs = Album.objects.all()
print(AlbumSerializer(qs, many=True).data)
If `AlbumSerializer` is used to serialize a fairly large queryset with `many=True` then it could be a serious performance problem. Optimizing the queryset passed to `AlbumSerializer` with:
qs = Album.objects.prefetch_related('tracks')
# No additional database hits required
print(AlbumSerializer(qs, many=True).data)
would solve the issue.
#### Inspecting relationships.
@ -183,15 +177,12 @@ Would serialize to a representation like this:
By default this field is read-write, although you can change this behavior using the `read_only` flag.
---
!!! note
This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the `lookup_field` and `lookup_url_kwarg` arguments.
**Note**: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the `lookup_field` and `lookup_url_kwarg` arguments.
This is suitable for URLs that contain a single primary key or slug argument as part of the URL.
This is suitable for URLs that contain a single primary key or slug argument as part of the URL.
If you require more complex hyperlinked representation you'll need to customize the field, as described in the [custom hyperlinked fields](#custom-hyperlinked-fields) section, below.
---
If you require more complex hyperlinked representation you'll need to customize the field, as described in the [custom hyperlinked fields](#custom-hyperlinked-fields) section, below.
**Arguments**:
@ -300,7 +291,7 @@ For example, the following serializer:
Would serialize to a nested representation like this:
>>> album = Album.objects.create(album_name="The Grey Album", artist='Danger Mouse')
>>> album = Album.objects.create(album_name="The Gray Album", artist='Danger Mouse')
>>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)
<Track: Track object>
>>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)
@ -310,7 +301,7 @@ Would serialize to a nested representation like this:
>>> serializer = AlbumSerializer(instance=album)
>>> serializer.data
{
'album_name': 'The Grey Album',
'album_name': 'The Gray Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
@ -344,7 +335,7 @@ By default nested serializers are read-only. If you want to support write-operat
return album
>>> data = {
'album_name': 'The Grey Album',
'album_name': 'The Gray Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},

View File

@ -103,15 +103,10 @@ Unlike other renderers, the data passed to the `Response` does not need to be se
The TemplateHTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context.
---
!!! note
When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the `TemplateHTMLRenderer` to render it. For example:
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the `TemplateHTMLRenderer` to render it. For example:
```
response.data = {'results': response.data}
```
---
response.data = {'results': response.data}
The template name is determined by (in order of preference):
@ -134,7 +129,7 @@ An example of a view that uses `TemplateHTMLRenderer`:
You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers.
If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritized first even for browsers that send poorly formed `ACCEPT:` headers.
See the [_HTML & Forms_ Topic Page][html-and-forms] for further examples of `TemplateHTMLRenderer` usage.
@ -202,13 +197,16 @@ This renderer is suitable for CRUD-style web APIs that should also present a use
Note that views that have nested or list serializers for their input won't work well with the `AdminRenderer`, as the HTML forms are unable to properly support them.
**Note**: The `AdminRenderer` is only able to include links to detail pages when a properly configured `URL_FIELD_NAME` (`url` by default) attribute is present in the data. For `HyperlinkedModelSerializer` this will be the case, but for `ModelSerializer` or plain `Serializer` classes you'll need to make sure to include the field explicitly. For example here we use models `get_absolute_url` method:
!!! note
The `AdminRenderer` is only able to include links to detail pages when a properly configured `URL_FIELD_NAME` (`url` by default) attribute is present in the data. For `HyperlinkedModelSerializer` this will be the case, but for `ModelSerializer` or plain `Serializer` classes you'll need to make sure to include the field explicitly.
class AccountSerializer(serializers.ModelSerializer):
url = serializers.CharField(source='get_absolute_url', read_only=True)
For example here we use models `get_absolute_url` method:
class Meta:
model = Account
class AccountSerializer(serializers.ModelSerializer):
url = serializers.CharField(source='get_absolute_url', read_only=True)
class Meta:
model = Account
**.media_type**: `text/html`
@ -390,9 +388,8 @@ Exceptions raised and handled by an HTML renderer will attempt to render using o
Templates will render with a `RequestContext` which includes the `status_code` and `details` keys.
**Note**: If `DEBUG=True`, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.
---
!!! note
If `DEBUG=True`, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.
# Third party packages
@ -444,13 +441,10 @@ Modify your REST framework settings.
[REST framework JSONP][rest-framework-jsonp] provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
---
!!! warning
If you require cross-domain AJAX requests, you should generally be using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details.
**Warning**: If you require cross-domain AJAX requests, you should generally be using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details.
The `jsonp` approach is essentially a browser hack, and is [only appropriate for globally readable API endpoints][jsonp-security], where `GET` requests are unauthenticated and do not require any user permissions.
---
The `jsonp` approach is essentially a browser hack, and is [only appropriate for globally readable API endpoints][jsonp-security], where `GET` requests are unauthenticated and do not require any user permissions.
#### Installation & configuration

View File

@ -39,13 +39,10 @@ The `APIView` class or `@api_view` decorator will ensure that this property is a
You won't typically need to access this property.
---
!!! note
If a client sends malformed content, then accessing `request.data` may raise a `ParseError`. By default REST framework's `APIView` class or `@api_view` decorator will catch the error and return a `400 Bad Request` response.
**Note:** If a client sends malformed content, then accessing `request.data` may raise a `ParseError`. By default REST framework's `APIView` class or `@api_view` decorator will catch the error and return a `400 Bad Request` response.
If a client sends a request with a content-type that cannot be parsed then a `UnsupportedMediaType` exception will be raised, which by default will be caught and return a `415 Unsupported Media Type` response.
---
If a client sends a request with a content-type that cannot be parsed then a `UnsupportedMediaType` exception will be raised, which by default will be caught and return a `415 Unsupported Media Type` response.
# Content negotiation
@ -91,11 +88,8 @@ The `APIView` class or `@api_view` decorator will ensure that this property is a
You won't typically need to access this property.
---
**Note:** You may see a `WrappedAttributeError` raised when calling the `.user` or `.auth` properties. These errors originate from an authenticator as a standard `AttributeError`, however it's necessary that they be re-raised as a different exception type in order to prevent them from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from the authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. The authenticator will need to be fixed.
---
!!! note
You may see a `WrappedAttributeError` raised when calling the `.user` or `.auth` properties. These errors originate from an authenticator as a standard `AttributeError`, however it's necessary that they be re-raised as a different exception type in order to prevent them from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from the authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. The authenticator will need to be fixed.
# Browser enhancements

View File

@ -11,7 +11,7 @@ source:
REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request.
The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` objects are initialised with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.
The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` objects are initialized with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.
There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` or `StreamingHttpResponse` objects from your views if required. Using the `Response` class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats.

View File

@ -40,17 +40,14 @@ The example above would generate the following URL patterns:
* URL pattern: `^accounts/$` Name: `'account-list'`
* URL pattern: `^accounts/{pk}/$` Name: `'account-detail'`
---
!!! note
The `basename` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part.
**Note**: The `basename` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part.
Typically you won't *need* to specify the `basename` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this:
Typically you won't *need* to specify the `basename` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this:
'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
This means you'll need to explicitly set the `basename` argument when registering the viewset, as it could not be automatically determined from the model name.
---
This means you'll need to explicitly set the `basename` argument when registering the viewset, as it could not be automatically determined from the model name.
### Using `include` with routers
@ -91,16 +88,13 @@ Or both an application and instance namespace:
See Django's [URL namespaces docs][url-namespace-docs] and the [`include` API reference][include-api-reference] for more details.
---
**Note**: If using namespacing with hyperlinked serializers you'll also need to ensure that any `view_name` parameters
on the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as
`view_name='app_name:user-detail'` for serializer fields hyperlinked to the user detail view.
The automatic `view_name` generation uses a pattern like `%(model_name)-detail`. Unless your models names actually clash
you may be better off **not** namespacing your Django REST Framework views when using hyperlinked serializers.
---
!!! note
If using namespacing with hyperlinked serializers you'll also need to ensure that any `view_name` parameters
on the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as
`view_name='app_name:user-detail'` for serializer fields hyperlinked to the user detail view.
The automatic `view_name` generation uses a pattern like `%(model_name)-detail`. Unless your models names actually clash
you may be better off **not** namespacing your Django REST Framework views when using hyperlinked serializers.
### Routing for extra actions
@ -350,6 +344,6 @@ The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions
[drf-extensions-nested-viewsets]: https://chibisov.github.io/drf-extensions/docs/#nested-routes
[drf-extensions-collection-level-controllers]: https://chibisov.github.io/drf-extensions/docs/#collection-level-controllers
[drf-extensions-customizable-endpoint-names]: https://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name
[url-namespace-docs]: https://docs.djangoproject.com/en/4.0/topics/http/urls/#url-namespaces
[include-api-reference]: https://docs.djangoproject.com/en/4.0/ref/urls/#include
[path-converters-topic-reference]: https://docs.djangoproject.com/en/2.0/topics/http/urls/#path-converters
[url-namespace-docs]: https://docs.djangoproject.com/en/stable/topics/http/urls/#url-namespaces
[include-api-reference]: https://docs.djangoproject.com/en/stable/ref/urls/#include
[path-converters-topic-reference]: https://docs.djangoproject.com/en/stable/topics/http/urls/#path-converters

View File

@ -20,7 +20,7 @@ package and then subsequently retired over the next releases.
As a full-fledged replacement, we recommend the [drf-spectacular] package.
It has extensive support for generating OpenAPI 3 schemas from
REST framework APIs, with both automatic and customisable options available.
REST framework APIs, with both automatic and customizable options available.
For further information please refer to
[Documenting your API](../topics/documenting-your-api.md#drf-spectacular).
@ -238,15 +238,12 @@ operation = auto_schema.get_operation(...)
In compiling the schema, `SchemaGenerator` calls `get_components()` and
`get_operation()` for each view, allowed method, and path.
----
**Note**: The automatic introspection of components, and many operation
parameters relies on the relevant attributes and methods of
`GenericAPIView`: `get_serializer()`, `pagination_class`, `filter_backends`,
etc. For basic `APIView` subclasses, default introspection is essentially limited to
the URL kwarg path parameters for this reason.
----
!!! note
The automatic introspection of components, and many operation
parameters relies on the relevant attributes and methods of
`GenericAPIView`: `get_serializer()`, `pagination_class`, `filter_backends`,
etc. For basic `APIView` subclasses, default introspection is essentially limited to
the URL kwarg path parameters for this reason.
`AutoSchema` encapsulates the view introspection needed for schema generation.
Because of this all the schema generation logic is kept in a single place,
@ -392,7 +389,7 @@ introspection.
#### `get_operation_id()`
There must be a unique [operationid](openapi-operationid) for each operation.
There must be a unique [operationid][openapi-operationid] for each operation.
By default the `operationId` is deduced from the model name, serializer name or
view name. The operationId looks like "listItems", "retrieveItem",
"updateItem", etc. The `operationId` is camelCase by convention.
@ -451,14 +448,14 @@ If your views have related customizations that are needed frequently, you can
create a base `AutoSchema` subclass for your project that takes additional
`__init__()` kwargs to save subclassing `AutoSchema` for each view.
[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api
[cite]: https://www.heroku.com/blog/json_schema_for_heroku_platform_api/
[openapi]: https://github.com/OAI/OpenAPI-Specification
[openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions
[openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject
[openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#specification-extensions
[openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#operationObject
[openapi-tags]: https://swagger.io/specification/#tagObject
[openapi-operationid]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#fixed-fields-17
[openapi-components]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#componentsObject
[openapi-reference]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#referenceObject
[openapi-operationid]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#fixed-fields-17
[openapi-components]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#componentsObject
[openapi-reference]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#referenceObject
[openapi-generator]: https://github.com/OpenAPITools/openapi-generator
[swagger-codegen]: https://github.com/swagger-api/swagger-codegen
[info-object]: https://swagger.io/specification/#infoObject

View File

@ -48,7 +48,7 @@ We can now use `CommentSerializer` to serialize a comment, or list of comments.
serializer.data
# {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}
At this point we've translated the model instance into Python native datatypes. To finalise the serialization process we render the data into `json`.
At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`.
from rest_framework.renderers import JSONRenderer
@ -155,7 +155,7 @@ When deserializing data, you always need to call `is_valid()` before attempting
serializer.is_valid()
# False
serializer.errors
# {'email': ['Enter a valid e-mail address.'], 'created': ['This field is required.']}
# {'email': ['Enter a valid email address.'], 'created': ['This field is required.']}
Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The `non_field_errors` key may also be present, and will list any general validation errors. The name of the `non_field_errors` key may be customized using the `NON_FIELD_ERRORS_KEY` REST framework setting.
@ -192,11 +192,8 @@ Your `validate_<field_name>` methods should return the validated value or raise
raise serializers.ValidationError("Blog post is not about Django")
return value
---
**Note:** If your `<field_name>` is declared on your serializer with the parameter `required=False` then this validation step will not take place if the field is not included.
---
!!! note
If your `<field_name>` is declared on your serializer with the parameter `required=False` then this validation step will not take place if the field is not included.
#### Object-level validation
@ -298,7 +295,7 @@ When dealing with nested representations that support deserializing the data, an
serializer.is_valid()
# False
serializer.errors
# {'user': {'email': ['Enter a valid e-mail address.']}, 'created': ['This field is required.']}
# {'user': {'email': ['Enter a valid email address.']}, 'created': ['This field is required.']}
Similarly, the `.validated_data` property will include nested data structures.
@ -542,20 +539,16 @@ This option should be a list or tuple of field names, and is declared as follows
Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option.
---
!!! note
There is a special-case where a read-only field is part of a `unique_together` constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user.
**Note**: There is a special-case where a read-only field is part of a `unique_together` constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user.
The right way to deal with this is to specify the field explicitly on the serializer, providing both the `read_only=True` and `default=…` keyword arguments.
The right way to deal with this is to specify the field explicitly on the serializer, providing both the `read_only=True` and `default=…` keyword arguments.
One example of this is a read-only relation to the currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so:
One example of this is a read-only relation to the currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so:
user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
Please review the [Validators Documentation](/api-guide/validators/) for details on the [UniqueTogetherValidator](/api-guide/validators/#uniquetogethervalidator) and [CurrentUserDefault](/api-guide/validators/#currentuserdefault) classes.
---
user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
Please review the [Validators Documentation](/api-guide/validators/) for details on the [UniqueTogetherValidator](/api-guide/validators/#uniquetogethervalidator) and [CurrentUserDefault](/api-guide/validators/#currentuserdefault) classes.
## Additional keyword arguments
@ -708,7 +701,7 @@ You can override a URL field view name and lookup field by using either, or both
class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
fields = ['account_url', 'account_name', 'users', 'created']
fields = ['url', 'account_name', 'users', 'created']
extra_kwargs = {
'url': {'view_name': 'accounts', 'lookup_field': 'account_name'},
'users': {'lookup_field': 'username'}
@ -1189,6 +1182,10 @@ The [drf-writable-nested][drf-writable-nested] package provides writable nested
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
## Shapeless Serializers
The [drf-shapeless-serializers][drf-shapeless-serializers] package provides dynamic serializer configuration capabilities, allowing runtime field selection, renaming, attribute modification, and nested relationship configuration without creating multiple serializer classes. It helps eliminate serializer boilerplate while providing flexible API responses.
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
[relations]: relations.md
@ -1212,3 +1209,4 @@ The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your da
[djangorestframework-queryfields]: https://djangorestframework-queryfields.readthedocs.io/
[drf-writable-nested]: https://github.com/beda-software/drf-writable-nested
[drf-encrypt-content]: https://github.com/oguzhancelikarslan/drf-encrypt-content
[drf-shapeless-serializers]: https://github.com/khaledsukkar2/drf-shapeless-serializers

View File

@ -314,6 +314,15 @@ May be a list including the string `'iso-8601'` or Python [strftime format][strf
Default: `['iso-8601']`
#### DURATION_FORMAT
Indicates the default format that should be used for rendering the output of `DurationField` serializer fields. If `None`, then `DurationField` serializer fields will return Python `timedelta` objects, and the duration encoding will be determined by the renderer.
May be any of `None`, `'iso-8601'` or `'django'` (the format accepted by `django.utils.dateparse.parse_duration`).
Default: `'django'`
---
## Encodings
@ -362,6 +371,14 @@ When set to `True`, the serializer `DecimalField` class will return strings inst
Default: `True`
#### COERCE_BIGINT_TO_STRING
When returning biginteger objects in API representations that do not support numbers up to 2^64, it is best to return the value as a string. This avoids the loss of precision that occurs with biginteger implementations.
When set to `True`, the serializer `BigIntegerField` class (by default) will return strings instead of `BigInteger` objects. When set to `False`, serializers will return `BigInteger` objects, which the default JSON encoder will return as numbers.
Default: `False`
---
## View names and descriptions

View File

@ -90,22 +90,32 @@ For example, when forcibly authenticating using a token, you might do something
request = factory.get('/accounts/django-superstars/')
force_authenticate(request, user=user, token=user.auth_token)
---
!!! note
`force_authenticate` directly sets `request.user` to the in-memory `user` instance. If you are reusing the same `user` instance across multiple tests that update the saved `user` state, you may need to call [`refresh_from_db()`][refresh_from_db_docs] between tests.
**Note**: `force_authenticate` directly sets `request.user` to the in-memory `user` instance. If you are re-using the same `user` instance across multiple tests that update the saved `user` state, you may need to call [`refresh_from_db()`][refresh_from_db_docs] between tests.
!!! note
When using `APIRequestFactory`, the object that is returned is Django's standard `HttpRequest`, and not REST framework's `Request` object, which is only generated once the view is called.
---
**Note**: When using `APIRequestFactory`, the object that is returned is Django's standard `HttpRequest`, and not REST framework's `Request` object, which is only generated once the view is called.
This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting `.token` directly will have no effect, and setting `.user` directly will only work if session authentication is being used.
# Request will only authenticate if `SessionAuthentication` is in use.
request = factory.get('/accounts/django-superstars/')
request.user = user
response = view(request)
---
This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting `.token` directly will have no effect, and setting `.user` directly will only work if session authentication is being used.
# Request will only authenticate if `SessionAuthentication` is in use.
request = factory.get('/accounts/django-superstars/')
request.user = user
response = view(request)
If you want to test a request involving the REST frameworks 'Request' object, youll need to manually transform it first:
class DummyView(APIView):
...
factory = APIRequestFactory()
request = factory.get('/', {'demo': 'test'})
drf_request = DummyView().initialize_request(request)
assert drf_request.query_params == {'demo': ['test']}
request = factory.post('/', {'example': 'test'})
drf_request = DummyView().initialize_request(request)
assert drf_request.data.get('example') == 'test'
## Forcing CSRF validation
@ -113,11 +123,8 @@ By default, requests created with `APIRequestFactory` will not have CSRF validat
factory = APIRequestFactory(enforce_csrf_checks=True)
---
**Note**: It's worth noting that Django's standard `RequestFactory` doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.
---
!!! note
It's worth noting that Django's standard `RequestFactory` doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.
# APIClient
@ -250,7 +257,7 @@ For example...
csrftoken = response.cookies['csrftoken']
# Interact with the API.
response = client.post('http://testserver/organisations/', json={
response = client.post('http://testserver/organizations/', json={
'name': 'MegaCorp',
'status': 'active'
}, headers={'X-CSRFToken': csrftoken})
@ -278,12 +285,12 @@ The CoreAPIClient allows you to interact with your API using the Python
client = CoreAPIClient()
schema = client.get('http://testserver/schema/')
# Create a new organisation
# Create a new organization
params = {'name': 'MegaCorp', 'status': 'active'}
client.action(schema, ['organisations', 'create'], params)
client.action(schema, ['organizations', 'create'], params)
# Ensure that the organisation exists in the listing
data = client.action(schema, ['organisations', 'list'])
# Ensure that the organization exists in the listing
data = client.action(schema, ['organizations', 'list'])
assert(len(data) == 1)
assert(data == [{'name': 'MegaCorp', 'status': 'active'}])
@ -339,6 +346,7 @@ REST framework also provides a test case class for isolating `urlpatterns` on a
## Example
from django.urls import include, path, reverse
from rest_framework import status
from rest_framework.test import APITestCase, URLPatternsTestCase
@ -417,5 +425,5 @@ For example, to add support for using `format='html'` in test requests, you migh
[requestfactory]: https://docs.djangoproject.com/en/stable/topics/testing/advanced/#django.test.client.RequestFactory
[configuration]: #configuration
[refresh_from_db_docs]: https://docs.djangoproject.com/en/stable/ref/models/instances/#django.db.models.Model.refresh_from_db
[session_objects]: https://requests.readthedocs.io/en/master/user/advanced/#session-objects
[session_objects]: https://requests.readthedocs.io/en/latest/user/advanced/#session-objects
[provided_test_case_classes]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#provided-test-case-classes

View File

@ -19,9 +19,9 @@ Multiple throttles can also be used if you want to impose both burst throttling
Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.
**The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins. In addition to this, the built-in throttling implementations are implemented using Django's cache framework, and use non-atomic operations to determine the request rate, which may sometimes result in some fuzziness.
**The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins. In addition to this, the built-in throttling implementations are implemented using Django's cache framework, and use non-atomic operations to determine the request rate, which may sometimes result in some fuzziness.**
The application-level throttling provided by REST framework is intended for implementing policies such as different business tiers and basic protections against service over-use.**
**The application-level throttling provided by REST framework is intended for implementing policies such as different business tiers and basic protections against service over-use.**
## How throttling is determined

View File

@ -5,7 +5,7 @@ source:
# Validators
> Validators can be useful for re-using validation logic between different types of fields.
> Validators can be useful for reusing validation logic between different types of fields.
>
> &mdash; [Django documentation][cite]
@ -13,7 +13,7 @@ Most of the time you're dealing with validation in REST framework you'll simply
However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.
## Validation in REST framework
## Validation in REST framework
Validation in Django REST framework serializers is handled a little differently to how validation works in Django's `ModelForm` class.
@ -75,7 +75,7 @@ This validator should be applied to *serializer fields*, like so:
validators=[UniqueValidator(queryset=BlogPost.objects.all())]
)
## UniqueTogetherValidator
## UniqueTogetherValidator
This validator can be used to enforce `unique_together` constraints on model instances.
It has two required arguments, and a single optional `messages` argument:
@ -92,7 +92,7 @@ The validator should be applied to *serializer classes*, like so:
# ...
class Meta:
# ToDo items belong to a parent list, and have an ordering defined
# by the 'position' field. No two items in a given list may share
# by the 'position' field. No two items in a given list may share
# the same position.
validators = [
UniqueTogetherValidator(
@ -101,11 +101,8 @@ The validator should be applied to *serializer classes*, like so:
)
]
---
**Note**: The `UniqueTogetherValidator` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
---
!!! note
The `UniqueTogetherValidator` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
## UniqueForDateValidator
@ -158,24 +155,19 @@ If you want the date field to be entirely hidden from the user, then use `Hidden
published = serializers.HiddenField(default=timezone.now)
---
!!! note
The `UniqueFor<Range>Validator` classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
**Note**: The `UniqueFor<Range>Validator` classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
---
---
**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request). This behavior might change in future, follow updates on [github discussion](https://github.com/encode/django-rest-framework/discussions/8259).
---
!!! note
`HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request).
# Advanced field defaults
Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that *is* available as input to the validator.
For this purposes use `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation.
**Note:** Using a `read_only=True` field is excluded from writable fields so it won't use a `default=…` argument. Look [3.8 announcement](https://www.django-rest-framework.org/community/3.8-announcement/#altered-the-behaviour-of-read_only-plus-default-on-field).
!!! note
Using a `read_only=True` field is excluded from writable fields so it won't use a `default=…` argument. Look [3.8 announcement](https://www.django-rest-framework.org/community/3.8-announcement/#altered-the-behavior-of-read_only-plus-default-on-field).
REST framework includes a couple of defaults that may be useful in this context.

View File

@ -45,11 +45,8 @@ For example:
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
---
**Note**: The full methods, attributes on, and relations between Django REST Framework's `APIView`, `GenericAPIView`, various `Mixins`, and `Viewsets` can be initially complex. In addition to the documentation here, the [Classy Django REST Framework][classy-drf] resource provides a browsable reference, with full methods and attributes, for each of Django REST Framework's class-based views.
---
!!! note
The full methods, attributes on, and relations between Django REST Framework's `APIView`, `GenericAPIView`, various `Mixins`, and `Viewsets` can be initially complex. In addition to the documentation here, the [Classy Django REST Framework][classy-drf] resource provides a browsable reference, with full methods and attributes, for each of Django REST Framework's class-based views.
## API policy attributes
@ -186,8 +183,13 @@ The available decorators are:
* `@authentication_classes(...)`
* `@throttle_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
@ -224,4 +226,5 @@ You may pass `None` in order to exclude the view from schema generation.
[throttling]: throttling.md
[schemas]: schemas.md
[classy-drf]: http://www.cdrf.co
[api-policy-attributes]: views.md#api-policy-attributes

View File

@ -57,6 +57,9 @@ Typically we wouldn't do this, but would instead register the viewset with a rou
router.register(r'users', UserViewSet, basename='user')
urlpatterns = router.urls
!!! warning
Do not use `.as_view()` with `@action` methods. It bypasses router setup and may ignore action settings like `permission_classes`. Use `DefaultRouter` for actions.
Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:
class UserViewSet(viewsets.ModelViewSet):
@ -128,7 +131,8 @@ You may inspect these attributes to adjust behavior based on the current action.
permission_classes = [IsAdminUser]
return [permission() for permission in permission_classes]
**Note**: the `action` attribute is not available in the `get_parsers`, `get_authenticators` and `get_content_negotiator` methods, as it is set _after_ they are called in the framework lifecycle. If you override one of these methods and try to access the `action` attribute in them, you will get an `AttributeError` error.
!!! note
The `action` attribute is not available in the `get_parsers`, `get_authenticators` and `get_content_negotiator` methods, as it is set _after_ they are called in the framework lifecycle. If you override one of these methods and try to access the `action` attribute in them, you will get an `AttributeError` error.
## Marking extra actions for routing
@ -231,7 +235,7 @@ Using the example from the previous section:
Alternatively, you can use the `url_name` attribute set by the `@action` decorator.
```pycon
>>> view.reverse_action(view.set_password.url_name, args=['1'])
>>> view.reverse_action(view.set_password.url_name, args=["1"])
'http://localhost:8000/api/users/1/set_password'
```

View File

@ -632,7 +632,7 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behavior in a way that did not simply lookup the field value from the object. For example...
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customize the behavior in a way that did not simply lookup the field value from the object. For example...
def field_to_native(self, obj, field_name):
"""A custom read-only field that returns the class name."""
@ -961,5 +961,5 @@ You can follow development on the GitHub site, where we use [milestones to indic
[kickstarter]: https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3
[sponsors]: https://www.django-rest-framework.org/community/kickstarter-announcement/#sponsors
[mixins.py]: https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py
[mixins.py]: https://github.com/encode/django-rest-framework/blob/main/rest_framework/mixins.py
[django-localization]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#localization-how-to-create-language-files

View File

@ -46,7 +46,7 @@ The cursor based pagination renders a more simple style of control:
The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the `Link` or `Content-Range` headers.
For more information, see the [custom pagination styles](../api-guide/pagination/#custom-pagination-styles) documentation.
For more information, see the [custom pagination styles](../api-guide/pagination.md#custom-pagination-styles) documentation.
---

View File

@ -50,11 +50,9 @@ class DocStringExampleListView(APIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get(self, request, *args, **kwargs):
...
def get(self, request, *args, **kwargs): ...
def post(self, request, *args, **kwargs):
...
def post(self, request, *args, **kwargs): ...
```
## Validator / Default Context
@ -76,8 +74,7 @@ Validator implementations will look like this:
class CustomValidator:
requires_context = True
def __call__(self, value, serializer_field):
...
def __call__(self, value, serializer_field): ...
```
Default implementations will look like this:
@ -86,8 +83,7 @@ Default implementations will look like this:
class CustomDefault:
requires_context = True
def __call__(self, serializer_field):
...
def __call__(self, serializer_field): ...
```
---

View File

@ -50,7 +50,7 @@ See [the schema documentation](https://www.django-rest-framework.org/api-guide/s
## Customizing the operation ID.
REST framework automatically determines operation IDs to use in OpenAPI
schemas. The latest version provides more control for overriding the behaviour
schemas. The latest version provides more control for overriding the behavior
used to generate the operation IDs.
See [the schema documentation](https://www.django-rest-framework.org/api-guide/schemas/#operationid) for more information.
@ -96,7 +96,7 @@ for details on using custom `AutoSchema` subclasses.
## Support for JSONField.
Django 3.1 deprecated the existing `django.contrib.postgres.fields.JSONField`
in favour of a new database-agnositic `JSONField`.
in favor of a new database-agnositic `JSONField`.
REST framework 3.12 now supports this new model field, and `ModelSerializer`
classes will correctly map the model field.

View File

@ -50,6 +50,6 @@ They must now use the more explicit keyword argument style...
aliases = serializers.ListField(child=serializers.CharField())
```
This change has been made because using positional arguments here *does not* result in the expected behaviour.
This change has been made because using positional arguments here *does not* result in the expected behavior.
See Pull Request [#7632](https://github.com/encode/django-rest-framework/pull/7632) for more details.

View File

@ -39,12 +39,12 @@ By default the URLs created by `SimpleRouter` use regular expressions. This beha
Dependency on pytz has been removed and deprecation warnings have been added, Django will provide ZoneInfo instances as long as USE_DEPRECATED_PYTZ is not enabled. More info on the migration can be found [in this guide](https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html).
## Align `SearchFilter` behaviour to `django.contrib.admin` search
## Align `SearchFilter` behavior to `django.contrib.admin` search
Searches now may contain _quoted phrases_ with spaces, each phrase is considered as a single search term, and it will raise a validation error if any null-character is provided in search. See the [Filtering API guide](../api-guide/filtering.md) for more information.
## Other fixes and improvements
There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behaviour.
There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behavior.
See the [release notes](release-notes.md) page for a complete listing.

View File

@ -29,7 +29,7 @@ The current minimum versions of Django is now 4.2 and Python 3.9.
## Django LoginRequiredMiddleware
The new `LoginRequiredMiddleware` introduced by Django 5.1 can now be used alongside Django REST Framework, however it is not honored for API views as an equivalent behaviour can be configured via `DEFAULT_AUTHENTICATION_CLASSES`. See [our dedicated section](../api-guide/authentication.md#django-51-loginrequiredmiddleware) in the docs for more information.
The new `LoginRequiredMiddleware` introduced by Django 5.1 can now be used alongside Django REST Framework, however it is not honored for API views as an equivalent behavior can be configured via `DEFAULT_AUTHENTICATION_CLASSES`. See [our dedicated section](../api-guide/authentication.md#django-51-loginrequiredmiddleware) in the docs for more information.
## Improved support for UniqueConstraint
@ -37,6 +37,6 @@ The generation of validators for [UniqueConstraint](https://docs.djangoproject.c
## Other fixes and improvements
There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behaviour.
There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behavior.
See the [release notes](release-notes.md) page for a complete listing.

View File

@ -54,7 +54,7 @@ The `ModelSerializer` and `HyperlinkedModelSerializer` classes should now includ
[forms-api]: ../topics/html-and-forms.md
[ajax-form]: https://github.com/encode/ajax-form
[jsonfield]: ../api-guide/fields#jsonfield
[jsonfield]: ../api-guide/fields.md#jsonfield
[accept-headers]: ../topics/browser-enhancements.md#url-based-accept-headers
[method-override]: ../topics/browser-enhancements.md#http-header-based-method-overriding
[django-supported-versions]: https://www.djangoproject.com/download/#supported-versions

View File

@ -157,7 +157,7 @@ will result in a list of the available choices being returned in the response.
In cases where there is a relational field, the previous behavior would be
to return a list of available instances to choose from for that relational field.
In order to minimise exposed information the behavior now is to *not* return
In order to minimize exposed information the behavior now is to *not* return
choices information for relational fields.
If you want to override this new behavior you'll need to [implement a custom
@ -179,16 +179,16 @@ The full set of itemized release notes [are available here][release-notes].
[moss]: mozilla-grant.md
[funding]: funding.md
[core-api]: https://www.coreapi.org/
[command-line-client]: api-clients#command-line-client
[client-library]: api-clients#python-client-library
[command-line-client]: https://github.com/encode/django-rest-framework/blob/3.4.7/docs/topics/api-clients.md#command-line-client
[client-library]: https://github.com/encode/django-rest-framework/blob/3.4.7/docs/topics/api-clients.md#python-client-library
[core-json]: https://www.coreapi.org/specification/encoding/#core-json-encoding
[swagger]: https://openapis.org/specification
[hyperschema]: https://json-schema.org/latest/json-schema-hypermedia.html
[api-blueprint]: https://apiblueprint.org/
[tut-7]: ../tutorial/7-schemas-and-client-libraries/
[schema-generation]: ../api-guide/schemas/
[tut-7]: https://github.com/encode/django-rest-framework/blob/3.4.7/docs/tutorial/7-schemas-and-client-libraries.md
[schema-generation]: ../api-guide/schemas.md
[api-clients]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md
[milestone]: https://github.com/encode/django-rest-framework/milestone/35
[release-notes]: release-notes#34
[metadata]: ../api-guide/metadata/#custom-metadata-classes
[release-notes]: ./release-notes.md#34x-series
[metadata]: ../api-guide/metadata.md#custom-metadata-classes
[gh3751]: https://github.com/encode/django-rest-framework/issues/3751

View File

@ -81,7 +81,7 @@ a dynamic client library to interact with your API.
Finally, we're also now exposing the schema generation as a
[publicly documented API][schema-generation-api], allowing you to more easily
override the behaviour.
override the behavior.
## Requests test client
@ -106,12 +106,12 @@ client library.
client = CoreAPIClient()
schema = client.get('http://testserver/schema/')
# Create a new organisation
# Create a new organization
params = {'name': 'MegaCorp', 'status': 'active'}
client.action(schema, ['organisations', 'create'], params)
client.action(schema, ['organizations', 'create'], params)
# Ensure that the organisation exists in the listing
data = client.action(schema, ['organisations', 'list'])
# Ensure that the organization exists in the listing
data = client.action(schema, ['organizations', 'list'])
assert(len(data) == 1)
assert(data == [{'name': 'MegaCorp', 'status': 'active'}])
@ -204,10 +204,10 @@ The `'pk'` identifier in schema paths is now mapped onto the actually model fiel
name by default. This will typically be `'id'`.
This gives a better external representation for schemas, with less implementation
detail being exposed. It also reflects the behaviour of using a ModelSerializer
detail being exposed. It also reflects the behavior of using a ModelSerializer
class with `fields = '__all__'`.
You can revert to the previous behaviour by setting `'SCHEMA_COERCE_PATH_PK': False`
You can revert to the previous behavior by setting `'SCHEMA_COERCE_PATH_PK': False`
in the REST framework settings.
### Schema action name representations
@ -215,7 +215,7 @@ in the REST framework settings.
The internal `retrieve()` and `destroy()` method names are now coerced to an
external representation of `read` and `delete`.
You can revert to the previous behaviour by setting `'SCHEMA_COERCE_METHOD_NAMES': {}`
You can revert to the previous behavior by setting `'SCHEMA_COERCE_METHOD_NAMES': {}`
in the REST framework settings.
### DjangoFilterBackend
@ -254,9 +254,9 @@ in version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandato
[funding]: funding.md
[uploads]: https://core-api.github.io/python-client/api-guide/utils/#file
[downloads]: https://core-api.github.io/python-client/api-guide/codecs/#downloadcodec
[schema-generation-api]: ../api-guide/schemas/#schemagenerator
[schema-docs]: ../api-guide/schemas/#schemas-as-documentation
[schema-view]: ../api-guide/schemas/#the-get_schema_view-shortcut
[schema-generation-api]: ../api-guide/schemas.md#schemagenerator
[schema-docs]: ../api-guide/schemas.md#schemas-as-documentation
[schema-view]: ../api-guide/schemas.md#get_schema_view
[django-rest-raml]: https://github.com/encode/django-rest-raml
[raml-image]: ../img/raml.png
[raml-codec]: https://github.com/core-api/python-raml-codec

View File

@ -53,7 +53,7 @@ In order to try to address this we're now adding the ability for per-view custom
Let's take a quick look at using the new functionality...
The `APIView` class has a `schema` attribute, that is used to control how the Schema for that particular view is generated. The default behaviour is to use the `AutoSchema` class.
The `APIView` class has a `schema` attribute, that is used to control how the Schema for that particular view is generated. The default behavior is to use the `AutoSchema` class.
from rest_framework.views import APIView
from rest_framework.schemas import AutoSchema

View File

@ -36,7 +36,7 @@ If you use REST framework commercially and would like to see this work continue,
## Breaking Changes
### Altered the behaviour of `read_only` plus `default` on Field.
### Altered the behavior of `read_only` plus `default` on Field.
[#5886][gh5886] `read_only` fields will now **always** be excluded from writable fields.
@ -44,7 +44,7 @@ Previously `read_only` fields when combined with a `default` value would use the
operations. This was counter-intuitive in some circumstances and led to difficulties supporting dotted `source`
attributes on nullable relations.
In order to maintain the old behaviour you may need to pass the value of `read_only` fields when calling `save()` in
In order to maintain the old behavior you may need to pass the value of `read_only` fields when calling `save()` in
the view:
def perform_create(self, serializer):

View File

@ -152,7 +152,7 @@ See [#5990][gh5990].
### `action` decorator replaces `list_route` and `detail_route`
Both `list_route` and `detail_route` are now deprecated in favour of the single `action` decorator.
Both `list_route` and `detail_route` are now deprecated in favor of the single `action` decorator.
They will be removed entirely in 3.10.
The `action` decorator takes a boolean `detail` argument.

View File

@ -30,9 +30,7 @@ The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines f
# Issues
Our contribution process is that the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Please only raise an issue or pull request if you've been recommended to do so after discussion.
Some tips on good potential issue reporting:
Our contribution process is that the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Some tips on good potential issue reporting:
* Django REST framework is considered feature-complete. Please do not file requests to change behavior, unless it is required for security reasons or to maintain compatibility with upcoming Django or Python versions.
* Search the GitHub project page for related items, and make sure you're running the latest version of REST framework before reporting an issue.
@ -83,12 +81,42 @@ To run the tests, clone the repository, and then:
# Run the tests
./runtests.py
!!! tip
If your tests require access to the database, do not forget to inherit from `django.test.TestCase` or use the `@pytest.mark.django_db()` decorator.
For example, with TestCase:
from django.test import TestCase
class MyDatabaseTest(TestCase):
def test_something(self):
# Your test code here
pass
Or with decorator:
import pytest
@pytest.mark.django_db()
class MyDatabaseTest:
def test_something(self):
# Your test code here
pass
You can reuse existing models defined in `tests/models.py` for your tests.
### Test options
Run using a more concise output style.
./runtests.py -q
If you do not want the output to be captured (for example, to see print statements directly), you can use the `-s` flag.
./runtests.py -s
Run the tests for a given test case.
./runtests.py MyTestCase
@ -101,7 +129,9 @@ Shorter form to run the tests for a given test method.
./runtests.py test_this_method
Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
!!! 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
@ -193,26 +223,25 @@ Linking in this style means you'll be able to click the hyperlink in your Markdo
##### 3. Notes
If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:
If you want to draw attention to a note or warning, use an [admonition], like so:
---
!!! note
A useful documentation note.
**Note:** A useful documentation note.
---
The documentation theme styles `info`, `warning`, `tip` and `danger` admonition types, but more could be added if the need arise.
[cite]: https://www.w3.org/People/Berners-Lee/FAQ.html
[code-of-conduct]: https://www.djangoproject.com/conduct/
[google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[so-filter]: https://stackexchange.com/filters/66475/rest-framework
[issues]: https://github.com/encode/django-rest-framework/issues?state=open
[pep-8]: https://www.python.org/dev/peps/pep-0008/
[build-status]: ../img/build-status.png
[pull-requests]: https://help.github.com/articles/using-pull-requests
[tox]: https://tox.readthedocs.io/en/latest/
[markdown]: https://daringfireball.net/projects/markdown/basics
[docs]: https://github.com/encode/django-rest-framework/tree/master/docs
[docs]: https://github.com/encode/django-rest-framework/tree/main/docs
[mou]: http://mouapp.com/
[repo]: https://github.com/encode/django-rest-framework
[how-to-fork]: https://help.github.com/articles/fork-a-repo/
[admonition]: https://python-markdown.github.io/extensions/admonition/

View File

@ -1,398 +0,0 @@
<script>
// Imperfect, but easier to fit in with the existing docs build.
// Hyperlinks should point directly to the "fund." subdomain, but this'll
// handle the nav bar links without requiring any docs build changes for the moment.
if (window.location.hostname == "www.django-rest-framework.org") {
window.location.replace("https://fund.django-rest-framework.org/topics/funding/");
}
</script>
<style>
.promo li a {
float: left;
width: 130px;
height: 20px;
text-align: center;
margin: 10px 30px;
padding: 150px 0 0 0;
background-position: 0 50%;
background-size: 130px auto;
background-repeat: no-repeat;
font-size: 120%;
color: black;
}
.promo li {
list-style: none;
}
.chart {
background-color: #e3e3e3;
background: -webkit-linear-gradient(top, #fff 0, #e3e3e3 100%);
border: 1px solid #E6E6E6;
border-radius: 5px;
box-shadow: 0px 0px 2px 0px rgba(181, 181, 181, 0.3);
padding: 40px 0px 5px;
position: relative;
text-align: center;
width: 97%;
min-height: 255px;
position: relative;
top: 37px;
margin-bottom: 20px
}
.quantity {
text-align: center
}
.dollar {
font-size: 19px;
position: relative;
top: -18px;
}
.price {
font-size: 49px;
}
.period {
font-size: 17px;
position: relative;
top: -8px;
margin-left: 4px;
}
.plan-name {
text-align: center;
font-size: 20px;
font-weight: 400;
color: #777;
border-bottom: 1px solid #d5d5d5;
padding-bottom: 15px;
width: 90%;
margin: 0 auto;
margin-top: 8px;
}
.specs {
margin-top: 20px;
min-height: 130px;
}
.specs.freelancer {
min-height: 0px;
}
.spec {
font-size: 15px;
color: #474747;
text-align: center;
font-weight: 300;
margin-bottom: 13px;
}
.variable {
color: #1FBEE7;
font-weight: 400;
}
form.signup {
margin-top: 35px
}
.clear-promo {
padding-top: 30px
}
#main-content h1:first-of-type {
margin: 0 0 50px;
font-size: 60px;
font-weight: 200;
text-align: center
}
#main-content {
padding-top: 10px; line-height: 23px
}
#main-content li {
line-height: 23px
}
</style>
# Funding
If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan.
**We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.**
Signing up for a paid plan will:
* Directly contribute to faster releases, more features, and higher quality software.
* Allow more time to be invested in documentation, issue triage, and community support.
* Safeguard the future development of REST framework.
REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development.
---
## What funding has enabled so far
* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/).
* Tom Christie, the creator of Django REST framework, working on the project full-time.
* Around 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time.
* A community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship.
* Contracting development time for the work on the JavaScript client library and API documentation tooling.
---
## What future funding will enable
* Realtime API support, using WebSockets. This will consist of documentation and support for using REST framework together with Django Channels, plus integrating WebSocket support into the client libraries.
* Better authentication defaults, possibly bringing JWT & CORS support into the core package.
* Securing the community & operations manager position long-term.
* Opening up and securing a part-time position to focus on ticket triage and resolution.
* Paying for development time on building API client libraries in a range of programming languages. These would be integrated directly into the upcoming API documentation.
Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.
---
## What our sponsors and users say
> As a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem.
>
> &mdash; José Padilla, Django REST framework contributor
&nbsp;
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
>
> &mdash; Filipe Ximenes, Vinta Software
&nbsp;
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.
>
> &mdash; Andrew Conti, Django REST framework user
---
## Individual plan
This subscription is recommended for individuals with an interest in seeing REST framework continue to&nbsp;improve.
If you are using REST framework as a full-time employee, consider recommending that your company takes out a [corporate&nbsp;plan](#corporate-plans).
<div class="pricing">
<div class="span4">
<div class="chart first">
<div class="quantity">
<span class="dollar">{{ symbol }}</span>
<span class="price">{{ rates.personal1 }}</span>
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
</div>
<div class="plan-name">Individual</div>
<div class="specs freelancer">
<div class="spec">
Support ongoing development
</div>
<div class="spec">
Credited on the site
</div>
</div>
<form class="signup" action="/signup/{{ currency }}-{{ rates.personal1 }}/" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public }}"
data-amount="{{ stripe_amounts.personal1 }}"
data-name="Django REST framework"
data-description="Individual"
data-currency="{{ currency }}"
data-allow-remember-me=false
data-billing-address=true
data-label='Sign up'
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
</script>
</form>
</div>
</div>
</div>
<div style="clear: both; padding-top: 50px"></div>
*Billing is monthly and you can cancel at any time.*
---
## Corporate plans
These subscriptions are recommended for companies and organizations using REST framework either publicly or privately.
In exchange for funding you'll also receive advertising space on our site, allowing you to **promote your company or product to many tens of thousands of developers worldwide**.
Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.
<div class="pricing">
<div class="span4">
<div class="chart first">
<div class="quantity">
<span class="dollar">{{ symbol }}</span>
<span class="price">{{ rates.corporate1 }}</span>
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
</div>
<div class="plan-name">Basic</div>
<div class="specs startup">
<div class="spec">
Support ongoing development
</div>
<div class="spec">
<span class="variable">Funding page</span> ad placement
</div>
</div>
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate1 }}/" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public }}"
data-amount="{{ stripe_amounts.corporate1 }}"
data-name="Django REST framework"
data-description="Basic"
data-currency="{{ currency }}"
data-allow-remember-me=false
data-billing-address=true
data-label='Sign up'
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
</script>
</form>
</div>
</div>
<div class="span4">
<div class="chart">
<div class="quantity">
<span class="dollar">{{ symbol }}</span>
<span class="price">{{ rates.corporate2 }}</span>
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
</div>
<div class="plan-name">Professional</div>
<div class="specs">
<div class="spec">
Support ongoing development
</div>
<div class="spec">
<span class="variable">Sidebar</span> ad placement
</div>
<div class="spec">
<span class="variable">Priority support</span> for your engineers
</div>
</div>
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate2 }}/" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public }}"
data-amount="{{ stripe_amounts.corporate2 }}"
data-name="Django REST framework"
data-description="Professional"
data-currency="{{ currency }}"
data-allow-remember-me=false
data-billing-address=true
data-label='Sign up'
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
</script>
</form>
</div>
</div>
<div class="span4">
<div class="chart last">
<div class="quantity">
<span class="dollar">{{ symbol }}</span>
<span class="price">{{ rates.corporate3 }}</span>
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
</div>
<div class="plan-name">Premium</div>
<div class="specs">
<div class="spec">
Support ongoing development
</div>
<div class="spec">
<span class="variable">Homepage</span> ad placement
</div>
<div class="spec">
<span class="variable">Sidebar</span> ad placement
</div>
<div class="spec">
<span class="variable">Priority support</span> for your engineers
</div>
</div>
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate3 }}/" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public }}"
data-amount="{{ stripe_amounts.corporate3 }}"
data-name="Django REST framework"
data-description="Premium"
data-currency="{{ currency }}"
data-allow-remember-me=false
data-billing-address=true
data-label='Sign up'
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
</script>
</form>
</div>
</div>
</div>
<div style="clear: both; padding-top: 50px"></div>
*Billing is monthly and you can cancel at any time.*
Once you've signed up, we will contact you via email and arrange your ad placements on the site.
For further enquires please contact <a href=mailto:funding@django-rest-framework.org>funding@django-rest-framework.org</a>.
---
## Accountability
In an effort to keep the project as transparent as possible, we are releasing [monthly progress reports](https://www.encode.io/reports/march-2018/) and regularly include financial reports and cost breakdowns.
<!-- Begin MailChimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
<style type="text/css">
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="//encode.us13.list-manage.com/subscribe/post?u=b6b66bb5e4c7cb484a85c8dd7&amp;id=e382ef68ef" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<div id="mc_embed_signup_scroll">
<h2>Stay up to date, with our monthly progress reports...</h2>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address </label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_b6b66bb5e4c7cb484a85c8dd7_e382ef68ef" tabindex="-1" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</div>
</form>
</div>
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!--End mc_embed_signup-->
---
## Frequently asked questions
**Q: Can you issue monthly invoices?**
A: Yes, we are happy to issue monthly invoices. Please just <a href=mailto:funding@django-rest-framework.org>email us</a> and let us know who to issue the invoice to (name and address) and which email address to send it to each month.
**Q: Does sponsorship include VAT?**
A: Sponsorship is VAT exempt.
**Q: Do I have to sign up for a certain time period?**
A: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime.
**Q: Can I pay yearly? Can I pay upfront fox X amount of months at a time?**
A: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution.
**Q: Are you only looking for corporate sponsors?**
A: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support.
---
## Our sponsors
<div id="fundingInclude"></div>
<script src="https://fund.django-rest-framework.org/funding_include.js"></script>

View File

@ -31,7 +31,7 @@ Team members have the following responsibilities.
Further notes for maintainers:
* Code changes should come in the form of a pull request - do not push directly to master.
* Code changes should come in the form of a pull request - do not push directly to main.
* Maintainers should typically not merge their own pull requests.
* Each issue/pull request should have exactly one label once triaged.
* Search for un-triaged issues with [is:open no:label][un-triaged].
@ -51,28 +51,24 @@ The following template should be used for the description of the issue, and serv
Release manager is @***.
Pull request is #***.
During development cycle:
- [ ] Upload the new content to be translated to [transifex](https://www.django-rest-framework.org/topics/project-management/#translations).
Checklist:
- [ ] Create pull request for [release notes](https://github.com/encode/django-rest-framework/blob/master/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:
- [ ] `setup.py` `python_requires` list
- [ ] `setup.py` Python & Django version trove classifiers
- [ ] `pyproject.toml` `python_requires` list
- [ ] `pyproject.toml` Python & Django version trove classifiers
- [ ] `README` Python & Django versions
- [ ] `docs` Python & Django versions
- [ ] Update the translations from [transifex](https://www.django-rest-framework.org/topics/project-management/#translations).
- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/__init__.py).
- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/main/rest_framework/__init__.py).
- [ ] Ensure documentation validates
- Build and serve docs `mkdocs serve`
- Validate links `pylinkvalidate.py -P http://127.0.0.1:8000`
- [ ] Confirm with @tomchristie that release is finalized and ready to go.
- [ ] Ensure that release date is included in 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`.
- [ ] 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).
@ -85,55 +81,6 @@ When pushing the release to PyPI ensure that your environment has been installed
---
## Translations
The maintenance team are responsible for managing the translation packs include in REST framework. Translating the source strings into multiple languages is managed through the [transifex service][transifex-project].
### Managing Transifex
The [official Transifex client][transifex-client] is used to upload and download translations to Transifex. The client is installed using pip:
pip install transifex-client
To use it you'll need a login to Transifex which has a password, and you'll need to have administrative access to the Transifex project. You'll need to create a `~/.transifexrc` file which contains your credentials.
[https://www.transifex.com]
username = ***
token = ***
password = ***
hostname = https://www.transifex.com
### Upload new source files
When any user visible strings are changed, they should be uploaded to Transifex so that the translators can start to translate them. To do this, just run:
# 1. Update the source django.po file, which is the US English version.
cd rest_framework
django-admin makemessages -l en_US
# 2. Push the source django.po file to Transifex.
cd ..
tx push -s
When pushing source files, Transifex will update the source strings of a resource to match those from the new source file.
Here's how differences between the old and new source files will be handled:
* New strings will be added.
* Modified strings will be added as well.
* Strings which do not exist in the new source file will be removed from the database, along with their translations. If that source strings gets re-added later then [Transifex Translation Memory][translation-memory] will automatically include the translation string.
### Download translations
When a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run:
# 3. Pull the translated django.po files from Transifex.
tx pull -a --minimum-perc 10
cd rest_framework
# 4. Compile the binary .mo files for all supported languages.
django-admin compilemessages
---
## Project requirements
All our test requirements are pinned to exact versions, in order to ensure that our test runs are reproducible. We maintain the requirements in the `requirements` directory. The requirements files are referenced from the `tox.ini` configuration file, ensuring we have a single source of truth for package versions used in testing.
@ -158,7 +105,4 @@ The following issues still need to be addressed:
[bus-factor]: https://en.wikipedia.org/wiki/Bus_factor
[un-triaged]: https://github.com/encode/django-rest-framework/issues?q=is%3Aopen+no%3Alabel
[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/
[transifex-client]: https://pypi.org/project/transifex-client/
[translation-memory]: http://docs.transifex.com/guides/tm#let-tm-automatically-populate-translations
[mailing-list]: https://groups.google.com/forum/#!forum/django-rest-framework

View File

@ -38,20 +38,83 @@ You can determine your currently installed version using `pip show`:
## 3.16.x series
### 3.16.1
**Date**: 6th August 2025
This release fixes a few bugs, clean-up some old code paths for unsupported Python versions and improve translations.
#### Minor changes
* Cleanup optional `backports.zoneinfo` dependency and conditions on unsupported Python 3.8 and lower in [#9681](https://github.com/encode/django-rest-framework/pull/9681). Python versions prior to 3.9 were already unsupported so this shouldn't be a breaking change.
#### Bug fixes
* Fix regression in `unique_together` validation with `SerializerMethodField` in [#9712](https://github.com/encode/django-rest-framework/pull/9712)
* Fix `UniqueTogetherValidator` to handle fields with `source` attribute in [#9688](https://github.com/encode/django-rest-framework/pull/9688)
* Drop HTML line breaks on long headers in browsable API in [#9438](https://github.com/encode/django-rest-framework/pull/9438)
#### Translations
* Add Kazakh locale support in [#9713](https://github.com/encode/django-rest-framework/pull/9713)
* Update translations for Korean translations in [#9571](https://github.com/encode/django-rest-framework/pull/9571)
* Update German translations in [#9676](https://github.com/encode/django-rest-framework/pull/9676)
* Update Chinese translations in [#9675](https://github.com/encode/django-rest-framework/pull/9675)
* Update Arabic translations-sal in [#9595](https://github.com/encode/django-rest-framework/pull/9595)
* Update Persian translations in [#9576](https://github.com/encode/django-rest-framework/pull/9576)
* Update Spanish translations in [#9701](https://github.com/encode/django-rest-framework/pull/9701)
* Update Turkish Translations in [#9749](https://github.com/encode/django-rest-framework/pull/9749)
* Fix some typos in Brazilian Portuguese translations in [#9673](https://github.com/encode/django-rest-framework/pull/9673)
#### Documentation
* Removed reference to GitHub Issues and Discussions in [#9660](https://github.com/encode/django-rest-framework/pull/9660)
* Add `drf-restwind` and update outdated images in `browsable-api.md` in [#9680](https://github.com/encode/django-rest-framework/pull/9680)
* Updated funding page to represent current scope in [#9686](https://github.com/encode/django-rest-framework/pull/9686)
* Fix broken Heroku JSON Schema link in [#9693](https://github.com/encode/django-rest-framework/pull/9693)
* Update Django documentation links to use stable version in [#9698](https://github.com/encode/django-rest-framework/pull/9698)
* Expand docs on unique constraints cause 'required=True' in [#9725](https://github.com/encode/django-rest-framework/pull/9725)
* Revert extension back from `djangorestframework-guardian2` to `djangorestframework-guardian` in [#9734](https://github.com/encode/django-rest-framework/pull/9734)
* Add note to tutorial about required `request` in serializer context when using `HyperlinkedModelSerializer` in [#9732](https://github.com/encode/django-rest-framework/pull/9732)
#### Internal changes
* Update GitHub Actions to use Ubuntu 24.04 for testing in [#9677](https://github.com/encode/django-rest-framework/pull/9677)
* Update test matrix to use Django 5.2 stable version in [#9679](https://github.com/encode/django-rest-framework/pull/9679)
* Add `pyupgrade` to `pre-commit` hooks in [#9682](https://github.com/encode/django-rest-framework/pull/9682)
* Fix test with Django 5 when `pytz` is available in [#9715](https://github.com/encode/django-rest-framework/pull/9715)
#### New Contributors
* [`@araggohnxd`](https://github.com/araggohnxd) made their first contribution in [#9673](https://github.com/encode/django-rest-framework/pull/9673)
* [`@mbeijen`](https://github.com/mbeijen) made their first contribution in [#9660](https://github.com/encode/django-rest-framework/pull/9660)
* [`@stefan6419846`](https://github.com/stefan6419846) made their first contribution in [#9676](https://github.com/encode/django-rest-framework/pull/9676)
* [`@ren000thomas`](https://github.com/ren000thomas) made their first contribution in [#9675](https://github.com/encode/django-rest-framework/pull/9675)
* [`@ulgens`](https://github.com/ulgens) made their first contribution in [#9682](https://github.com/encode/django-rest-framework/pull/9682)
* [`@bukh-sal`](https://github.com/bukh-sal) made their first contribution in [#9595](https://github.com/encode/django-rest-framework/pull/9595)
* [`@rezatn0934`](https://github.com/rezatn0934) made their first contribution in [#9576](https://github.com/encode/django-rest-framework/pull/9576)
* [`@Rohit10jr`](https://github.com/Rohit10jr) made their first contribution in [#9693](https://github.com/encode/django-rest-framework/pull/9693)
* [`@kushibayev`](https://github.com/kushibayev) made their first contribution in [#9713](https://github.com/encode/django-rest-framework/pull/9713)
* [`@alihassancods`](https://github.com/alihassancods) made their first contribution in [#9732](https://github.com/encode/django-rest-framework/pull/9732)
* [`@kulikjak`](https://github.com/kulikjak) made their first contribution in [#9715](https://github.com/encode/django-rest-framework/pull/9715)
* [`@Natgho`](https://github.com/Natgho) made their first contribution in [#9749](https://github.com/encode/django-rest-framework/pull/9749)
**Full Changelog**: https://github.com/encode/django-rest-framework/compare/3.16.0...3.16.1
### 3.16.0
**Date**: 28th March 2025
This release is considered a significant release to improve upstream support with Django and Python. Some of these may change the behaviour of existing features and pre-existing behaviour. Specifically, some fixes were added to around the support of `UniqueConstraint` with nullable fields which will improve built-in serializer validation.
This release is considered a significant release to improve upstream support with Django and Python. Some of these may change the behavior of existing features and pre-existing behavior. Specifically, some fixes were added to around the support of `UniqueConstraint` with nullable fields which will improve built-in serializer validation.
## Features
#### Features
* Add official support for Django 5.1 and its new `LoginRequiredMiddleware` in [#9514](https://github.com/encode/django-rest-framework/pull/9514) and [#9657](https://github.com/encode/django-rest-framework/pull/9657)
* Add official Django 5.2a1 support in [#9634](https://github.com/encode/django-rest-framework/pull/9634)
* Add support for Python 3.13 in [#9527](https://github.com/encode/django-rest-framework/pull/9527) and [#9556](https://github.com/encode/django-rest-framework/pull/9556)
* Support Django 2.1+ test client JSON data automatically serialized in [#6511](https://github.com/encode/django-rest-framework/pull/6511) and fix a regression in [#9615](https://github.com/encode/django-rest-framework/pull/9615)
## Bug fixes
#### Bug fixes
* Fix unique together validator to respect condition's fields from `UniqueConstraint` in [#9360](https://github.com/encode/django-rest-framework/pull/9360)
* Fix raising on nullable fields part of `UniqueConstraint` in [#9531](https://github.com/encode/django-rest-framework/pull/9531)
@ -62,19 +125,19 @@ This release is considered a significant release to improve upstream support wit
* Fix noisy warning and accept integers as min/max values of `DecimalField` in [#9515](https://github.com/encode/django-rest-framework/pull/9515)
* Fix usages of `open()` in `setup.py` in [#9661](https://github.com/encode/django-rest-framework/pull/9661)
## Translations
#### Translations
* Add some missing Chinese translations in [#9505](https://github.com/encode/django-rest-framework/pull/9505)
* Fix spelling mistakes in Farsi language were corrected in [#9521](https://github.com/encode/django-rest-framework/pull/9521)
* Fixing and adding missing Brazilian Portuguese translations in [#9535](https://github.com/encode/django-rest-framework/pull/9535)
## Removals
#### Removals
* Remove support for Python 3.8 in [#9670](https://github.com/encode/django-rest-framework/pull/9670)
* Remove long deprecated code from request wrapper in [#9441](https://github.com/encode/django-rest-framework/pull/9441)
* Remove deprecated `AutoSchema._get_reference` method in [#9525](https://github.com/encode/django-rest-framework/pull/9525)
## Documentation and internal changes
#### Documentation and internal changes
* Provide tests for hashing of `OperandHolder` in [#9437](https://github.com/encode/django-rest-framework/pull/9437)
* Update documentation: Add `adrf` third party package in [#9198](https://github.com/encode/django-rest-framework/pull/9198)
@ -94,7 +157,7 @@ This release is considered a significant release to improve upstream support wit
* Fix a number of typos in the test suite in the docs in [#9662](https://github.com/encode/django-rest-framework/pull/9662)
* Add `django-pyoidc` as a third party authentication library in [#9667](https://github.com/encode/django-rest-framework/pull/9667)
## New Contributors
#### New Contributors
* [`@maerteijn`](https://github.com/maerteijn) made their first contribution in [#9198](https://github.com/encode/django-rest-framework/pull/9198)
* [`@FraCata00`](https://github.com/FraCata00) made their first contribution in [#9444](https://github.com/encode/django-rest-framework/pull/9444)
@ -152,7 +215,7 @@ Date: 15th March 2024
* Partial serializer should not have required fields [[#7563](https://github.com/encode/django-rest-framework/pull/7563)]
* Propagate 'default' from model field to serializer field. [[#9030](https://github.com/encode/django-rest-framework/pull/9030)]
* Allow to override child.run_validation call in ListSerializer [[#8035](https://github.com/encode/django-rest-framework/pull/8035)]
* Align SearchFilter behaviour to django.contrib.admin search [[#9017](https://github.com/encode/django-rest-framework/pull/9017)]
* Align SearchFilter behavior to django.contrib.admin search [[#9017](https://github.com/encode/django-rest-framework/pull/9017)]
* Class name added to unknown field error [[#9019](https://github.com/encode/django-rest-framework/pull/9019)]
* Fix: Pagination response schemas. [[#9049](https://github.com/encode/django-rest-framework/pull/9049)]
* Fix choices in ChoiceField to support IntEnum [[#8955](https://github.com/encode/django-rest-framework/pull/8955)]
@ -306,7 +369,7 @@ Date: 28th September 2020
* Add `--file` option to `generateschema` command. [#7130]
* Support `tags` for OpenAPI schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#grouping-operations-with-tags). [#7184]
* Support customising the operation ID for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#operationid). [#7190]
* Support customizing the operation ID for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#operationid). [#7190]
* Support OpenAPI components for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#components). [#7124]
* The following methods on `AutoSchema` become public API: `get_path_parameters`, `get_pagination_parameters`, `get_filter_parameters`, `get_request_body`, `get_responses`, `get_serializer`, `get_paginator`, `map_serializer`, `map_field`, `map_choice_field`, `map_field_validators`, `allows_filters`. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#autoschema)
* Add support for Django 3.1's database-agnositic `JSONField`. [#7467]
@ -344,7 +407,7 @@ Date: 28th September 2020
* Fix `PrimaryKeyRelatedField` and `HyperlinkedRelatedField` when source field is actually a property. [#7142]
* `Token.generate_key` is now a class method. [#7502]
* `@action` warns if method is wrapped in a decorator that does not preserve information using `@functools.wraps`. [#7098]
* Deprecate `serializers.NullBooleanField` in favour of `serializers.BooleanField` with `allow_null=True` [#7122]
* Deprecate `serializers.NullBooleanField` in favor of `serializers.BooleanField` with `allow_null=True` [#7122]
---
@ -354,7 +417,7 @@ Date: 28th September 2020
**Date**: 30th September 2020
* **Security**: Drop `urlize_quoted_links` template tag in favour of Django's built-in `urlize`. Removes a XSS vulnerability for some kinds of content in the browsable API.
* **Security**: Drop `urlize_quoted_links` template tag in favor of Django's built-in `urlize`. Removes a XSS vulnerability for some kinds of content in the browsable API.
### 3.11.1
@ -366,7 +429,7 @@ Date: 28th September 2020
**Date**: 12th December 2019
* Drop `.set_context` API [in favour of a `requires_context` marker](3.11-announcement.md#validator-default-context).
* Drop `.set_context` API [in favor of a `requires_context` marker](3.11-announcement.md#validator-default-context).
* Changed default widget for TextField with choices to select box. [#6892][gh6892]
* Supported nested writes on non-relational fields, such as JSONField. [#6916][gh6916]
* Include request/response media types in OpenAPI schemas, based on configured parsers/renderers. [#6865][gh6865]
@ -558,13 +621,13 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
**Date**: [3rd April 2018][3.8.0-milestone]
* **Breaking Change**: Alter `read_only` plus `default` behaviour. [#5886][gh5886]
* **Breaking Change**: Alter `read_only` plus `default` behavior. [#5886][gh5886]
`read_only` fields will now **always** be excluded from writable fields.
Previously `read_only` fields with a `default` value would use the `default` for create and update operations.
In order to maintain the old behaviour you may need to pass the value of `read_only` fields when calling `save()` in
In order to maintain the old behavior you may need to pass the value of `read_only` fields when calling `save()` in
the view:
def perform_create(self, serializer):
@ -572,13 +635,13 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
Alternatively you may override `save()` or `create()` or `update()` on the serializer as appropriate.
* Correct allow_null behaviour when required=False [#5888][gh5888]
* Correct allow_null behavior when required=False [#5888][gh5888]
Without an explicit `default`, `allow_null` implies a default of `null` for outgoing serialization. Previously such
fields were being skipped when read-only or otherwise not required.
**Possible backwards compatibility break** if you were relying on such fields being excluded from the outgoing
representation. In order to restore the old behaviour you can override `data` to exclude the field when `None`.
representation. In order to restore the old behavior you can override `data` to exclude the field when `None`.
For example:
@ -635,7 +698,7 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
* Add HStoreField, postgres fields tests [#5654][gh5654]
* Always fully qualify ValidationError in docs [#5751][gh5751]
* Remove unreachable code from ManualSchema [#5766][gh5766]
* Allowed customising API documentation code samples [#5752][gh5752]
* Allowed customizing API documentation code samples [#5752][gh5752]
* Updated docs to use `pip show` [#5757][gh5757]
* Load 'static' instead of 'staticfiles' in templates [#5773][gh5773]
* Fixed a typo in `fields` docs [#5783][gh5783]
@ -698,7 +761,7 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
* Schema: Extract method for `manual_fields` processing [#5633][gh5633]
Allows for easier customisation of `manual_fields` processing, for example
Allows for easier customization of `manual_fields` processing, for example
to provide per-method manual fields. `AutoSchema` adds `get_manual_fields`,
as the intended override point, and a utility method `update_fields`, to
handle by-name field replacement from a list, which, in general, you are not
@ -820,7 +883,7 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
* Don't strip microseconds from `time` when encoding. Makes consistent with `datetime`.
**BC Change**: Previously only milliseconds were encoded. [#5440][gh5440]
* Added `STRICT_JSON` setting (default `True`) to raise exception for the extended float values (`nan`, `inf`, `-inf`) accepted by Python's `json` module.
**BC Change**: Previously these values would converted to corresponding strings. Set `STRICT_JSON` to `False` to restore the previous behaviour. [#5265][gh5265]
**BC Change**: Previously these values would converted to corresponding strings. Set `STRICT_JSON` to `False` to restore the previous behavior. [#5265][gh5265]
* Add support for `page_size` parameter in CursorPaginator class [#5250][gh5250]
* Make `DEFAULT_PAGINATION_CLASS` `None` by default.
**BC Change**: If your were **just** setting `PAGE_SIZE` to enable pagination you will need to add `DEFAULT_PAGINATION_CLASS`.
@ -858,10 +921,10 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
* Fix naming collisions in Schema Generation [#5464][gh5464]
* Call Django's authenticate function with the request object [#5295][gh5295]
* Update coreapi JS to 0.1.1 [#5479][gh5479]
* Have `is_list_view` recognise RetrieveModel… views [#5480][gh5480]
* Have `is_list_view` recognize RetrieveModel… views [#5480][gh5480]
* Remove Django 1.8 & 1.9 compatibility code [#5481][gh5481]
* Remove deprecated schema code from DefaultRouter [#5482][gh5482]
* Refactor schema generation to allow per-view customisation.
* Refactor schema generation to allow per-view customization.
**BC Change**: `SchemaGenerator.get_serializer_fields` has been refactored as `AutoSchema.get_serializer_fields` and drops the `view` argument [#5354][gh5354]
## 3.6.x series

View File

@ -32,7 +32,7 @@ We suggest adding your package to the [REST Framework][rest-framework-grid] grid
#### Adding to the Django REST framework docs
Create a [Pull Request][drf-create-pr] or [Issue][drf-create-issue] on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under **Third party packages** of the API Guide section that best applies, like [Authentication][authentication] or [Permissions][permissions]. You can also link your package under the [Third Party Packages][third-party-packages] section.
Create a [Pull Request][drf-create-pr] on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under **Third party packages** of the API Guide section that best applies, like [Authentication][authentication] or [Permissions][permissions]. You can also link your package under the [Third Party Packages][third-party-packages] section.
#### Announce on the discussion group.
@ -44,7 +44,7 @@ Django REST Framework has a growing community of developers, packages, and resou
Check out a grid detailing all the packages and ecosystem around Django REST Framework at [Django Packages][rest-framework-grid].
To submit new content, [open an issue][drf-create-issue] or [create a pull request][drf-create-pr].
To submit new content, [create a pull request][drf-create-pr].
## Async Support
@ -58,6 +58,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [hawkrest][hawkrest] - Provides Hawk HTTP Authorization.
* [djangorestframework-httpsignature][djangorestframework-httpsignature] - Provides an easy to use HTTP Signature Authentication mechanism.
* [djoser][djoser] - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.
* [DRF Auth Kit][drf-auth-kit] - Provides complete REST authentication with JWT cookies, social login, MFA, and user management. Features full type safety and automatic OpenAPI schema generation.
* [dj-rest-auth][dj-rest-auth] - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.
* [drf-oidc-auth][drf-oidc-auth] - Implements OpenID Connect token authentication for DRF.
* [drfpasswordless][drfpasswordless] - Adds (Medium, Square Cash inspired) passwordless logins and signups via email and mobile numbers.
@ -72,6 +73,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [dry-rest-permissions][dry-rest-permissions] - Provides a simple way to define permissions for individual api actions.
* [drf-access-policy][drf-access-policy] - Declarative and flexible permissions inspired by AWS' IAM policies.
* [drf-psq][drf-psq] - An extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.
* [axioms-drf-py][axioms-drf-py] - Supports authentication and claim-based fine-grained authorization (**scopes**, **roles**, **groups**, **permissions**, etc. including object-level checks) using JWT tokens issued by an OAuth2/OIDC Authorization Server.
### Serializers
@ -88,6 +90,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [djangorestframework-dataclasses][djangorestframework-dataclasses] - Serializer providing automatic field generation for Python dataclasses, like the built-in ModelSerializer does for models.
* [django-restql][django-restql] - Turn your REST API into a GraphQL like API(It allows clients to control which fields will be sent in a response, uses GraphQL like syntax, supports read and write on both flat and nested fields).
* [graphwrap][graphwrap] - Transform your REST API into a fully compliant GraphQL API with just two lines of code. Leverages [Graphene-Django](https://docs.graphene-python.org/projects/django/en/latest/) to dynamically build, at runtime, a GraphQL ObjectType for each view in your API.
* [drf-shapeless-serializers][drf-shapeless-serializers] - Dynamically assemble, configure, and shape your Django Rest Framework serializers at runtime, much like connecting Lego bricks.
### Serializer fields
@ -126,7 +129,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [djangorestframework-chain][djangorestframework-chain] - Allows arbitrary chaining of both relations and lookup filters.
* [django-url-filter][django-url-filter] - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.
* [drf-url-filter][drf-url-filter] is a simple Django app to apply filters on drf `ModelViewSet`'s `Queryset` in a clean, simple and configurable way. It also supports validations on incoming query params and their values.
* [django-rest-framework-guardian2][django-rest-framework-guardian2] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF.
* [django-rest-framework-guardian][django-rest-framework-guardian] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF.
### Misc
@ -149,17 +152,20 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [django-rest-framework-condition][django-rest-framework-condition] - Decorators for managing HTTP cache headers for Django REST framework (ETag and Last-modified).
* [django-rest-witchcraft][django-rest-witchcraft] - Provides DRF integration with SQLAlchemy with SQLAlchemy model serializers/viewsets and a bunch of other goodies
* [djangorestframework-mvt][djangorestframework-mvt] - An extension for creating views that serve Postgres data as Map Box Vector Tiles.
* [drf-viewset-profiler][drf-viewset-profiler] - Lib to profile all methods from a viewset line by line.
* [drf-viewset-profiler][drf-viewset-profiler] - Lib to profile all methods from a viewset line by line.
* [djangorestframework-features][djangorestframework-features] - Advanced schema generation and more based on named features.
* [django-elasticsearch-dsl-drf][django-elasticsearch-dsl-drf] - Integrate Elasticsearch DSL with Django REST framework. Package provides views, serializers, filter backends, pagination and other handy add-ons.
* [django-lisan][django-lisan] - A lightweight translation and localization framework for Django REST Framework APIs.
* [django-api-client][django-api-client] - DRF client that groups the Endpoint response, for use in CBVs and FBV as if you were working with Django's Native Models..
* [fast-drf] - A model based library for making API development faster and easier.
* [django-requestlogs] - Providing middleware and other helpers for audit logging for REST framework.
* [drf-standardized-errors][drf-standardized-errors] - DRF exception handler to standardize error responses for all API endpoints.
* [drf-api-action][drf-api-action] - uses the power of DRF also as a library functions
* [apitally] - A simple API monitoring, analytics, and request logging tool using middleware. For DRF-specific setup guide, [click here](https://docs.apitally.io/frameworks/django-rest-framework).
### Customization
* [drf-restwind][drf-restwind] - a modern re-imagining of the Django REST Framework utilizes TailwindCSS and DaisyUI to provide flexible and customizable UI solutions with minimal coding effort.
* [drf-redesign][drf-redesign] - A project that gives a fresh look to the browse-able API using Bootstrap 5.
* [drf-material][drf-material] - A project that gives a sleek and elegant look to the browsable API using Material Design.
@ -171,14 +177,14 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
[pypi-register]: https://pypi.org/account/register/
[semver]: https://semver.org/
[tox-docs]: https://tox.readthedocs.io/en/latest/
[drf-compat]: https://github.com/encode/django-rest-framework/blob/master/rest_framework/compat.py
[drf-compat]: https://github.com/encode/django-rest-framework/blob/main/rest_framework/compat.py
[rest-framework-grid]: https://www.djangopackages.com/grids/g/django-rest-framework/
[drf-create-pr]: https://github.com/encode/django-rest-framework/compare
[drf-create-issue]: https://github.com/encode/django-rest-framework/issues/new
[authentication]: ../api-guide/authentication.md
[permissions]: ../api-guide/permissions.md
[third-party-packages]: ../topics/third-party-packages/#existing-third-party-packages
[third-party-packages]: #existing-third-party-packages
[discussion-group]: https://groups.google.com/forum/#!forum/django-rest-framework
[drf-auth-kit]: https://github.com/huynguyengl99/drf-auth-kit
[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
[django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
[djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt
@ -242,7 +248,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
[djangorestframework-dataclasses]: https://github.com/oxan/djangorestframework-dataclasses
[django-restql]: https://github.com/yezyilomo/django-restql
[djangorestframework-mvt]: https://github.com/corteva/djangorestframework-mvt
[django-rest-framework-guardian2]: https://github.com/johnthagen/django-rest-framework-guardian2
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
[drf-viewset-profiler]: https://github.com/fvlima/drf-viewset-profiler
[djangorestframework-features]: https://github.com/cloudcode-hungary/django-rest-framework-features/
[django-elasticsearch-dsl-drf]: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf
@ -255,6 +261,11 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
[django-requestlogs]: https://github.com/Raekkeri/django-requestlogs
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors
[drf-api-action]: https://github.com/Ori-Roza/drf-api-action
[drf-restwind]: https://github.com/youzarsiph/drf-restwind
[drf-redesign]: https://github.com/youzarsiph/drf-redesign
[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
[django-lisan]: https://github.com/Nabute/django-lisan
[axioms-drf-py]: https://github.com/abhishektiwari/axioms-drf-py

BIN
docs/img/drf-m-api-root.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

BIN
docs/img/drf-r-api-root.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

View File

@ -53,33 +53,7 @@ Some reasons you might want to use REST framework:
* [Serialization][serializers] that supports both [ORM][modelserializer-section] and [non-ORM][serializer-section] data sources.
* Customizable all the way down - just use [regular function-based views][functionview-section] if you don't need the [more][generic-views] [powerful][viewsets] [features][routers].
* Extensive documentation, and [great community support][group].
* Used and trusted by internationally recognised companies including [Mozilla][mozilla], [Red Hat][redhat], [Heroku][heroku], and [Eventbrite][eventbrite].
---
## Funding
REST framework is a *collaboratively funded project*. If you use
REST framework commercially we strongly encourage you to invest in its
continued development by **[signing up for a paid plan][funding]**.
*Every single sign-up helps us make REST framework long-term financially sustainable.*
<ul class="premium-promo promo">
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
<li><a href="https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
<li><a href="https://www.spacinov.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/spacinov.png)">Spacinov</a></li>
<li><a href="https://retool.com/?utm_source=djangorest&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/retool-sidebar.png)">Retool</a></li>
<li><a href="https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/bitio_logo_gold_background.png)">bit.io</a></li>
<li><a href="https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/135996800-d49fe024-32d9-441a-98d9-4c7596287a67.png)">PostHog</a></li>
<li><a href="https://cryptapi.io" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cryptapi.png)">CryptAPI</a></li>
<li><a href="https://www.fezto.xyz/?utm_source=DjangoRESTFramework" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/fezto.png)">FEZTO</a></li>
<li><a href="https://www.svix.com/?utm_source=django-REST&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/svix.png)">Svix</a></li>
<li><a href="https://zuplo.link/django-web" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/zuplo.png)">Zuplo</a></li>
</ul>
<div style="clear: both; padding-bottom: 20px;"></div>
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage), [Spacinov](https://www.spacinov.com/), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [PostHog](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [CryptAPI](https://cryptapi.io), [FEZTO](https://www.fezto.xyz/?utm_source=DjangoRESTFramework), [Svix](https://www.svix.com/?utm_source=django-REST&utm_medium=sponsorship), , and [Zuplo](https://zuplo.link/django-web).*
* Used and trusted by internationally recognized companies including [Mozilla][mozilla], [Red Hat][redhat], [Heroku][heroku], and [Eventbrite][eventbrite].
---
@ -88,7 +62,7 @@ continued development by **[signing up for a paid plan][funding]**.
REST framework requires the following:
* Django (4.2, 5.0, 5.1, 5.2)
* Python (3.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
each Python and Django series.
@ -192,8 +166,6 @@ Framework.
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.libera.chat`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
For priority support please sign up for a [professional or premium sponsorship plan](https://fund.django-rest-framework.org/topics/funding/).
## Security
**Please report security issues by emailing security@encode.io**.
@ -246,7 +218,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[serializer-section]: api-guide/serializers#serializers
[modelserializer-section]: api-guide/serializers#modelserializer
[functionview-section]: api-guide/views#function-based-views
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[quickstart]: tutorial/quickstart.md
@ -257,10 +228,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[authentication]: api-guide/authentication.md
[contributing]: community/contributing.md
[funding]: community/funding.md
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[stack-overflow]: https://stackoverflow.com/
[django-rest-framework-tag]: https://stackoverflow.com/questions/tagged/django-rest-framework
[security-mail]: mailto:rest-framework-security@googlegroups.com
[twitter]: https://twitter.com/_tomchristie

View File

@ -81,22 +81,43 @@ For more specific CSS tweaks than simply overriding the default bootstrap theme
### Third party packages for customization
You can use a third party package for customization, rather than doing it by yourself. Here is 2 packages for customizing the API:
You can use a third party package for customization, rather than doing it by yourself. Here is 3 packages for customizing the API:
* [rest-framework-redesign][rest-framework-redesign] - A package for customizing the API using Bootstrap 5. Modern and sleek design, it comes with the support for dark mode.
* [rest-framework-material][rest-framework-material] - Material design for Django REST Framework.
* [drf-restwind][drf-restwind] - a modern re-imagining of the Django REST Framework utilizes TailwindCSS and DaisyUI to provide flexible and customizable UI solutions with minimal coding effort.
* [drf-redesign][drf-redesign] - A package for customizing the API using Bootstrap 5. Modern and sleek design, it comes with the support for dark mode.
* [drf-material][drf-material] - Material design for Django REST Framework.
---
![Django REST Framework Redesign][rfr]
![API Root][drf-rw-api-root]
*Screenshot of the rest-framework-redesign*
![List View][drf-rw-list-view]
![Detail View][drf-rw-detail-view]
*Screenshots of the drf-restwind*
---
![Django REST Framework Material][rfm]
---
*Screenshot of the rest-framework-material*
![API Root][drf-r-api-root]
![List View][drf-r-list-view]
![Detail View][drf-r-detail-view]
*Screenshot of the drf-redesign*
---
![API Root][drf-m-api-root]
![List View][drf-m-api-root]
![Detail View][drf-m-api-root]
*Screenshot of the drf-material*
---
@ -160,7 +181,7 @@ The context that's available to the template:
* `FORMAT_PARAM` : The view can accept a format override
* `METHOD_PARAM` : The view can accept a method override
You can override the `BrowsableAPIRenderer.get_context()` method to customise the context that gets passed to the template.
You can override the `BrowsableAPIRenderer.get_context()` method to customize the context that gets passed to the template.
#### Not using base.html
@ -197,7 +218,15 @@ There are [a variety of packages for autocomplete widgets][autocomplete-packages
[bcomponentsnav]: https://getbootstrap.com/2.3.2/components.html#navbar
[autocomplete-packages]: https://www.djangopackages.com/grids/g/auto-complete/
[django-autocomplete-light]: https://github.com/yourlabs/django-autocomplete-light
[rest-framework-redesign]: https://github.com/youzarsiph/rest-framework-redesign
[rest-framework-material]: https://github.com/youzarsiph/rest-framework-material
[rfr]: ../img/rfr.png
[rfm]: ../img/rfm.png
[drf-restwind]: https://github.com/youzarsiph/drf-restwind
[drf-rw-api-root]: ../img/drf-rw-api-root.png
[drf-rw-list-view]: ../img/drf-rw-list-view.png
[drf-rw-detail-view]: ../img/drf-rw-detail-view.png
[drf-redesign]: https://github.com/youzarsiph/drf-redesign
[drf-r-api-root]: ../img/drf-r-api-root.png
[drf-r-list-view]: ../img/drf-r-list-view.png
[drf-r-detail-view]: ../img/drf-r-detail-view.png
[drf-material]: https://github.com/youzarsiph/drf-material
[drf-m-api-root]: ../img/drf-m-api-root.png
[drf-m-list-view]: ../img/drf-m-list-view.png
[drf-m-detail-view]: ../img/drf-m-detail-view.png

View File

@ -60,11 +60,12 @@ If you only wish to support a subset of the available languages, use Django's st
## Adding new translations
REST framework translations are managed online using [Transifex][transifex-project]. You can use the Transifex service to add new translation languages. The maintenance team will then ensure that these translation strings are included in the REST framework package.
REST framework translations are managed on GitHub. You can contribute new translation languages or update existing ones
by following the guidelines in the [Contributing to REST Framework] section and submitting a pull request.
Sometimes you may need to add translation strings to your project locally. You may need to do this if:
* You want to use REST Framework in a language which has not been translated yet on Transifex.
* You want to use REST Framework in a language which is not supported by the project.
* Your project includes custom error messages, which are not part of REST framework's default translation strings.
#### Translating a new language locally
@ -103,10 +104,10 @@ You can find more information on how the language preference is determined in th
For API clients the most appropriate of these will typically be to use the `Accept-Language` header; Sessions and cookies will not be available unless using session authentication, and generally better practice to prefer an `Accept-Language` header for API clients rather than using language URL prefixes.
[cite]: https://youtu.be/Wa0VfS2q94Y
[Contributing to REST Framework]: ../community/contributing.md#development
[django-translation]: https://docs.djangoproject.com/en/stable/topics/i18n/translation
[custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling
[transifex-project]: https://explore.transifex.com/django-rest-framework-1/django-rest-framework/
[django-po-source]: https://raw.githubusercontent.com/encode/django-rest-framework/master/rest_framework/locale/en_US/LC_MESSAGES/django.po
[django-po-source]: https://raw.githubusercontent.com/encode/django-rest-framework/main/rest_framework/locale/en_US/LC_MESSAGES/django.po
[django-language-preference]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#how-django-discovers-language-preference
[django-locale-paths]: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-LOCALE_PATHS
[django-locale-name]: https://docs.djangoproject.com/en/stable/topics/i18n/#term-locale-name

View File

@ -32,7 +32,7 @@ REST framework also includes [serialization] and [parser]/[renderer] components
## What REST framework doesn't provide.
What REST framework doesn't do is give you machine readable hypermedia formats such as [HAL][hal], [Collection+JSON][collection], [JSON API][json-api] or HTML [microformats] by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.
What REST framework doesn't do is give you machine readable hypermedia formats such as [HAL][hal], [Collection+JSON][collection], [JSON API][json-api] or HTML [microformats] by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labeled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.
[cite]: https://vimeo.com/channels/restfest/49503453
[dissertation]: https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

View File

@ -6,47 +6,55 @@ This tutorial will cover creating a simple pastebin code highlighting Web API.
The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the [quickstart] documentation instead.
---
**Note**: The code for this tutorial is available in the [encode/rest-framework-tutorial][repo] repository on GitHub. Feel free to clone the repository and see the code in action.
---
!!! note
The code for this tutorial is available in the [encode/rest-framework-tutorial][repo] repository on GitHub. Feel free to clone the repository and see the code in action.
## Setting up a new environment
Before we do anything else we'll create a new virtual environment, using [venv]. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.
python3 -m venv env
source env/bin/activate
```bash
python3 -m venv env
source env/bin/activate
```
Now that we're inside a virtual environment, we can install our package requirements.
pip install django
pip install djangorestframework
pip install pygments # We'll be using this for the code highlighting
```bash
pip install django
pip install djangorestframework
pip install pygments # We'll be using this for the code highlighting
```
**Note:** To exit the virtual environment at any time, just type `deactivate`. For more information see the [venv documentation][venv].
!!! tip
To exit the virtual environment at any time, just type `deactivate`. For more information see the [venv documentation][venv].
## Getting started
Okay, we're ready to get coding.
To get started, let's create a new project to work with.
cd ~
django-admin startproject tutorial
cd tutorial
```bash
cd ~
django-admin startproject tutorial
cd tutorial
```
Once that's done we can create an app that we'll use to create a simple Web API.
python manage.py startapp snippets
```bash
python manage.py startapp snippets
```
We'll need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. Let's edit the `tutorial/settings.py` file:
INSTALLED_APPS = [
...
'rest_framework',
'snippets',
]
```text
INSTALLED_APPS = [
...
'rest_framework',
'snippets',
]
```
Okay, we're ready to roll.
@ -54,64 +62,72 @@ Okay, we're ready to roll.
For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets/models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
```python
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default="")
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(
choices=LANGUAGE_CHOICES, default="python", max_length=100
)
style = models.CharField(choices=STYLE_CHOICES, default="friendly", max_length=100)
class Meta:
ordering = ['created']
class Meta:
ordering = ["created"]
```
We'll also need to create an initial migration for our snippet model, and sync the database for the first time.
python manage.py makemigrations snippets
python manage.py migrate snippets
```bash
python manage.py makemigrations snippets
python manage.py migrate snippets
```
## Creating a Serializer class
The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as `json`. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the `snippets` directory named `serializers.py` and add the following.
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
```python
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
class SnippetSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
code = serializers.CharField(style={'base_template': 'textarea.html'})
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
class SnippetSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
code = serializers.CharField(style={"base_template": "textarea.html"})
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default="python")
style = serializers.ChoiceField(choices=STYLE_CHOICES, default="friendly")
def create(self, validated_data):
"""
Create and return a new `Snippet` instance, given the validated data.
"""
return Snippet.objects.create(**validated_data)
def create(self, validated_data):
"""
Create and return a new `Snippet` instance, given the validated data.
"""
return Snippet.objects.create(**validated_data)
def update(self, instance, validated_data):
"""
Update and return an existing `Snippet` instance, given the validated data.
"""
instance.title = validated_data.get('title', instance.title)
instance.code = validated_data.get('code', instance.code)
instance.linenos = validated_data.get('linenos', instance.linenos)
instance.language = validated_data.get('language', instance.language)
instance.style = validated_data.get('style', instance.style)
instance.save()
return instance
def update(self, instance, validated_data):
"""
Update and return an existing `Snippet` instance, given the validated data.
"""
instance.title = validated_data.get("title", instance.title)
instance.code = validated_data.get("code", instance.code)
instance.linenos = validated_data.get("linenos", instance.linenos)
instance.language = validated_data.get("language", instance.language)
instance.style = validated_data.get("style", instance.style)
instance.save()
return instance
```
The first part of the serializer class defines the fields that get serialized/deserialized. The `create()` and `update()` methods define how fully fledged instances are created or modified when calling `serializer.save()`
@ -125,57 +141,71 @@ We can actually also save ourselves some time by using the `ModelSerializer` cla
Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.
python manage.py shell
```bash
python manage.py shell
```
Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
```pycon
>>> from snippets.models import Snippet
>>> from snippets.serializers import SnippetSerializer
>>> from rest_framework.renderers import JSONRenderer
>>> from rest_framework.parsers import JSONParser
snippet = Snippet(code='foo = "bar"\n')
snippet.save()
>>> snippet = Snippet(code='foo = "bar"\n')
>>> snippet.save()
snippet = Snippet(code='print("hello, world")\n')
snippet.save()
>>> snippet = Snippet(code='print("hello, world")\n')
>>> snippet.save()
```
We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.
serializer = SnippetSerializer(snippet)
serializer.data
# {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
```pycon
>>> serializer = SnippetSerializer(snippet)
>>> serializer.data
{'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
```
At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`.
content = JSONRenderer().render(serializer.data)
content
# b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}'
```pycon
>>> content = JSONRenderer().render(serializer.data)
>>> content
b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}'
```
Deserialization is similar. First we parse a stream into Python native datatypes...
import io
```pycon
>>> import io
stream = io.BytesIO(content)
data = JSONParser().parse(stream)
>>> stream = io.BytesIO(content)
>>> data = JSONParser().parse(stream)
```
...then we restore those native datatypes into a fully populated object instance.
serializer = SnippetSerializer(data=data)
serializer.is_valid()
# True
serializer.validated_data
# {'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}
serializer.save()
# <Snippet: Snippet object>
```pycon
>>> serializer = SnippetSerializer(data=data)
>>> serializer.is_valid()
True
>>> serializer.validated_data
{'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}
>>> serializer.save()
<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.
We can also serialize querysets instead of model instances. To do so we simply add a `many=True` flag to the serializer arguments.
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
# [{'id': 1, 'title': '', 'code': 'foo = "bar"\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 3, 'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}]
```pycon
>>> serializer = SnippetSerializer(Snippet.objects.all(), many=True)
>>> serializer.data
[{'id': 1, 'title': '', 'code': 'foo = "bar"\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 3, 'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}]
```
## Using ModelSerializers
@ -186,23 +216,28 @@ In the same way that Django provides both `Form` classes and `ModelForm` classes
Let's look at refactoring our serializer using the `ModelSerializer` class.
Open the file `snippets/serializers.py` again, and replace the `SnippetSerializer` class with the following.
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ['id', 'title', 'code', 'linenos', 'language', 'style']
```python
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ["id", "title", "code", "linenos", "language", "style"]
```
One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with `python manage.py shell`, then try the following:
from snippets.serializers import SnippetSerializer
serializer = SnippetSerializer()
print(repr(serializer))
# SnippetSerializer():
# id = IntegerField(label='ID', read_only=True)
# title = CharField(allow_blank=True, max_length=100, required=False)
# code = CharField(style={'base_template': 'textarea.html'})
# linenos = BooleanField(required=False)
# language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...
# style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...
```pycon
>>> from snippets.serializers import SnippetSerializer
>>> serializer = SnippetSerializer()
>>> print(repr(serializer))
SnippetSerializer():
id = IntegerField(label='ID', read_only=True)
title = CharField(allow_blank=True, max_length=100, required=False)
code = CharField(style={'base_template': 'textarea.html'})
linenos = BooleanField(required=False)
language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...
style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...
```
It's important to remember that `ModelSerializer` classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:
@ -216,79 +251,89 @@ For the moment we won't use any of REST framework's other features, we'll just w
Edit the `snippets/views.py` file, and add the following.
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
```python
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
```
The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.
@csrf_exempt
def snippet_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return JsonResponse(serializer.data, safe=False)
```python
@csrf_exempt
def snippet_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == "GET":
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = SnippetSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
elif request.method == "POST":
data = JSONParser().parse(request)
serializer = SnippetSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
```
Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as `csrf_exempt`. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.
We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.
@csrf_exempt
def snippet_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return HttpResponse(status=404)
```python
@csrf_exempt
def snippet_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = SnippetSerializer(snippet)
if request.method == "GET":
serializer = SnippetSerializer(snippet)
return JsonResponse(serializer.data)
elif request.method == "PUT":
data = JSONParser().parse(request)
serializer = SnippetSerializer(snippet, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = SnippetSerializer(snippet, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
snippet.delete()
return HttpResponse(status=204)
elif request.method == "DELETE":
snippet.delete()
return HttpResponse(status=204)
```
Finally we need to wire these views up. Create the `snippets/urls.py` file:
from django.urls import path
from snippets import views
```python
from django.urls import path
from snippets import views
urlpatterns = [
path('snippets/', views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail),
]
urlpatterns = [
path("snippets/", views.snippet_list),
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.
from django.urls import path, include
```python
from django.urls import path, include
urlpatterns = [
path('', include('snippets.urls')),
]
urlpatterns = [
path("", include("snippets.urls")),
]
```
It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.
@ -298,18 +343,22 @@ Now we can start up a sample server that serves our snippets.
Quit out of the shell...
quit()
```pycon
>>> quit()
```
...and start up Django's development server.
python manage.py runserver
```bash
python manage.py runserver
Validating models...
Validating models...
0 errors found
Django version 5.0, using settings 'tutorial.settings'
Starting Development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
0 errors found
Django version 5.0, using settings 'tutorial.settings'
Starting Development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
```
In another terminal window, we can test the server.
@ -317,47 +366,26 @@ We can test our API using [curl][curl] or [httpie][httpie]. Httpie is a user fri
You can install httpie using pip:
pip install httpie
```bash
pip install httpie
```
Finally, we can get a list of all of the snippets:
http GET http://127.0.0.1:8000/snippets/ --unsorted
```bash
http GET http://127.0.0.1:8000/snippets/ --unsorted
HTTP/1.1 200 OK
...
[
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 2,
"title": "",
"code": "print(\"hello, world\")\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 3,
"title": "",
"code": "print(\"hello, world\")",
"linenos": false,
"language": "python",
"style": "friendly"
}
]
Or we can get a particular snippet by referencing its id:
http GET http://127.0.0.1:8000/snippets/2/ --unsorted
HTTP/1.1 200 OK
...
HTTP/1.1 200 OK
...
[
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 2,
"title": "",
@ -365,7 +393,34 @@ Or we can get a particular snippet by referencing its id:
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 3,
"title": "",
"code": "print(\"hello, world\")",
"linenos": false,
"language": "python",
"style": "friendly"
}
]
```
Or we can get a particular snippet by referencing its id:
```bash
http GET http://127.0.0.1:8000/snippets/2/ --unsorted
HTTP/1.1 200 OK
...
{
"id": 2,
"title": "",
"code": "print(\"hello, world\")\n",
"linenos": false,
"language": "python",
"style": "friendly"
}
```
Similarly, you can have the same json displayed by visiting these URLs in a web browser.

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.
request.POST # Only handles form data. Only works for 'POST' method.
request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
```python
request.POST # Only handles form data. Only works for 'POST' method.
request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
```
## Response objects
REST framework also introduces a `Response` object, which is a type of `TemplateResponse` that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.
return Response(data) # Renders to content type as requested by the client.
```python
return Response(data) # Renders to content type as requested by the client.
```
## Status codes
@ -35,58 +39,62 @@ The wrappers also provide behavior such as returning `405 Method Not Allowed` re
Okay, let's go ahead and start using these new components to refactor our views slightly.
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
```python
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
@api_view(['GET', 'POST'])
def snippet_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
@api_view(["GET", "POST"])
def snippet_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == "GET":
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = SnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == "POST":
serializer = SnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
```
Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
Here is the view for an individual snippet, in the `views.py` module.
@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
```python
@api_view(["GET", "PUT", "DELETE"])
def snippet_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = SnippetSerializer(snippet)
if request.method == "GET":
serializer = SnippetSerializer(snippet)
return Response(serializer.data)
elif request.method == "PUT":
serializer = SnippetSerializer(snippet, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'PUT':
serializer = SnippetSerializer(snippet, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
elif request.method == "DELETE":
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
```
This should all feel very familiar - it is not a lot different from working with regular Django views.
@ -94,28 +102,27 @@ Notice that we're no longer explicitly tying our requests or responses to a give
## Adding optional format suffixes to our URLs
To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4.json][json-url].
To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [<http://example.com/api/items/4.json>][json-url].
Start by adding a `format` keyword argument to both of the views, like so.
def snippet_list(request, format=None):
`def snippet_list(request, format=None):`
and
def snippet_detail(request, pk, format=None):
`def snippet_detail(request, pk, format=None):`
Now update the `snippets/urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs.
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
```python
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
urlpatterns = [
path('snippets/', views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail),
]
urlpatterns = [
path("snippets/", views.snippet_list),
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.
@ -125,68 +132,76 @@ Go ahead and test the API from the command line, as we did in [tutorial part 1][
We can get a list of all of the snippets, as before.
http http://127.0.0.1:8000/snippets/
```bash
http http://127.0.0.1:8000/snippets/
HTTP/1.1 200 OK
...
[
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 2,
"title": "",
"code": "print(\"hello, world\")\n",
"linenos": false,
"language": "python",
"style": "friendly"
}
]
HTTP/1.1 200 OK
...
[
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 2,
"title": "",
"code": "print(\"hello, world\")\n",
"linenos": false,
"language": "python",
"style": "friendly"
}
]
```
We can control the format of the response that we get back, either by using the `Accept` header:
http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON
http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML
```bash
http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON
http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML
```
Or by appending a format suffix:
http http://127.0.0.1:8000/snippets.json # JSON suffix
http http://127.0.0.1:8000/snippets.api # Browsable API suffix
```bash
http http://127.0.0.1:8000/snippets.json # JSON suffix
http http://127.0.0.1:8000/snippets.api # Browsable API suffix
```
Similarly, we can control the format of the request that we send, using the `Content-Type` header.
# POST using form data
http --form POST http://127.0.0.1:8000/snippets/ code="print(123)"
```bash
# POST using form data
http --form POST http://127.0.0.1:8000/snippets/ code="print(123)"
{
"id": 3,
"title": "",
"code": "print(123)",
"linenos": false,
"language": "python",
"style": "friendly"
}
{
"id": 3,
"title": "",
"code": "print(123)",
"linenos": false,
"language": "python",
"style": "friendly"
}
# POST using JSON
http --json POST http://127.0.0.1:8000/snippets/ code="print(456)"
# POST using JSON
http --json POST http://127.0.0.1:8000/snippets/ code="print(456)"
{
"id": 4,
"title": "",
"code": "print(456)",
"linenos": false,
"language": "python",
"style": "friendly"
}
{
"id": 4,
"title": "",
"code": "print(456)",
"linenos": false,
"language": "python",
"style": "friendly"
}
```
If you add a `--debug` switch to the `http` requests above, you will be able to see the request type in request headers.
Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver].
Now go and open the API in a web browser, by visiting [<http://127.0.0.1:8000/snippets/>][devserver].
### 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`.
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
```python
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class SnippetList(APIView):
"""
List all snippets, or create a new snippet.
"""
def get(self, request, format=None):
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
class SnippetList(APIView):
"""
List all snippets, or create a new snippet.
"""
def post(self, request, format=None):
serializer = SnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, format=None):
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = SnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
```
So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view in `views.py`.
class SnippetDetail(APIView):
"""
Retrieve, update or delete a snippet instance.
"""
def get_object(self, pk):
try:
return Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
raise Http404
```python
class SnippetDetail(APIView):
"""
Retrieve, update or delete a snippet instance.
"""
def get(self, request, pk, format=None):
snippet = self.get_object(pk)
serializer = SnippetSerializer(snippet)
def get_object(self, pk):
try:
return Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
snippet = self.get_object(pk)
serializer = SnippetSerializer(snippet)
return Response(serializer.data)
def put(self, request, pk, format=None):
snippet = self.get_object(pk)
serializer = SnippetSerializer(snippet, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk, format=None):
snippet = self.get_object(pk)
serializer = SnippetSerializer(snippet, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
snippet = self.get_object(pk)
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
def delete(self, request, pk, format=None):
snippet = self.get_object(pk)
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
```
That's looking good. Again, it's still pretty similar to the function based view right now.
We'll also need to refactor our `snippets/urls.py` slightly now that we're using class-based views.
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
```python
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
urlpatterns = [
path('snippets/', views.SnippetList.as_view()),
path('snippets/<int:pk>/', views.SnippetDetail.as_view()),
]
urlpatterns = [
path("snippets/", views.SnippetList.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.
@ -85,42 +93,49 @@ The create/retrieve/update/delete operations that we've been using so far are go
Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again.
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import mixins
from rest_framework import generics
```python
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import mixins
from rest_framework import generics
class SnippetList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class SnippetList(
mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView
):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
```
We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`.
The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far.
class SnippetDetail(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
```python
class SnippetDetail(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView,
):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
```
Pretty similar. Again we're using the `GenericAPIView` class to provide the core functionality, and adding in mixins to provide the `.retrieve()`, `.update()` and `.destroy()` actions.
@ -128,19 +143,21 @@ Pretty similar. Again we're using the `GenericAPIView` class to provide the cor
Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our `views.py` module even more.
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics
```python
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
```
Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.

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`.
owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
highlighted = models.TextField()
```python
owner = models.ForeignKey(
"auth.User", related_name="snippets", on_delete=models.CASCADE
)
highlighted = models.TextField()
```
We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code highlighting library.
We'll need some extra imports:
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight
```python
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight
```
And now we can add a `.save()` method to our model class:
def save(self, *args, **kwargs):
"""
Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
linenos = 'table' if self.linenos else False
options = {'title': self.title} if self.title else {}
formatter = HtmlFormatter(style=self.style, linenos=linenos,
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super().save(*args, **kwargs)
```python
def save(self, *args, **kwargs):
"""
Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
linenos = "table" if self.linenos else False
options = {"title": self.title} if self.title else {}
formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super().save(*args, **kwargs)
```
When that's all done we'll need to update our database tables.
Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
rm -f db.sqlite3
rm -r snippets/migrations
python manage.py makemigrations snippets
python manage.py migrate
```bash
rm -f db.sqlite3
rm -r snippets/migrations
python manage.py makemigrations snippets
python manage.py migrate
```
You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the `createsuperuser` command.
python manage.py createsuperuser
```bash
python manage.py createsuperuser
```
## Adding endpoints for our User models
Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In `serializers.py` add:
from django.contrib.auth.models import User
```python
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
class Meta:
model = User
fields = ['id', 'username', 'snippets']
class UserSerializer(serializers.ModelSerializer):
snippets = serializers.PrimaryKeyRelatedField(
many=True, queryset=Snippet.objects.all()
)
class Meta:
model = User
fields = ["id", "username", "snippets"]
```
Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it.
We'll also add a couple of views to `views.py`. We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class-based views.
from django.contrib.auth.models import User
```python
from django.contrib.auth.models import User
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
```
Make sure to also import the `UserSerializer` class
from snippets.serializers import UserSerializer
```python
from snippets.serializers import UserSerializer
```
Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `snippets/urls.py`.
path('users/', views.UserList.as_view()),
path('users/<int:pk>/', views.UserDetail.as_view()),
```python
path("users/", views.UserList.as_view()),
path("users/<int:pk>/", views.UserDetail.as_view()),
```
## Associating Snippets with Users
@ -98,8 +120,10 @@ The way we deal with that is by overriding a `.perform_create()` method on our s
On the `SnippetList` view class, add the following method:
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
```python
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
```
The `create()` method of our serializer will now be passed an additional `'owner'` field, along with the validated data from the request.
@ -107,9 +131,12 @@ The `create()` method of our serializer will now be passed an additional `'owner
Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition in `serializers.py`:
owner = serializers.ReadOnlyField(source='owner.username')
```python
owner = serializers.ReadOnlyField(source="owner.username")
```
**Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.
!!! note
Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.
This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.
@ -123,11 +150,15 @@ REST framework includes a number of permission classes that we can use to restri
First add the following import in the views module
from rest_framework import permissions
```python
from rest_framework import permissions
```
Then, add the following property to **both** the `SnippetList` and `SnippetDetail` view classes.
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
```python
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
```
## Adding login to the Browsable API
@ -137,13 +168,17 @@ We can add a login view for use with the browsable API, by editing the URLconf i
Add the following import at the top of the file:
from django.urls import path, include
```python
from django.urls import path, include
```
And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
urlpatterns += [
path('api-auth/', include('rest_framework.urls')),
]
```python
urlpatterns += [
path("api-auth/", include("rest_framework.urls")),
]
```
The `'api-auth/'` part of pattern can actually be whatever URL you want to use.
@ -159,31 +194,36 @@ To do that we're going to need to create a custom permission.
In the snippets app, create a new file, `permissions.py`
from rest_framework import permissions
```python
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the owner of the snippet.
return obj.owner == request.user
# Write permissions are only allowed to the owner of the snippet.
return obj.owner == request.user
```
Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` view class:
permission_classes = [permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly]
```python
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
```
Make sure to also import the `IsOwnerOrReadOnly` class.
from snippets.permissions import IsOwnerOrReadOnly
```python
from snippets.permissions import IsOwnerOrReadOnly
```
Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.
@ -197,25 +237,29 @@ If we're interacting with the API programmatically we need to explicitly provide
If we try to create a snippet without authenticating, we'll get an error:
http POST http://127.0.0.1:8000/snippets/ code="print(123)"
```bash
http POST http://127.0.0.1:8000/snippets/ code="print(123)"
{
"detail": "Authentication credentials were not provided."
}
{
"detail": "Authentication credentials were not provided."
}
```
We can make a successful request by including the username and password of one of the users we created earlier.
http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)"
```bash
http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)"
{
"id": 1,
"owner": "admin",
"title": "foo",
"code": "print(789)",
"linenos": false,
"language": "python",
"style": "friendly"
}
{
"id": 1,
"owner": "admin",
"title": "foo",
"code": "print(789)",
"linenos": false,
"language": "python",
"style": "friendly"
}
```
## Summary

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:
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
```python
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
@api_view(['GET'])
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request, format=format)
})
@api_view(["GET"])
def api_root(request, format=None):
return Response(
{
"users": reverse("user-list", request=request, format=format),
"snippets": reverse("snippet-list", request=request, format=format),
}
)
```
Two things should be noticed here. First, we're using REST framework's `reverse` function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our `snippets/urls.py`.
@ -30,24 +34,31 @@ The other thing we need to consider when creating the code highlight view is tha
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets/views.py` add:
from rest_framework import renderers
```python
from rest_framework import renderers
class SnippetHighlight(generics.GenericAPIView):
queryset = Snippet.objects.all()
renderer_classes = [renderers.StaticHTMLRenderer]
def get(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
class SnippetHighlight(generics.GenericAPIView):
queryset = Snippet.objects.all()
renderer_classes = [renderers.StaticHTMLRenderer]
def get(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
```
As usual we need to add the new views that we've created in to our URLconf.
We'll add a url pattern for our new API root in `snippets/urls.py`:
path('', views.api_root),
```python
path("", views.api_root),
```
And then add a url pattern for the snippet highlights:
path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view()),
```python
path("snippets/<int:pk>/highlight/", views.SnippetHighlight.as_view()),
```
## Hyperlinking our API
@ -73,27 +84,53 @@ The `HyperlinkedModelSerializer` has the following differences from `ModelSerial
We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add:
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
```python
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source="owner.username")
highlight = serializers.HyperlinkedIdentityField(
view_name="snippet-highlight", format="html"
)
class Meta:
model = Snippet
fields = ['url', 'id', 'highlight', 'owner',
'title', 'code', 'linenos', 'language', 'style']
class Meta:
model = Snippet
fields = [
"url",
"id",
"highlight",
"owner",
"title",
"code",
"linenos",
"language",
"style",
]
class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)
class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.HyperlinkedRelatedField(
many=True, view_name="snippet-detail", read_only=True
)
class Meta:
model = User
fields = ['url', 'id', 'username', 'snippets']
class Meta:
model = User
fields = ["url", "id", "username", "snippets"]
```
Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern.
Because we've included format suffixed URLs such as `'.json'`, we also need to indicate on the `highlight` field that any format suffixed hyperlinks it returns should use the `'.html'` suffix.
!!! note
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)
You must write:
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.
## Making sure our URL patterns are named
If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.
@ -105,29 +142,29 @@ If we're going to have a hyperlinked API, we need to make sure we name our URL p
After adding all those names into our URLconf, our final `snippets/urls.py` file should look like this:
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
```python
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
# API endpoints
urlpatterns = format_suffix_patterns([
path('', views.api_root),
path('snippets/',
views.SnippetList.as_view(),
name='snippet-list'),
path('snippets/<int:pk>/',
views.SnippetDetail.as_view(),
name='snippet-detail'),
path('snippets/<int:pk>/highlight/',
# API endpoints
urlpatterns = format_suffix_patterns(
[
path("", views.api_root),
path("snippets/", views.SnippetList.as_view(), name="snippet-list"),
path(
"snippets/<int:pk>/", views.SnippetDetail.as_view(), name="snippet-detail"
),
path(
"snippets/<int:pk>/highlight/",
views.SnippetHighlight.as_view(),
name='snippet-highlight'),
path('users/',
views.UserList.as_view(),
name='user-list'),
path('users/<int:pk>/',
views.UserDetail.as_view(),
name='user-detail')
])
name="snippet-highlight",
),
path("users/", views.UserList.as_view(), name="user-list"),
path("users/<int:pk>/", views.UserDetail.as_view(), name="user-detail"),
]
)
```
## Adding pagination
@ -135,10 +172,12 @@ The list views for users and code snippets could end up returning quite a lot of
We can change the default list style to use pagination, by modifying our `tutorial/settings.py` file slightly. Add the following setting:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
```python
REST_FRAMEWORK = {
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 10,
}
```
Note that settings in REST framework are all namespaced into a single dictionary setting, named `REST_FRAMEWORK`, which helps keep them well separated from your other project settings.

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:
from rest_framework import viewsets
```python
from rest_framework import viewsets
class UserViewSet(viewsets.ReadOnlyModelViewSet):
"""
This viewset automatically provides `list` and `retrieve` actions.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
class UserViewSet(viewsets.ReadOnlyModelViewSet):
"""
This viewset automatically provides `list` and `retrieve` actions.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
```
Here we've used the `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations. We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.
Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class.
from rest_framework import permissions
from rest_framework import renderers
from rest_framework.decorators import action
from rest_framework.response import Response
```python
from rest_framework import permissions
from rest_framework import renderers
from rest_framework.decorators import action
from rest_framework.response import Response
class SnippetViewSet(viewsets.ModelViewSet):
"""
This ViewSet automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
class SnippetViewSet(viewsets.ModelViewSet):
"""
This ViewSet automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action.
"""
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly]
Additionally we also provide an extra `highlight` action.
"""
@action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer])
def highlight(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
@action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer])
def highlight(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
```
This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations.
@ -67,42 +72,40 @@ To see what's going on under the hood let's first explicitly create a set of vie
In the `snippets/urls.py` file we bind our `ViewSet` classes into a set of concrete views.
from rest_framework import renderers
```python
from rest_framework import renderers
from snippets.views import api_root, SnippetViewSet, UserViewSet
from snippets.views import api_root, SnippetViewSet, UserViewSet
snippet_list = SnippetViewSet.as_view({
'get': 'list',
'post': 'create'
})
snippet_detail = SnippetViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
})
snippet_highlight = SnippetViewSet.as_view({
'get': 'highlight'
}, renderer_classes=[renderers.StaticHTMLRenderer])
user_list = UserViewSet.as_view({
'get': 'list'
})
user_detail = UserViewSet.as_view({
'get': 'retrieve'
})
snippet_list = SnippetViewSet.as_view({"get": "list", "post": "create"})
snippet_detail = SnippetViewSet.as_view(
{"get": "retrieve", "put": "update", "patch": "partial_update", "delete": "destroy"}
)
snippet_highlight = SnippetViewSet.as_view(
{"get": "highlight"}, renderer_classes=[renderers.StaticHTMLRenderer]
)
user_list = UserViewSet.as_view({"get": "list"})
user_detail = UserViewSet.as_view({"get": "retrieve"})
```
Notice how we're creating multiple views from each `ViewSet` class, by binding the HTTP methods to the required action for each view.
Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.
urlpatterns = format_suffix_patterns([
path('', api_root),
path('snippets/', snippet_list, name='snippet-list'),
path('snippets/<int:pk>/', snippet_detail, name='snippet-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')
])
```python
urlpatterns = format_suffix_patterns(
[
path("", api_root),
path("snippets/", snippet_list, name="snippet-list"),
path("snippets/<int:pk>/", snippet_detail, name="snippet-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
@ -110,20 +113,22 @@ Because we're using `ViewSet` classes rather than `View` classes, we actually do
Here's our re-wired `snippets/urls.py` file.
from django.urls import path, include
from rest_framework.routers import DefaultRouter
```python
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from snippets import views
from snippets import views
# Create a router and register our ViewSets with it.
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet, basename='snippet')
router.register(r'users', views.UserViewSet, basename='user')
# Create a router and register our ViewSets with it.
router = DefaultRouter()
router.register(r"snippets", views.SnippetViewSet, basename="snippet")
router.register(r"users", views.UserViewSet, basename="user")
# The API URLs are now determined automatically by the router.
urlpatterns = [
path('', include(router.urls)),
]
# The API URLs are now determined automatically by the router.
urlpatterns = [
path("", include(router.urls)),
]
```
Registering the ViewSets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the view set itself.

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 the project directory
mkdir tutorial
cd tutorial
```bash
# Create the project directory
mkdir tutorial
cd tutorial
# Create a virtual environment to isolate our package dependencies locally
python3 -m venv env
source env/bin/activate # On Windows use `env\Scripts\activate`
# Create a virtual environment to isolate our package dependencies locally
python3 -m venv env
source env/bin/activate # On Windows use `env\Scripts\activate`
# Install Django and Django REST framework into the virtual environment
pip install djangorestframework
# Install Django and Django REST framework into the virtual environment
pip install djangorestframework
# Set up a new project with a single application
django-admin startproject tutorial . # Note the trailing '.' character
cd tutorial
django-admin startapp quickstart
cd ..
# Set up a new project with a single application
django-admin startproject tutorial . # Note the trailing '.' character
cd tutorial
django-admin startapp quickstart
cd ..
```
The project layout should look like:
$ pwd
<some path>/tutorial
$ find .
.
./tutorial
./tutorial/asgi.py
./tutorial/__init__.py
./tutorial/quickstart
./tutorial/quickstart/migrations
./tutorial/quickstart/migrations/__init__.py
./tutorial/quickstart/models.py
./tutorial/quickstart/__init__.py
./tutorial/quickstart/apps.py
./tutorial/quickstart/admin.py
./tutorial/quickstart/tests.py
./tutorial/quickstart/views.py
./tutorial/settings.py
./tutorial/urls.py
./tutorial/wsgi.py
./env
./env/...
./manage.py
```bash
$ pwd
<some path>/tutorial
$ find .
.
./tutorial
./tutorial/asgi.py
./tutorial/__init__.py
./tutorial/quickstart
./tutorial/quickstart/migrations
./tutorial/quickstart/migrations/__init__.py
./tutorial/quickstart/models.py
./tutorial/quickstart/__init__.py
./tutorial/quickstart/apps.py
./tutorial/quickstart/admin.py
./tutorial/quickstart/tests.py
./tutorial/quickstart/views.py
./tutorial/settings.py
./tutorial/urls.py
./tutorial/wsgi.py
./env
./env/...
./manage.py
```
It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart).
Now sync your database for the first time:
python manage.py migrate
```bash
python manage.py migrate
```
We'll also create an initial user named `admin` with a password. We'll authenticate as that user later in our example.
python manage.py createsuperuser --username admin --email admin@example.com
```bash
python manage.py createsuperuser --username admin --email admin@example.com
```
Once you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding...
@ -64,20 +72,22 @@ Once you've set up a database and the initial user is created and ready to go, o
First up we're going to define some serializers. Let's create a new module named `tutorial/quickstart/serializers.py` that we'll use for our data representations.
from django.contrib.auth.models import Group, User
from rest_framework import serializers
```python
from django.contrib.auth.models import Group, User
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ["url", "username", "email", "groups"]
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ["url", "name"]
```
Notice that we're using hyperlinked relations in this case with `HyperlinkedModelSerializer`. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.
@ -85,28 +95,32 @@ Notice that we're using hyperlinked relations in this case with `HyperlinkedMode
Right, we'd better write some views then. Open `tutorial/quickstart/views.py` and get typing.
from django.contrib.auth.models import Group, User
from rest_framework import permissions, viewsets
```python
from django.contrib.auth.models import Group, User
from rest_framework import permissions, viewsets
from tutorial.quickstart.serializers import GroupSerializer, UserSerializer
from tutorial.quickstart.serializers import GroupSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by("-date_joined")
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all().order_by('name')
serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticated]
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all().order_by("name")
serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticated]
```
Rather than write multiple views we're grouping together all the common behavior into classes called `ViewSets`.
@ -116,21 +130,23 @@ We can easily break these down into individual views if we need to, but using vi
Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
from django.urls import include, path
from rest_framework import routers
```python
from django.urls import include, path
from rest_framework import routers
from tutorial.quickstart import views
from tutorial.quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router = routers.DefaultRouter()
router.register(r"users", views.UserViewSet)
router.register(r"groups", views.GroupViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path("", include(router.urls)),
path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
]
```
Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
@ -139,21 +155,26 @@ Again, if we need more control over the API URLs we can simply drop down to usin
Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.
## Pagination
Pagination allows you to control how many objects per page are returned. To enable it add the following lines to `tutorial/settings.py`
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
```python
REST_FRAMEWORK = {
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 10,
}
```
## Settings
Add `'rest_framework'` to `INSTALLED_APPS`. The settings module will be in `tutorial/settings.py`
INSTALLED_APPS = [
...
'rest_framework',
]
```text
INSTALLED_APPS = [
...
'rest_framework',
]
```
Okay, we're done.
@ -163,46 +184,51 @@ Okay, we're done.
We're now ready to test the API we've built. Let's fire up the server from the command line.
python manage.py runserver
```bash
python manage.py runserver
```
We can now access our API, both from the command-line, using tools like `curl`...
bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/
Enter host password for user 'admin':
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin",
"email": "admin@example.com",
"groups": []
}
]
}
```bash
bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/
Enter host password for user 'admin':
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin",
"email": "admin@example.com",
"groups": []
}
]
}
```
Or using the [httpie][httpie], command line tool...
bash: http -a admin http://127.0.0.1:8000/users/
http: password for admin@127.0.0.1:8000::
$HTTP/1.1 200 OK
...
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"email": "admin@example.com",
"groups": [],
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin"
}
]
}
```bash
bash: http -a admin http://127.0.0.1:8000/users/
http: password for admin@127.0.0.1:8000::
$HTTP/1.1 200 OK
...
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"email": "admin@example.com",
"groups": [],
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin"
}
]
}
```
Or directly through the browser, by going to the URL `http://127.0.0.1:8000/users/`...

View File

@ -452,4 +452,22 @@ ul.sponsor {
margin: 0 -.6rem 1em;
padding: 0.4rem 0.6rem;
}
.admonition.tip {
border: .075rem solid #1e8d21;
}
.admonition.tip .admonition-title {
background: #1e8d211a;
}
.admonition.warning {
border: .075rem solid #ff9844;
}
.admonition.warning .admonition-title {
background: #ff98441a;
}
.admonition.danger {
border: .075rem solid #f63a3a;
}
.admonition.danger .admonition-title {
background: #f63a3a1a;
}

View File

@ -110,7 +110,7 @@
{% block content %}
{% if page.meta.source %}
{% for filename in page.meta.source %}
<a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/{{ filename }}">
<a class="github" href="https://github.com/encode/django-rest-framework/tree/main/rest_framework/{{ filename }}">
<span class="label label-info">{{ filename }}</span>
</a>
{% endfor %}

View File

@ -1,7 +1,7 @@
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="repo-link btn btn-primary btn-small" href="https://github.com/encode/django-rest-framework/tree/master">GitHub</a>
<a class="repo-link btn btn-primary btn-small" href="https://github.com/encode/django-rest-framework">GitHub</a>
<a class="repo-link btn btn-inverse btn-small {% if not page.next_page %}disabled{% endif %}" rel="next" {% if page.next_page %}href="{{ page.next_page.url|url }}"{% endif %}>
Next <i class="icon-arrow-right icon-white"></i>
</a>

View File

@ -85,5 +85,4 @@ nav:
- '3.0 Announcement': 'community/3.0-announcement.md'
- 'Kickstarter Announcement': 'community/kickstarter-announcement.md'
- 'Mozilla Grant': 'community/mozilla-grant.md'
- 'Funding': 'community/funding.md'
- 'Jobs': 'community/jobs.md'

88
pyproject.toml Normal file
View File

@ -0,0 +1,88 @@
[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"
license-files = [ "LICENSE.md" ]
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",
"Framework :: Django :: 6.0",
"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.setuptools.package-data]
"rest_framework" = [
"templates/**/*",
"static/**/*",
"locale/**/*.mo",
]
[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.RemovedInDRF318Warning" ]
[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

@ -4,7 +4,8 @@ coreschema==0.0.4
django-filter
django-guardian>=2.4.0,<2.5
inflection==0.5.1
legacy-cgi; python_version>="3.13"
markdown>=3.3.7
psycopg2-binary>=2.9.5,<2.10
psycopg[binary]>=3.1.8
pygments~=2.17.0
pyyaml>=5.3.1,<5.4

View File

@ -5,3 +5,5 @@ pytest-django>=4.5.2,<5.0
importlib-metadata<5.0
# temporary pin of attrs
attrs==22.1.0
pytz # Remove when dropping support for Django<5.0
setuptools>=77.0.3

View File

@ -8,9 +8,9 @@ ______ _____ _____ _____ __
"""
__title__ = 'Django REST framework'
__version__ = '3.16.0'
__version__ = '3.16.1'
__author__ = 'Tom Christie'
__license__ = 'BSD 3-Clause'
__license__ = 'BSD-3-Clause'
__copyright__ = 'Copyright 2011-2023 Encode OSS Ltd'
# Version synonym
@ -21,7 +21,8 @@ HTTP_HEADER_ENCODING = 'iso-8859-1'
# Default datetime input and output formats
ISO_8601 = 'iso-8601'
DJANGO_DURATION_FORMAT = 'django'
class RemovedInDRF317Warning(PendingDeprecationWarning):
class RemovedInDRF318Warning(DeprecationWarning):
pass

View File

@ -23,10 +23,11 @@ class TokenChangeList(ChangeList):
class TokenAdmin(admin.ModelAdmin):
list_display = ('key', 'user', 'created')
list_filter = ('created',)
fields = ('user',)
search_fields = ('user__username',)
search_fields = ('user__%s' % User.USERNAME_FIELD,)
search_help_text = _('Username')
ordering = ('-created',)
ordering = ('user__%s' % User.USERNAME_FIELD,)
actions = None # Actions not compatible with mapped IDs.
def get_changelist(self, request, **kwargs):

View File

@ -42,4 +42,4 @@ class Command(BaseCommand):
username)
)
self.stdout.write(
'Generated token {} for user {}'.format(token.key, username))
f'Generated token {token.key} for user {username}')

View File

@ -1,5 +1,4 @@
import binascii
import os
import secrets
from django.conf import settings
from django.db import models
@ -28,13 +27,22 @@ class Token(models.Model):
verbose_name_plural = _("Tokens")
def save(self, *args, **kwargs):
"""
Save the token instance.
If no key is provided, generates a cryptographically secure key.
For new tokens, ensures they are inserted as new (not updated).
"""
if not self.key:
self.key = self.generate_key()
# For new objects, force INSERT to prevent overwriting existing tokens
if self._state.adding:
kwargs['force_insert'] = True
return super().save(*args, **kwargs)
@classmethod
def generate_key(cls):
return binascii.hexlify(os.urandom(20)).decode()
return secrets.token_hex(20)
def __str__(self):
return self.key

View File

@ -16,7 +16,7 @@ def unicode_http_header(value):
return value
# django.contrib.postgres requires psycopg2
# django.contrib.postgres requires psycopg
try:
from django.contrib.postgres import fields as postgres_fields
except ImportError:

View File

@ -70,6 +70,15 @@ def api_view(http_method_names=None):
WrappedAPIView.permission_classes = getattr(func, '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',
APIView.schema)
@ -78,8 +87,26 @@ def api_view(http_method_names=None):
return decorator
def _check_decorator_order(func, decorator_name):
"""
Check if an API policy decorator is being applied after @api_view.
"""
# Check if func is actually a view function (result of APIView.as_view())
if hasattr(func, 'cls') and issubclass(func.cls, APIView):
raise TypeError(
f"@{decorator_name} must come after (below) the @api_view decorator. "
"The correct order is:\n\n"
" @api_view(['GET'])\n"
f" @{decorator_name}(...)\n"
" def my_view(request):\n"
" ...\n\n"
"See https://www.django-rest-framework.org/api-guide/views/#api-policy-decorators"
)
def renderer_classes(renderer_classes):
def decorator(func):
_check_decorator_order(func, 'renderer_classes')
func.renderer_classes = renderer_classes
return func
return decorator
@ -87,6 +114,7 @@ def renderer_classes(renderer_classes):
def parser_classes(parser_classes):
def decorator(func):
_check_decorator_order(func, 'parser_classes')
func.parser_classes = parser_classes
return func
return decorator
@ -94,6 +122,7 @@ def parser_classes(parser_classes):
def authentication_classes(authentication_classes):
def decorator(func):
_check_decorator_order(func, 'authentication_classes')
func.authentication_classes = authentication_classes
return func
return decorator
@ -101,6 +130,7 @@ def authentication_classes(authentication_classes):
def throttle_classes(throttle_classes):
def decorator(func):
_check_decorator_order(func, 'throttle_classes')
func.throttle_classes = throttle_classes
return func
return decorator
@ -108,13 +138,39 @@ def throttle_classes(throttle_classes):
def permission_classes(permission_classes):
def decorator(func):
_check_decorator_order(func, 'permission_classes')
func.permission_classes = permission_classes
return func
return decorator
def content_negotiation_class(content_negotiation_class):
def decorator(func):
_check_decorator_order(func, 'content_negotiation_class')
func.content_negotiation_class = content_negotiation_class
return func
return decorator
def metadata_class(metadata_class):
def decorator(func):
_check_decorator_order(func, 'metadata_class')
func.metadata_class = metadata_class
return func
return decorator
def versioning_class(versioning_class):
def decorator(func):
_check_decorator_order(func, 'versioning_class')
func.versioning_class = versioning_class
return func
return decorator
def schema(view_inspector):
def decorator(func):
_check_decorator_order(func, 'schema')
func.schema = view_inspector
return func
return decorator

View File

@ -24,7 +24,7 @@ from django.utils import timezone
from django.utils.dateparse import (
parse_date, parse_datetime, parse_duration, parse_time
)
from django.utils.duration import duration_string
from django.utils.duration import duration_iso_string, duration_string
from django.utils.encoding import is_protected_type, smart_str
from django.utils.formats import localize_input, sanitize_separators
from django.utils.ipv6 import clean_ipv6_address
@ -35,7 +35,7 @@ try:
except ImportError:
pytz = None
from rest_framework import ISO_8601
from rest_framework import DJANGO_DURATION_FORMAT, ISO_8601
from rest_framework.compat import ip_address_validators
from rest_framework.exceptions import ErrorDetail, ValidationError
from rest_framework.settings import api_settings
@ -111,7 +111,7 @@ def get_attribute(instance, attrs):
# If we raised an Attribute or KeyError here it'd get treated
# as an omitted field in `Field.get_attribute()`. Instead we
# raise a ValueError to ensure the exception is not masked.
raise ValueError('Exception raised in callable attribute "{}"; original exception was: {}'.format(attr, exc))
raise ValueError(f'Exception raised in callable attribute "{attr}"; original exception was: {exc}')
return instance
@ -921,6 +921,28 @@ class IntegerField(Field):
return int(value)
class BigIntegerField(IntegerField):
default_error_messages = {
'invalid': _('A valid biginteger is required.'),
'max_value': _('Ensure this value is less than or equal to {max_value}.'),
'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
'max_string_length': _('String value too large.')
}
def __init__(self, coerce_to_string=None, **kwargs):
super().__init__(**kwargs)
if coerce_to_string is not None:
self.coerce_to_string = coerce_to_string
def to_representation(self, value):
if getattr(self, 'coerce_to_string', api_settings.COERCE_BIGINT_TO_STRING):
return '' if value is None else str(value)
return super().to_representation(value)
class FloatField(Field):
default_error_messages = {
'invalid': _('A valid number is required.'),
@ -1103,7 +1125,7 @@ class DecimalField(Field):
if self.localize:
return localize_input(quantized)
return '{:f}'.format(quantized)
return f'{quantized:f}'
def quantize(self, value):
"""
@ -1351,9 +1373,22 @@ class DurationField(Field):
'overflow': _('The number of days must be between {min_days} and {max_days}.'),
}
def __init__(self, **kwargs):
def __init__(self, *, format=empty, **kwargs):
self.max_value = kwargs.pop('max_value', None)
self.min_value = kwargs.pop('min_value', None)
if format is not empty:
if format is None or (isinstance(format, str) and format.lower() in (ISO_8601, DJANGO_DURATION_FORMAT)):
self.format = format
elif isinstance(format, str):
raise ValueError(
f"Unknown duration format provided, got '{format}'"
" while expecting 'django', 'iso-8601' or `None`."
)
else:
raise TypeError(
"duration format must be either str or `None`,"
f" not {type(format).__name__}"
)
super().__init__(**kwargs)
if self.max_value is not None:
message = lazy_format(self.error_messages['max_value'], max_value=self.max_value)
@ -1376,7 +1411,26 @@ class DurationField(Field):
self.fail('invalid', format='[DD] [HH:[MM:]]ss[.uuuuuu]')
def to_representation(self, value):
return duration_string(value)
output_format = getattr(self, 'format', api_settings.DURATION_FORMAT)
if output_format is None:
return value
if isinstance(output_format, str):
if output_format.lower() == ISO_8601:
return duration_iso_string(value)
if output_format.lower() == DJANGO_DURATION_FORMAT:
return duration_string(value)
raise ValueError(
f"Unknown duration format provided, got '{output_format}'"
" while expecting 'django', 'iso-8601' or `None`."
)
raise TypeError(
"duration format must be either str or `None`,"
f" not {type(output_format).__name__}"
)
# Choice types...
@ -1861,7 +1915,7 @@ class SerializerMethodField(Field):
def bind(self, field_name, parent):
# The method name defaults to `get_{field_name}`.
if self.method_name is None:
self.method_name = 'get_{field_name}'.format(field_name=field_name)
self.method_name = f'get_{field_name}'
super().bind(field_name, parent)

View File

@ -14,7 +14,7 @@ from django.utils.encoding import force_str
from django.utils.text import smart_split, unescape_string_literal
from django.utils.translation import gettext_lazy as _
from rest_framework import RemovedInDRF317Warning
from rest_framework import RemovedInDRF318Warning
from rest_framework.compat import coreapi, coreschema
from rest_framework.fields import CharField
from rest_framework.settings import api_settings
@ -51,7 +51,7 @@ class BaseFilterBackend:
def get_schema_fields(self, view):
assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`'
if coreapi is not None:
warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning)
warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning)
assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`'
return []
@ -189,7 +189,7 @@ class SearchFilter(BaseFilterBackend):
def get_schema_fields(self, view):
assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`'
if coreapi is not None:
warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning)
warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning)
assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`'
return [
coreapi.Field(
@ -249,7 +249,9 @@ class OrderingFilter(BaseFilterBackend):
return (ordering,)
return ordering
def get_default_valid_fields(self, queryset, view, context={}):
def get_default_valid_fields(self, queryset, view, context=None):
if context is None:
context = {}
# If `ordering_fields` is not specified, then we determine a default
# based on the serializer class, if one exists on the view.
if hasattr(view, 'get_serializer_class'):
@ -286,7 +288,9 @@ class OrderingFilter(BaseFilterBackend):
)
]
def get_valid_fields(self, queryset, view, context={}):
def get_valid_fields(self, queryset, view, context=None):
if context is None:
context = {}
valid_fields = getattr(view, 'ordering_fields', self.ordering_fields)
if valid_fields is None:
@ -351,7 +355,7 @@ class OrderingFilter(BaseFilterBackend):
def get_schema_fields(self, view):
assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`'
if coreapi is not None:
warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning)
warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.18', RemovedInDRF318Warning)
assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`'
return [
coreapi.Field(

View File

@ -1,5 +1,5 @@
"""
Generic views that provide commonly needed behaviour.
Generic views that provide commonly needed behavior.
"""
from django.core.exceptions import ValidationError
from django.db.models.query import QuerySet

View File

@ -8,6 +8,7 @@
# Bashar Al-Abdulhadi, 2016-2017
# Eyad Toma <d.eyad.t@gmail.com>, 2015,2017
# zak zak <zakaria.bendifallah@gmail.com>, 2020
# Salman Saeed Albukhaitan <ssyb2014@gmail.com>, 2024
msgid ""
msgstr ""
"Project-Id-Version: Django REST framework\n"
@ -24,19 +25,19 @@ msgstr ""
#: authentication.py:70
msgid "Invalid basic header. No credentials provided."
msgstr "رأس أساسي غير صالح, لم تقدم اي بيانات."
msgstr "ترويسة أساسية غير صالحة. لم تقدم أي بيانات تفويض."
#: authentication.py:73
msgid "Invalid basic header. Credentials string should not contain spaces."
msgstr "رأس أساسي غير صالح, سلسلة البيانات لا يجب أن تحتوي على أي أحرف مسافات"
msgstr "ترويسة أساسية غير صالحة. يجب أن لا تحتوي سلسلة بيانات التفويض على مسافات."
#: authentication.py:83
msgid "Invalid basic header. Credentials not correctly base64 encoded."
msgstr "رأس أساسي غير صالح, البيانات ليست مرمّزة بصحة على أساس64."
msgstr "ترويسة أساسية غير صالحة. بيانات التفويض لم تُشفر بشكل صحيح بنظام أساس64."
#: authentication.py:101
msgid "Invalid username/password."
msgstr "اسم المستخدم/كلمة السر غير صحيحين."
msgstr "اسم المستخدم/كلمة المرور غير صحيحة."
#: authentication.py:104 authentication.py:206
msgid "User inactive or deleted."
@ -93,7 +94,7 @@ msgstr "كلمة المرور"
#: authtoken/serializers.py:35
msgid "Unable to log in with provided credentials."
msgstr "تعذر تسجيل الدخول بالبيانات التي ادخلتها."
msgstr "تعذر تسجيل الدخول بالبيانات المدخلة."
#: authtoken/serializers.py:38
msgid "Must include \"username\" and \"password\"."
@ -101,11 +102,11 @@ msgstr "يجب أن تتضمن \"اسم المستخدم\" و \"كلمة الم
#: exceptions.py:102
msgid "A server error occurred."
msgstr "حدث خطأ في المخدم."
msgstr "حدث خطأ في الخادم."
#: exceptions.py:142
msgid "Invalid input."
msgstr ""
msgstr "مدخل غير صالح."
#: exceptions.py:161
msgid "Malformed request."
@ -130,11 +131,11 @@ msgstr "غير موجود."
#: exceptions.py:191
#, python-brace-format
msgid "Method \"{method}\" not allowed."
msgstr "الطريقة \"{method}\" غير مسموح بها."
msgstr "طريقة \"{method}\" غير مسموح بها."
#: exceptions.py:202
msgid "Could not satisfy the request Accept header."
msgstr "لم نتمكن من تلبية الرٱس Accept في الطلب."
msgstr "تعذر تلبية ترويسة Accept في الطلب."
#: exceptions.py:212
#, python-brace-format
@ -143,17 +144,17 @@ msgstr "الوسيط \"{media_type}\" الموجود في الطلب غير مع
#: exceptions.py:223
msgid "Request was throttled."
msgstr "تم تقييد الطلب."
msgstr "تم حد الطلب."
#: exceptions.py:224
#, python-brace-format
msgid "Expected available in {wait} second."
msgstr ""
msgstr "متوقع التوفر خلال {wait} ثانية."
#: exceptions.py:225
#, python-brace-format
msgid "Expected available in {wait} seconds."
msgstr ""
msgstr "متوقع التوفر خلال {wait} ثواني."
#: fields.py:316 relations.py:245 relations.py:279 validators.py:90
#: validators.py:183
@ -166,11 +167,11 @@ msgstr "لا يمكن لهذا الحقل ان يكون فارغاً null."
#: fields.py:701
msgid "Must be a valid boolean."
msgstr ""
msgstr "يجب أن يكون قيمة منطقية صالحة."
#: fields.py:766
msgid "Not a valid string."
msgstr ""
msgstr "ليس نصاً صالحاً."
#: fields.py:767
msgid "This field may not be blank."
@ -179,16 +180,16 @@ msgstr "لا يمكن لهذا الحقل ان يكون فارغاً."
#: fields.py:768 fields.py:1881
#, python-brace-format
msgid "Ensure this field has no more than {max_length} characters."
msgstr "تأكد ان الحقل لا يزيد عن {max_length} محرف."
msgstr "تأكد ان عدد الحروف في هذا الحقل لا تتجاوز {max_length}."
#: fields.py:769
#, python-brace-format
msgid "Ensure this field has at least {min_length} characters."
msgstr "تأكد ان الحقل {min_length} محرف على الاقل."
msgstr "تأكد ان عدد الحروف في هذا الحقل لا يقل عن {min_length}."
#: fields.py:816
msgid "Enter a valid email address."
msgstr "عليك ان تدخل بريد إلكتروني صالح."
msgstr "يرجى إدخال عنوان بريد إلكتروني صحيح."
#: fields.py:827
msgid "This value does not match the required pattern."
@ -204,7 +205,7 @@ msgstr "أدخل \"slug\" صالح يحتوي على حروف، أرقام، ش
msgid ""
"Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, "
"or hyphens."
msgstr ""
msgstr "أدخل \"slug\" صالح يحتوي على حروف يونيكود، أرقام، شُرط سفلية أو واصلات."
#: fields.py:854
msgid "Enter a valid URL."
@ -212,7 +213,7 @@ msgstr "الرجاء إدخال رابط إلكتروني صالح."
#: fields.py:867
msgid "Must be a valid UUID."
msgstr ""
msgstr "يجب أن يكون معرف UUID صالح."
#: fields.py:903
msgid "Enter a valid IPv4 or IPv6 address."
@ -225,16 +226,16 @@ msgstr "الرجاء إدخال رقم صحيح صالح."
#: fields.py:932 fields.py:969 fields.py:1005 fields.py:1366
#, python-brace-format
msgid "Ensure this value is less than or equal to {max_value}."
msgstr "تأكد ان القيمة أقل أو تساوي {max_value}."
msgstr "تأكد ان القيمة أقل من أو تساوي {max_value}."
#: fields.py:933 fields.py:970 fields.py:1006 fields.py:1367
#, python-brace-format
msgid "Ensure this value is greater than or equal to {min_value}."
msgstr "تأكد ان القيمة أكبر أو تساوي {min_value}."
msgstr "تأكد ان القيمة أكبر من أو تساوي {min_value}."
#: fields.py:934 fields.py:971 fields.py:1010
msgid "String value too large."
msgstr "السلسلة اطول من القيمة المسموح بها."
msgstr "النص طويل جداً."
#: fields.py:968 fields.py:1004
msgid "A valid number is required."
@ -249,7 +250,7 @@ msgstr "تأكد ان القيمة لا تحوي أكثر من {max_digits} رق
#, python-brace-format
msgid ""
"Ensure that there are no more than {max_decimal_places} decimal places."
msgstr "تأكد انه لا يوجد اكثر من {max_decimal_places} منازل عشرية."
msgstr "تأكد انه لا يوجد اكثر من {max_decimal_places} أرقام عشرية."
#: fields.py:1009
#, python-brace-format
@ -261,7 +262,7 @@ msgstr "تأكد انه لا يوجد اكثر من {max_whole_digits} أرقا
#: fields.py:1148
#, python-brace-format
msgid "Datetime has wrong format. Use one of these formats instead: {format}."
msgstr "صيغة التاريخ و الوقت غير صحيحة. عليك أن تستخدم واحدة من هذه الصيغ التالية: {format}."
msgstr "صيغة التاريخ و الوقت غير صحيحة. عليك أن تستخدم احد الصيغ التالية: {format}."
#: fields.py:1149
msgid "Expected a datetime but got a date."
@ -270,11 +271,11 @@ msgstr "متوقع تاريخ و وقت و وجد تاريخ فقط"
#: fields.py:1150
#, python-brace-format
msgid "Invalid datetime for the timezone \"{timezone}\"."
msgstr ""
msgstr "تاريخ و وقت غير صالح للمنطقة الزمنية \"{timezone}\"."
#: fields.py:1151
msgid "Datetime value out of range."
msgstr ""
msgstr "قيمة التاريخ و الوقت خارج النطاق."
#: fields.py:1236
#, python-brace-format
@ -293,12 +294,12 @@ msgstr "صيغة الوقت غير صحيحة. عليك أن تستخدم واح
#: fields.py:1365
#, python-brace-format
msgid "Duration has wrong format. Use one of these formats instead: {format}."
msgstr "صيغة المدة غير صحيحه, يرجى إستخدام إحدى هذه الصيغ: {format}."
msgstr "صيغة المدة غير صحيحة. يرجى استخدام احد الصيغ التالية: {format}."
#: fields.py:1399 fields.py:1456
#, python-brace-format
msgid "\"{input}\" is not a valid choice."
msgstr "\"{input}\" ليست واحدة من الخيارات الصالحة."
msgstr "\"{input}\" ليس خياراً صالحاً."
#: fields.py:1402
#, python-brace-format
@ -317,7 +318,7 @@ msgstr "هذا التحديد لا يجب أن يكون فارغا."
#: fields.py:1495
#, python-brace-format
msgid "\"{input}\" is not a valid path choice."
msgstr "{input} كإختيار مسار غير صالح."
msgstr "{input} ليس خيار مسار صالح."
#: fields.py:1514
msgid "No file was submitted."
@ -326,41 +327,41 @@ msgstr "لم يتم إرسال أي ملف."
#: fields.py:1515
msgid ""
"The submitted data was not a file. Check the encoding type on the form."
msgstr "المعطيات المرسولة ليست ملف. إفحص نوع الترميز في النموذج."
msgstr "البيانات المرسلة ليست ملف. تأكد من نوع الترميز في النموذج."
#: fields.py:1516
msgid "No filename could be determined."
msgstr "ما من إسم ملف أمكن تحديده."
msgstr "تعذر تحديد اسم الملف."
#: fields.py:1517
msgid "The submitted file is empty."
msgstr "الملف الذي تم إرساله فارغ."
msgstr "الملف المرسل فارغ."
#: fields.py:1518
#, python-brace-format
msgid ""
"Ensure this filename has at most {max_length} characters (it has {length})."
msgstr "تأكد ان اسم الملف لا يحوي أكثر من {max_length} محرف (الإسم المرسل يحوي {length} محرف)."
msgstr "تأكد ان طول إسم الملف لا يتجاوز {max_length} حرف (عدد الحروف الحالي {length})."
#: fields.py:1566
msgid ""
"Upload a valid image. The file you uploaded was either not an image or a "
"corrupted image."
msgstr "الرجاء تحميل صورة صالحة. الملف الذي تم تحميله إما لم يكن صورة او انه كان صورة تالفة."
msgstr "يرجى رفع صورة صالحة. الملف الذي قمت برفعه ليس صورة أو أنه ملف تالف."
#: fields.py:1604 relations.py:486 serializers.py:571
msgid "This list may not be empty."
msgstr "القائمة يجب أن لا تكون فارغة."
msgstr "يجب أن لا تكون القائمة فارغة."
#: fields.py:1605
#, python-brace-format
msgid "Ensure this field has at least {min_length} elements."
msgstr ""
msgstr "تأكد ان عدد العناصر في هذا الحقل لا يقل عن {min_length}."
#: fields.py:1606
#, python-brace-format
msgid "Ensure this field has no more than {max_length} elements."
msgstr ""
msgstr "تأكد ان عدد العناصر في هذا الحقل لا يتجاوز {max_length}."
#: fields.py:1682
#, python-brace-format
@ -369,7 +370,7 @@ msgstr "المتوقع كان قاموس عناصر و لكن النوع الم
#: fields.py:1683
msgid "This dictionary may not be empty."
msgstr ""
msgstr "يجب أن لا يكون القاموس فارغاً."
#: fields.py:1755
msgid "Value must be valid JSON."
@ -381,7 +382,7 @@ msgstr "بحث"
#: filters.py:50
msgid "A search term."
msgstr ""
msgstr "مصطلح البحث."
#: filters.py:180 templates/rest_framework/filters/ordering.html:3
msgid "Ordering"
@ -389,7 +390,7 @@ msgstr "الترتيب"
#: filters.py:181
msgid "Which field to use when ordering the results."
msgstr ""
msgstr "أي حقل يجب استخدامه عند ترتيب النتائج."
#: filters.py:287
msgid "ascending"
@ -401,11 +402,11 @@ msgstr "تنازلي"
#: pagination.py:174
msgid "A page number within the paginated result set."
msgstr ""
msgstr "رقم الصفحة ضمن النتائج المقسمة."
#: pagination.py:179 pagination.py:372 pagination.py:590
msgid "Number of results to return per page."
msgstr ""
msgstr "عدد النتائج التي يجب إرجاعها في كل صفحة."
#: pagination.py:189
msgid "Invalid page."
@ -413,11 +414,11 @@ msgstr "صفحة غير صحيحة."
#: pagination.py:374
msgid "The initial index from which to return the results."
msgstr ""
msgstr "الفهرس الأولي الذي يجب البدء منه لإرجاع النتائج."
#: pagination.py:581
msgid "The pagination cursor value."
msgstr ""
msgstr "قيمة المؤشر للتقسيم."
#: pagination.py:583
msgid "Invalid cursor"
@ -431,24 +432,24 @@ msgstr "معرف العنصر \"{pk_value}\" غير صالح - العنصر غ
#: relations.py:247
#, python-brace-format
msgid "Incorrect type. Expected pk value, received {data_type}."
msgstr "نوع خاطئ. المتوقع قيمة من pk، لكن المتحصل عليه {data_type}."
msgstr "نوع غير صحيح. يتوقع قيمة معرف العنصر، بينما حصل على {data_type}."
#: relations.py:280
msgid "Invalid hyperlink - No URL match."
msgstr "إرتباط تشعبي غير صالح - لا مطابقة لURL."
msgstr "رابط تشعبي غير صالح - لا يوجد تطابق URL."
#: relations.py:281
msgid "Invalid hyperlink - Incorrect URL match."
msgstr "إرتباط تشعبي غير صالح - مطابقة خاطئة لURL."
msgstr "رابط تشعبي غير صالح - تطابق URL غير صحيح."
#: relations.py:282
msgid "Invalid hyperlink - Object does not exist."
msgstr "إرتباط تشعبي غير صالح - عنصر غير موجود."
msgstr "رابط تشعبي غير صالح - العنصر غير موجود."
#: relations.py:283
#, python-brace-format
msgid "Incorrect type. Expected URL string, received {data_type}."
msgstr "نوع خاطئ. المتوقع سلسلة URL، لكن المتحصل عليه {data_type}."
msgstr "نوع غير صحيح. المتوقع هو رابط URL، ولكن تم الحصول على {data_type}."
#: relations.py:448
#, python-brace-format
@ -461,20 +462,20 @@ msgstr "قيمة غير صالحة."
#: schemas/utils.py:32
msgid "unique integer value"
msgstr ""
msgstr "رقم صحيح فريد"
#: schemas/utils.py:34
msgid "UUID string"
msgstr ""
msgstr "نص UUID"
#: schemas/utils.py:36
msgid "unique value"
msgstr ""
msgstr "قيمة فريدة"
#: schemas/utils.py:38
#, python-brace-format
msgid "A {value_type} identifying this {name}."
msgstr ""
msgstr "نوع {value_type} يحدد هذا {name}."
#: serializers.py:337
#, python-brace-format
@ -484,7 +485,7 @@ msgstr "معطيات غير صالحة. المتوقع هو قاموس، لكن
#: templates/rest_framework/admin.html:116
#: templates/rest_framework/base.html:136
msgid "Extra Actions"
msgstr ""
msgstr "إجراءات إضافية"
#: templates/rest_framework/admin.html:130
#: templates/rest_framework/base.html:150
@ -493,27 +494,27 @@ msgstr "مرشحات"
#: templates/rest_framework/base.html:37
msgid "navbar"
msgstr ""
msgstr "شريط التنقل"
#: templates/rest_framework/base.html:75
msgid "content"
msgstr ""
msgstr "المحتوى"
#: templates/rest_framework/base.html:78
msgid "request form"
msgstr ""
msgstr "نموذج الطلب"
#: templates/rest_framework/base.html:157
msgid "main content"
msgstr ""
msgstr "المحتوى الرئيسي"
#: templates/rest_framework/base.html:173
msgid "request info"
msgstr ""
msgstr "معلومات الطلب"
#: templates/rest_framework/base.html:177
msgid "response info"
msgstr ""
msgstr "معلومات الرد"
#: templates/rest_framework/horizontal/radio.html:4
#: templates/rest_framework/inline/radio.html:3
@ -525,7 +526,7 @@ msgstr "لا شيء"
#: templates/rest_framework/inline/select_multiple.html:3
#: templates/rest_framework/vertical/select_multiple.html:3
msgid "No items to select."
msgstr "ما من عناصر للتحديد."
msgstr "لا يوجد عناصر لتحديدها."
#: validators.py:39
msgid "This field must be unique."
@ -539,7 +540,7 @@ msgstr "الحقول {field_names} يجب أن تشكل مجموعة فريدة.
#: validators.py:171
#, python-brace-format
msgid "Surrogate characters are not allowed: U+{code_point:X}."
msgstr ""
msgstr "لا يُسمح بالحروف البديلة: U+{code_point:X}."
#: validators.py:243
#, python-brace-format
@ -558,11 +559,11 @@ msgstr "الحقل يجب ان يكون فريد للعام {date_field}."
#: versioning.py:40
msgid "Invalid version in \"Accept\" header."
msgstr "إصدار غير صالح في الرٱس \"Accept\"."
msgstr "إصدار غير صالح في ترويسة \"Accept\"."
#: versioning.py:71
msgid "Invalid version in URL path."
msgstr "إصدار غير صالح في المسار URL."
msgstr "نسخة غير صالحة في مسار URL."
#: versioning.py:116
msgid "Invalid version in URL path. Does not match any version namespace."

View File

@ -11,6 +11,7 @@
# Thomas Tanner, 2015
# Tom Jaster <futur3.tom@googlemail.com>, 2015
# Xavier Ordoquy <xordoquy@linovia.com>, 2015
# stefan6419846, 2025
msgid ""
msgstr ""
"Project-Id-Version: Django REST framework\n"
@ -27,19 +28,19 @@ msgstr ""
#: authentication.py:70
msgid "Invalid basic header. No credentials provided."
msgstr "Ungültiger basic header. Keine Zugangsdaten angegeben."
msgstr "Ungültiger Basic Header. Keine Zugangsdaten angegeben."
#: authentication.py:73
msgid "Invalid basic header. Credentials string should not contain spaces."
msgstr "Ungültiger basic header. Zugangsdaten sollen keine Leerzeichen enthalten."
msgstr "Ungültiger Basic Header. Zugangsdaten sollen keine Leerzeichen enthalten."
#: authentication.py:83
msgid "Invalid basic header. Credentials not correctly base64 encoded."
msgstr "Ungültiger basic header. Zugangsdaten sind nicht korrekt mit base64 kodiert."
msgstr "Ungültiger Basic Header. Zugangsdaten sind nicht korrekt mit base64 kodiert."
#: authentication.py:101
msgid "Invalid username/password."
msgstr "Ungültiger Benutzername/Passwort"
msgstr "Ungültiger Benutzername/Passwort."
#: authentication.py:104 authentication.py:206
msgid "User inactive or deleted."
@ -47,16 +48,16 @@ msgstr "Benutzer inaktiv oder gelöscht."
#: authentication.py:184
msgid "Invalid token header. No credentials provided."
msgstr "Ungültiger token header. Keine Zugangsdaten angegeben."
msgstr "Ungültiger Token Header. Keine Zugangsdaten angegeben."
#: authentication.py:187
msgid "Invalid token header. Token string should not contain spaces."
msgstr "Ungültiger token header. Zugangsdaten sollen keine Leerzeichen enthalten."
msgstr "Ungültiger Token Header. Zugangsdaten sollen keine Leerzeichen enthalten."
#: authentication.py:193
msgid ""
"Invalid token header. Token string should not contain invalid characters."
msgstr "Ungültiger Token Header. Tokens dürfen keine ungültigen Zeichen enthalten."
msgstr "Ungültiger Token Header. Zugangsdaten dürfen keine ungültigen Zeichen enthalten."
#: authentication.py:203
msgid "Invalid token."
@ -108,7 +109,7 @@ msgstr "Ein Serverfehler ist aufgetreten."
#: exceptions.py:142
msgid "Invalid input."
msgstr ""
msgstr "Ungültige Eingabe."
#: exceptions.py:161
msgid "Malformed request."
@ -124,7 +125,7 @@ msgstr "Anmeldedaten fehlen."
#: exceptions.py:179
msgid "You do not have permission to perform this action."
msgstr "Sie sind nicht berechtigt diese Aktion durchzuführen."
msgstr "Sie sind nicht berechtigt, diese Aktion durchzuführen."
#: exceptions.py:185
msgid "Not found."
@ -151,17 +152,17 @@ msgstr "Die Anfrage wurde gedrosselt."
#: exceptions.py:224
#, python-brace-format
msgid "Expected available in {wait} second."
msgstr ""
msgstr "Erwarte Verfügbarkeit in {wait} Sekunde."
#: exceptions.py:225
#, python-brace-format
msgid "Expected available in {wait} seconds."
msgstr ""
msgstr "Erwarte Verfügbarkeit in {wait} Sekunden."
#: fields.py:316 relations.py:245 relations.py:279 validators.py:90
#: validators.py:183
msgid "This field is required."
msgstr "Dieses Feld ist erforderlich."
msgstr "Dieses Feld ist zwingend erforderlich."
#: fields.py:317
msgid "This field may not be null."
@ -169,11 +170,11 @@ msgstr "Dieses Feld darf nicht null sein."
#: fields.py:701
msgid "Must be a valid boolean."
msgstr ""
msgstr "Muss ein gültiger Wahrheitswert sein."
#: fields.py:766
msgid "Not a valid string."
msgstr ""
msgstr "Kein gültiger String."
#: fields.py:767
msgid "This field may not be blank."
@ -207,7 +208,7 @@ msgstr "Gib ein gültiges \"slug\" aus Buchstaben, Ziffern, Unterstrichen und Mi
msgid ""
"Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, "
"or hyphens."
msgstr ""
msgstr "Gib ein gültiges \"slug\" aus Unicode-Buchstaben, Ziffern, Unterstrichen und Minuszeichen ein."
#: fields.py:854
msgid "Enter a valid URL."
@ -215,11 +216,11 @@ msgstr "Gib eine gültige URL ein."
#: fields.py:867
msgid "Must be a valid UUID."
msgstr ""
msgstr "Muss eine gültige UUID sein."
#: fields.py:903
msgid "Enter a valid IPv4 or IPv6 address."
msgstr "Geben Sie eine gültige IPv4 oder IPv6 Adresse an"
msgstr "Geben Sie eine gültige IPv4 oder IPv6 Adresse an."
#: fields.py:931
msgid "A valid integer is required."
@ -273,11 +274,11 @@ msgstr "Erwarte eine Datums- und Zeitangabe, erhielt aber ein Datum."
#: fields.py:1150
#, python-brace-format
msgid "Invalid datetime for the timezone \"{timezone}\"."
msgstr ""
msgstr "Ungültige Datumsangabe für die Zeitzone \"{timezone}\"."
#: fields.py:1151
msgid "Datetime value out of range."
msgstr ""
msgstr "Datumsangabe außerhalb des Bereichs."
#: fields.py:1236
#, python-brace-format
@ -358,12 +359,12 @@ msgstr "Diese Liste darf nicht leer sein."
#: fields.py:1605
#, python-brace-format
msgid "Ensure this field has at least {min_length} elements."
msgstr ""
msgstr "Dieses Feld muss mindestens {min_length} Einträge enthalten."
#: fields.py:1606
#, python-brace-format
msgid "Ensure this field has no more than {max_length} elements."
msgstr ""
msgstr "Dieses Feld darf nicht mehr als {max_length} Einträge enthalten."
#: fields.py:1682
#, python-brace-format
@ -372,7 +373,7 @@ msgstr "Erwartete ein Dictionary mit Elementen, erhielt aber den Typ \"{input_ty
#: fields.py:1683
msgid "This dictionary may not be empty."
msgstr ""
msgstr "Dieses Dictionary darf nicht leer sein."
#: fields.py:1755
msgid "Value must be valid JSON."
@ -384,7 +385,7 @@ msgstr "Suche"
#: filters.py:50
msgid "A search term."
msgstr ""
msgstr "Ein Suchbegriff."
#: filters.py:180 templates/rest_framework/filters/ordering.html:3
msgid "Ordering"
@ -392,7 +393,7 @@ msgstr "Sortierung"
#: filters.py:181
msgid "Which field to use when ordering the results."
msgstr ""
msgstr "Feld, das zum Sortieren der Ergebnisse verwendet werden soll."
#: filters.py:287
msgid "ascending"
@ -404,11 +405,11 @@ msgstr "Absteigend"
#: pagination.py:174
msgid "A page number within the paginated result set."
msgstr ""
msgstr "Eine Seitenzahl in der paginierten Ergebnismenge."
#: pagination.py:179 pagination.py:372 pagination.py:590
msgid "Number of results to return per page."
msgstr ""
msgstr "Anzahl der pro Seite zurückzugebenden Ergebnisse."
#: pagination.py:189
msgid "Invalid page."
@ -416,11 +417,11 @@ msgstr "Ungültige Seite."
#: pagination.py:374
msgid "The initial index from which to return the results."
msgstr ""
msgstr "Der initiale Index, von dem die Ergebnisse zurückgegeben werden sollen."
#: pagination.py:581
msgid "The pagination cursor value."
msgstr ""
msgstr "Der Zeigerwert für die Paginierung"
#: pagination.py:583
msgid "Invalid cursor"
@ -434,7 +435,7 @@ msgstr "Ungültiger pk \"{pk_value}\" - Object existiert nicht."
#: relations.py:247
#, python-brace-format
msgid "Incorrect type. Expected pk value, received {data_type}."
msgstr "Falscher Typ. Erwarte pk Wert, erhielt aber {data_type}."
msgstr "Falscher Typ. Erwarte pk-Wert, erhielt aber {data_type}."
#: relations.py:280
msgid "Invalid hyperlink - No URL match."
@ -451,7 +452,7 @@ msgstr "Ungültiger Hyperlink - Objekt existiert nicht."
#: relations.py:283
#, python-brace-format
msgid "Incorrect type. Expected URL string, received {data_type}."
msgstr "Falscher Typ. Erwarte URL Zeichenkette, erhielt aber {data_type}."
msgstr "Falscher Typ. Erwarte URL-Zeichenkette, erhielt aber {data_type}."
#: relations.py:448
#, python-brace-format
@ -464,20 +465,20 @@ msgstr "Ungültiger Wert."
#: schemas/utils.py:32
msgid "unique integer value"
msgstr ""
msgstr "eindeutiger Ganzzahl-Wert"
#: schemas/utils.py:34
msgid "UUID string"
msgstr ""
msgstr "UUID-String"
#: schemas/utils.py:36
msgid "unique value"
msgstr ""
msgstr "eindeutiger Wert"
#: schemas/utils.py:38
#, python-brace-format
msgid "A {value_type} identifying this {name}."
msgstr ""
msgstr "Ein {value_type}, der {name} identifiziert."
#: serializers.py:337
#, python-brace-format
@ -487,7 +488,7 @@ msgstr "Ungültige Daten. Dictionary erwartet, aber {datatype} erhalten."
#: templates/rest_framework/admin.html:116
#: templates/rest_framework/base.html:136
msgid "Extra Actions"
msgstr ""
msgstr "Zusätzliche Aktionen"
#: templates/rest_framework/admin.html:130
#: templates/rest_framework/base.html:150
@ -496,27 +497,27 @@ msgstr "Filter"
#: templates/rest_framework/base.html:37
msgid "navbar"
msgstr ""
msgstr "Navigation"
#: templates/rest_framework/base.html:75
msgid "content"
msgstr ""
msgstr "Inhalt"
#: templates/rest_framework/base.html:78
msgid "request form"
msgstr ""
msgstr "Anfrage-Formular"
#: templates/rest_framework/base.html:157
msgid "main content"
msgstr ""
msgstr "Hauptteil"
#: templates/rest_framework/base.html:173
msgid "request info"
msgstr ""
msgstr "Anfrage-Informationen"
#: templates/rest_framework/base.html:177
msgid "response info"
msgstr ""
msgstr "Antwort-Informationen"
#: templates/rest_framework/horizontal/radio.html:4
#: templates/rest_framework/inline/radio.html:3
@ -542,7 +543,7 @@ msgstr "Die Felder {field_names} müssen eine eindeutige Menge bilden."
#: validators.py:171
#, python-brace-format
msgid "Surrogate characters are not allowed: U+{code_point:X}."
msgstr ""
msgstr "Ersatzzeichen sind nicht erlaubt: U+{code_point:X}."
#: validators.py:243
#, python-brace-format
@ -565,7 +566,7 @@ msgstr "Ungültige Version in der \"Accept\" Kopfzeile."
#: versioning.py:71
msgid "Invalid version in URL path."
msgstr "Ungültige Version im URL Pfad."
msgstr "Ungültige Version im URL-Pfad."
#: versioning.py:116
msgid "Invalid version in URL path. Does not match any version namespace."

View File

@ -10,12 +10,13 @@
# Miguel Gonzalez <migonzalvar@gmail.com>, 2016
# Miguel Gonzalez <migonzalvar@gmail.com>, 2015-2016
# Sergio Infante <rsinfante@gmail.com>, 2015
# Federico Bond <federicobond@gmail.com>, 2025
msgid ""
msgstr ""
"Project-Id-Version: Django REST framework\n"
"Report-Msgid-Bugs-To: \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-05-19 00:05+1000\n"
"Last-Translator: Xavier Ordoquy <xordoquy@linovia.com>\n"
"Language-Team: Spanish (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/es/)\n"
"MIME-Version: 1.0\n"
@ -107,7 +108,7 @@ msgstr "Se ha producido un error en el servidor."
#: exceptions.py:142
msgid "Invalid input."
msgstr ""
msgstr "Entrada inválida."
#: exceptions.py:161
msgid "Malformed request."
@ -150,12 +151,12 @@ msgstr "Solicitud fue regulada (throttled)."
#: exceptions.py:224
#, python-brace-format
msgid "Expected available in {wait} second."
msgstr ""
msgstr "Se espera que esté disponible en {wait} segundo."
#: exceptions.py:225
#, python-brace-format
msgid "Expected available in {wait} seconds."
msgstr ""
msgstr "Se espera que esté disponible en {wait} segundos."
#: fields.py:316 relations.py:245 relations.py:279 validators.py:90
#: validators.py:183
@ -168,11 +169,11 @@ msgstr "Este campo no puede ser nulo."
#: fields.py:701
msgid "Must be a valid boolean."
msgstr ""
msgstr "Debe ser un booleano válido."
#: fields.py:766
msgid "Not a valid string."
msgstr ""
msgstr "No es una cadena válida."
#: fields.py:767
msgid "This field may not be blank."
@ -204,9 +205,8 @@ msgstr "Introduzca un \"slug\" válido consistente en letras, números, guiones
#: fields.py:839
msgid ""
"Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, "
"or hyphens."
msgstr ""
"Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, or hyphens."
msgstr "Introduzca un “slug” válido compuesto por letras Unicode, números, guiones bajos o medios."
#: fields.py:854
msgid "Enter a valid URL."
@ -214,7 +214,7 @@ msgstr "Introduzca una URL válida."
#: fields.py:867
msgid "Must be a valid UUID."
msgstr ""
msgstr "Debe ser un UUID válido."
#: fields.py:903
msgid "Enter a valid IPv4 or IPv6 address."
@ -272,11 +272,11 @@ msgstr "Se esperaba un fecha/hora en vez de una fecha."
#: fields.py:1150
#, python-brace-format
msgid "Invalid datetime for the timezone \"{timezone}\"."
msgstr ""
msgstr "Fecha y hora inválida para la zona horaria \"{timezone}\"."
#: fields.py:1151
msgid "Datetime value out of range."
msgstr ""
msgstr "Valor de fecha y hora fuera de rango."
#: fields.py:1236
#, python-brace-format
@ -357,12 +357,12 @@ msgstr "Esta lista no puede estar vacía."
#: fields.py:1605
#, python-brace-format
msgid "Ensure this field has at least {min_length} elements."
msgstr ""
msgstr "Asegúrese de que este campo tiene al menos {min_length} elementos."
#: fields.py:1606
#, python-brace-format
msgid "Ensure this field has no more than {max_length} elements."
msgstr ""
msgstr "Asegúrese de que este campo no tiene más de {max_length} elementos."
#: fields.py:1682
#, python-brace-format
@ -371,7 +371,7 @@ msgstr "Se esperaba un diccionario de elementos en vez del tipo \"{input_type}\"
#: fields.py:1683
msgid "This dictionary may not be empty."
msgstr ""
msgstr "Este diccionario no debe estar vacío."
#: fields.py:1755
msgid "Value must be valid JSON."
@ -383,7 +383,7 @@ msgstr "Buscar"
#: filters.py:50
msgid "A search term."
msgstr ""
msgstr "Un término de búsqueda."
#: filters.py:180 templates/rest_framework/filters/ordering.html:3
msgid "Ordering"
@ -391,7 +391,7 @@ msgstr "Ordenamiento"
#: filters.py:181
msgid "Which field to use when ordering the results."
msgstr ""
msgstr "Qué campo usar para ordenar los resultados."
#: filters.py:287
msgid "ascending"
@ -403,11 +403,11 @@ msgstr "descendiente"
#: pagination.py:174
msgid "A page number within the paginated result set."
msgstr ""
msgstr "Un número de página dentro del conjunto de resultados paginado."
#: pagination.py:179 pagination.py:372 pagination.py:590
msgid "Number of results to return per page."
msgstr ""
msgstr "Número de resultados a devolver por página."
#: pagination.py:189
msgid "Invalid page."
@ -415,11 +415,11 @@ msgstr "Página inválida."
#: pagination.py:374
msgid "The initial index from which to return the results."
msgstr ""
msgstr "El índice inicial a partir del cual devolver los resultados."
#: pagination.py:581
msgid "The pagination cursor value."
msgstr ""
msgstr "El valor del cursor de paginación."
#: pagination.py:583
msgid "Invalid cursor"
@ -463,20 +463,20 @@ msgstr "Valor inválido."
#: schemas/utils.py:32
msgid "unique integer value"
msgstr ""
msgstr "valor de entero único"
#: schemas/utils.py:34
msgid "UUID string"
msgstr ""
msgstr "Cadena UUID"
#: schemas/utils.py:36
msgid "unique value"
msgstr ""
msgstr "valor único"
#: schemas/utils.py:38
#, python-brace-format
msgid "A {value_type} identifying this {name}."
msgstr ""
msgstr "Un {value_type} que identifique este {name}."
#: serializers.py:337
#, python-brace-format
@ -486,7 +486,7 @@ msgstr "Datos inválidos. Se esperaba un diccionario pero es un {datatype}."
#: templates/rest_framework/admin.html:116
#: templates/rest_framework/base.html:136
msgid "Extra Actions"
msgstr ""
msgstr "Acciones extras"
#: templates/rest_framework/admin.html:130
#: templates/rest_framework/base.html:150

View File

@ -105,7 +105,7 @@ msgstr "خطای سمت سرور رخ داده است."
#: exceptions.py:142
msgid "Invalid input."
msgstr ""
msgstr "ورودی نامعتبر"
#: exceptions.py:161
msgid "Malformed request."
@ -148,12 +148,12 @@ msgstr "تعداد درخواست‌های شما محدود شده است."
#: exceptions.py:224
#, python-brace-format
msgid "Expected available in {wait} second."
msgstr ""
msgstr "انتظار می‌رود در {wait} ثانیه در دسترس باشد."
#: exceptions.py:225
#, python-brace-format
msgid "Expected available in {wait} seconds."
msgstr ""
msgstr "انتظار می‌رود در {wait} ثانیه در دسترس باشد."
#: fields.py:316 relations.py:245 relations.py:279 validators.py:90
#: validators.py:183
@ -166,11 +166,11 @@ msgstr "این مقدار نباید توهی باشد."
#: fields.py:701
msgid "Must be a valid boolean."
msgstr ""
msgstr "باید یک مقدار منطقی(بولی) معتبر باشد."
#: fields.py:766
msgid "Not a valid string."
msgstr ""
msgstr "یک رشته معتبر نیست."
#: fields.py:767
msgid "This field may not be blank."
@ -212,7 +212,7 @@ msgstr "یک URL معتبر وارد کنید"
#: fields.py:867
msgid "Must be a valid UUID."
msgstr ""
msgstr "باید یک UUID معتبر باشد."
#: fields.py:903
msgid "Enter a valid IPv4 or IPv6 address."
@ -270,11 +270,11 @@ msgstr "باید datetime باشد اما date دریافت شد."
#: fields.py:1150
#, python-brace-format
msgid "Invalid datetime for the timezone \"{timezone}\"."
msgstr ""
msgstr "تاریخ و زمان برای منطقه زمانی \"{timezone}\" نامعتبر است."
#: fields.py:1151
msgid "Datetime value out of range."
msgstr ""
msgstr "مقدار تاریخ و زمان خارج از محدوده است."
#: fields.py:1236
#, python-brace-format
@ -355,12 +355,12 @@ msgstr "این لیست نمی تواند خالی باشد"
#: fields.py:1605
#, python-brace-format
msgid "Ensure this field has at least {min_length} elements."
msgstr ""
msgstr "اطمینان حاصل کنید که این فیلد حداقل {min_length} عنصر دارد."
#: fields.py:1606
#, python-brace-format
msgid "Ensure this field has no more than {max_length} elements."
msgstr ""
msgstr "اطمینان حاصل کنید که این فیلد بیش از {max_length} عنصر ندارد."
#: fields.py:1682
#, python-brace-format
@ -369,7 +369,7 @@ msgstr "باید دیکشنری از آیتم ها ارسال می شد، اما
#: fields.py:1683
msgid "This dictionary may not be empty."
msgstr ""
msgstr "این دیکشنری نمی‌تواند خالی باشد."
#: fields.py:1755
msgid "Value must be valid JSON."
@ -381,7 +381,7 @@ msgstr "جستجو"
#: filters.py:50
msgid "A search term."
msgstr ""
msgstr "یک عبارت جستجو."
#: filters.py:180 templates/rest_framework/filters/ordering.html:3
msgid "Ordering"
@ -389,7 +389,7 @@ msgstr "ترتیب"
#: filters.py:181
msgid "Which field to use when ordering the results."
msgstr ""
msgstr "کدام فیلد باید هنگام مرتب‌سازی نتایج استفاده شود."
#: filters.py:287
msgid "ascending"
@ -401,11 +401,11 @@ msgstr "نزولی"
#: pagination.py:174
msgid "A page number within the paginated result set."
msgstr ""
msgstr "یک شماره صفحه‌ در مجموعه نتایج صفحه‌بندی شده."
#: pagination.py:179 pagination.py:372 pagination.py:590
msgid "Number of results to return per page."
msgstr ""
msgstr "تعداد نتایج برای نمایش در هر صفحه."
#: pagination.py:189
msgid "Invalid page."
@ -413,11 +413,11 @@ msgstr "صفحه نامعتبر"
#: pagination.py:374
msgid "The initial index from which to return the results."
msgstr ""
msgstr "ایندکس اولیه‌ای که از آن نتایج بازگردانده می‌شود."
#: pagination.py:581
msgid "The pagination cursor value."
msgstr ""
msgstr "مقدار نشانگر صفحه‌بندی."
#: pagination.py:583
msgid "Invalid cursor"
@ -461,20 +461,20 @@ msgstr "مقدار نامعتبر."
#: schemas/utils.py:32
msgid "unique integer value"
msgstr ""
msgstr "مقداد عدد یکتا"
#: schemas/utils.py:34
msgid "UUID string"
msgstr ""
msgstr "رشته UUID"
#: schemas/utils.py:36
msgid "unique value"
msgstr ""
msgstr "مقدار یکتا"
#: schemas/utils.py:38
#, python-brace-format
msgid "A {value_type} identifying this {name}."
msgstr ""
msgstr "یک {value_type} که این {name} را شناسایی میکند."
#: serializers.py:337
#, python-brace-format
@ -484,7 +484,7 @@ msgstr "داده نامعتبر. باید دیکشنری ارسال می شد،
#: templates/rest_framework/admin.html:116
#: templates/rest_framework/base.html:136
msgid "Extra Actions"
msgstr ""
msgstr "اقدامات اضافی"
#: templates/rest_framework/admin.html:130
#: templates/rest_framework/base.html:150
@ -493,27 +493,27 @@ msgstr "فیلترها"
#: templates/rest_framework/base.html:37
msgid "navbar"
msgstr ""
msgstr "نوار ناوبری"
#: templates/rest_framework/base.html:75
msgid "content"
msgstr ""
msgstr "محتوا"
#: templates/rest_framework/base.html:78
msgid "request form"
msgstr ""
msgstr "فرم درخواست"
#: templates/rest_framework/base.html:157
msgid "main content"
msgstr ""
msgstr "محتوای اصلی"
#: templates/rest_framework/base.html:173
msgid "request info"
msgstr ""
msgstr "اطلاعات درخواست"
#: templates/rest_framework/base.html:177
msgid "response info"
msgstr ""
msgstr "اطلاعات پاسخ"
#: templates/rest_framework/horizontal/radio.html:4
#: templates/rest_framework/inline/radio.html:3
@ -539,7 +539,7 @@ msgstr "فیلدهای {field_names} باید یک مجموعه یکتا باش
#: validators.py:171
#, python-brace-format
msgid "Surrogate characters are not allowed: U+{code_point:X}."
msgstr ""
msgstr "کاراکترهای جایگزین مجاز نیستند: U+{code_point:X}."
#: validators.py:243
#, python-brace-format

View File

@ -1,21 +1,21 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
#
#
# Translators:
# Erwann Mest <m+transifex@kud.io>, 2019
# Etienne Desgagné <etienne.desgagne@evimbec.ca>, 2015
# Martin Maillard <martin.maillard@gmail.com>, 2015
# Martin Maillard <martin.maillard@gmail.com>, 2015
# Stéphane Raimbault <stephane.raimbault@gmail.com>, 2019
# Xavier Ordoquy <xordoquy@linovia.com>, 2015-2016
# Sébastien Corbin <seb.corbin@gmail.com>, 2025
msgid ""
msgstr ""
"Project-Id-Version: Django REST framework\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-10-13 21:45+0200\n"
"PO-Revision-Date: 2020-10-13 19:45+0000\n"
"Last-Translator: Xavier Ordoquy <xordoquy@linovia.com>\n"
"PO-Revision-Date: 2025-08-17 20:30+0200\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"
"MIME-Version: 1.0\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."
#: authentication.py:193
msgid ""
"Invalid token header. Token string should not contain invalid characters."
msgid "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."
#: authentication.py:203
@ -106,11 +105,11 @@ msgstr "Une erreur du serveur est survenue."
#: exceptions.py:142
msgid "Invalid input."
msgstr ""
msgstr "Entrée invalide."
#: exceptions.py:161
msgid "Malformed request."
msgstr "Requête malformée"
msgstr "Requête malformée."
#: exceptions.py:167
msgid "Incorrect authentication credentials."
@ -149,12 +148,12 @@ msgstr "Requête ralentie."
#: exceptions.py:224
#, python-brace-format
msgid "Expected available in {wait} second."
msgstr ""
msgstr "Disponible à nouveau dans {wait} seconde."
#: exceptions.py:225
#, python-brace-format
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
#: validators.py:183
@ -167,11 +166,11 @@ msgstr "Ce champ ne peut être nul."
#: fields.py:701
msgid "Must be a valid boolean."
msgstr ""
msgstr "Doit être un booléen valide."
#: fields.py:766
msgid "Not a valid string."
msgstr ""
msgstr "Chaîne de charactère invalide."
#: fields.py:767
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é."
#: fields.py:838
msgid ""
"Enter a valid \"slug\" consisting of letters, numbers, underscores or "
"hyphens."
msgid "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."
#: fields.py:839
msgid ""
"Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, "
"or hyphens."
msgstr ""
msgid "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, or hyphens."
msgstr "Ce champ ne doit contenir que des lettres Unicode, des nombres, des tirets bas _ et des traits d'union."
#: fields.py:854
msgid "Enter a valid URL."
@ -213,7 +208,7 @@ msgstr "Saisissez une URL valide."
#: fields.py:867
msgid "Must be a valid UUID."
msgstr ""
msgstr "Doit être un UUID valide."
#: fields.py:903
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
#, python-brace-format
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
#, 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
#, python-brace-format
msgid ""
"Ensure that there are no more than {max_decimal_places} decimal places."
msgid "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."
#: fields.py:1009
#, python-brace-format
msgid ""
"Ensure that there are no more than {max_whole_digits} digits before the "
"decimal point."
msgid "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."
#: fields.py:1148
@ -271,11 +263,11 @@ msgstr "Attendait une date + heure mais a reçu une date."
#: fields.py:1150
#, python-brace-format
msgid "Invalid datetime for the timezone \"{timezone}\"."
msgstr ""
msgstr "Date et heure non valides pour le fuseau horaire \"{timezone}\"."
#: fields.py:1151
msgid "Datetime value out of range."
msgstr ""
msgstr "Valeur de date et heure hors de l'intervalle."
#: fields.py:1236
#, python-brace-format
@ -325,8 +317,7 @@ msgid "No file was submitted."
msgstr "Aucun fichier n'a été soumis."
#: fields.py:1515
msgid ""
"The submitted data was not a file. Check the encoding type on the form."
msgid "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."
#: fields.py:1516
@ -339,14 +330,11 @@ msgstr "Le fichier soumis est vide."
#: fields.py:1518
#, python-brace-format
msgid ""
"Ensure this filename has at most {max_length} characters (it has {length})."
msgid "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})."
#: fields.py:1566
msgid ""
"Upload a valid image. The file you uploaded was either not an image or a "
"corrupted image."
msgid "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."
#: fields.py:1604 relations.py:486 serializers.py:571
@ -356,12 +344,12 @@ msgstr "Cette liste ne peut pas être vide."
#: fields.py:1605
#, python-brace-format
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
#, python-brace-format
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
#, python-brace-format
@ -370,7 +358,7 @@ msgstr "Attendait un dictionnaire d'éléments mais a reçu « {input_type} »
#: fields.py:1683
msgid "This dictionary may not be empty."
msgstr ""
msgstr "Ce dictionnaire ne peut être vide."
#: fields.py:1755
msgid "Value must be valid JSON."
@ -382,7 +370,7 @@ msgstr "Recherche"
#: filters.py:50
msgid "A search term."
msgstr ""
msgstr "Un terme de recherche."
#: filters.py:180 templates/rest_framework/filters/ordering.html:3
msgid "Ordering"
@ -390,7 +378,7 @@ msgstr "Ordre"
#: filters.py:181
msgid "Which field to use when ordering the results."
msgstr ""
msgstr "Quel champ utiliser pour classer les résultats."
#: filters.py:287
msgid "ascending"
@ -402,11 +390,11 @@ msgstr "décroissant"
#: pagination.py:174
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
msgid "Number of results to return per page."
msgstr ""
msgstr "Nombre de résultats à retourner par page."
#: pagination.py:189
msgid "Invalid page."
@ -414,11 +402,11 @@ msgstr "Page non valide."
#: pagination.py:374
msgid "The initial index from which to return the results."
msgstr ""
msgstr "L'index initial depuis lequel retourner les résultats."
#: pagination.py:581
msgid "The pagination cursor value."
msgstr ""
msgstr "La valeur du curseur de pagination."
#: pagination.py:583
msgid "Invalid cursor"
@ -454,7 +442,7 @@ msgstr "Type incorrect. Attendait une URL, a reçu {data_type}."
#: relations.py:448
#, python-brace-format
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
msgid "Invalid value."
@ -462,20 +450,20 @@ msgstr "Valeur non valide."
#: schemas/utils.py:32
msgid "unique integer value"
msgstr ""
msgstr "valeur entière unique"
#: schemas/utils.py:34
msgid "UUID string"
msgstr ""
msgstr "Chaîne UUID"
#: schemas/utils.py:36
msgid "unique value"
msgstr ""
msgstr "valeur unique"
#: schemas/utils.py:38
#, python-brace-format
msgid "A {value_type} identifying this {name}."
msgstr ""
msgstr "Un(une) {value_type} identifiant ce(cette) {name}."
#: serializers.py:337
#, 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/base.html:136
msgid "Extra Actions"
msgstr ""
msgstr "Actions supplémentaires"
#: templates/rest_framework/admin.html:130
#: templates/rest_framework/base.html:150
@ -494,27 +482,27 @@ msgstr "Filtres"
#: templates/rest_framework/base.html:37
msgid "navbar"
msgstr ""
msgstr "barre de navigation"
#: templates/rest_framework/base.html:75
msgid "content"
msgstr ""
msgstr "contenu"
#: templates/rest_framework/base.html:78
msgid "request form"
msgstr ""
msgstr "formulaire de requête"
#: templates/rest_framework/base.html:157
msgid "main content"
msgstr ""
msgstr "contenu principal"
#: templates/rest_framework/base.html:173
msgid "request info"
msgstr ""
msgstr "information de la requête"
#: templates/rest_framework/base.html:177
msgid "response info"
msgstr ""
msgstr "information de la réponse"
#: templates/rest_framework/horizontal/radio.html:4
#: templates/rest_framework/inline/radio.html:3
@ -540,7 +528,7 @@ msgstr "Les champs {field_names} doivent former un ensemble unique."
#: validators.py:171
#, python-brace-format
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
#, python-brace-format

Some files were not shown because too many files have changed in this diff Show More