Merge branch 'encode:master' into booleanfield-fix
22
.github/stale.yml
vendored
Normal file
|
@ -0,0 +1,22 @@
|
|||
# Documentation: https://github.com/probot/stale
|
||||
|
||||
# Number of days of inactivity before an issue becomes stale
|
||||
daysUntilStale: 60
|
||||
|
||||
# Number of days of inactivity before a stale issue is closed
|
||||
daysUntilClose: 7
|
||||
|
||||
# Comment to post when marking an issue as stale. Set to `false` to disable
|
||||
markComment: >
|
||||
This issue has been automatically marked as stale because it has not had
|
||||
recent activity. It will be closed if no further activity occurs. Thank you
|
||||
for your contributions.
|
||||
|
||||
# Comment to post when closing a stale issue. Set to `false` to disable
|
||||
closeComment: false
|
||||
|
||||
# Limit the number of actions per hour, from 1-30. Default is 30
|
||||
limitPerRun: 1
|
||||
|
||||
# Label to use when marking as stale
|
||||
staleLabel: stale
|
14
.github/workflows/main.yml
vendored
|
@ -18,20 +18,16 @@ jobs:
|
|||
- '3.7'
|
||||
- '3.8'
|
||||
- '3.9'
|
||||
- '3.10'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions/setup-python@v2
|
||||
- uses: actions/setup-python@v3
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- uses: actions/cache@v2
|
||||
with:
|
||||
path: ~/.cache/pip
|
||||
key: ${{ runner.os }}-pip-${{ hashFiles('requirements/*.txt') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pip-
|
||||
cache: 'pip'
|
||||
cache-dependency-path: 'requirements/*.txt'
|
||||
|
||||
- name: Upgrade packaging tools
|
||||
run: python -m pip install --upgrade pip setuptools virtualenv wheel
|
||||
|
|
|
@ -1,3 +1,7 @@
|
|||
# Contributing to REST framework
|
||||
|
||||
See the [Contributing guide in the documentation](https://www.django-rest-framework.org/community/contributing/).
|
||||
At this point in it's 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.
|
||||
|
||||
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.
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
include README.md
|
||||
include LICENSE.md
|
||||
recursive-include tests/ *
|
||||
recursive-include rest_framework/static *.js *.css *.png *.ico *.eot *.svg *.ttf *.woff *.woff2
|
||||
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__
|
||||
|
|
42
README.md
|
@ -21,13 +21,14 @@ The initial aim is to provide a single full-time position on REST framework.
|
|||
|
||||
[![][sentry-img]][sentry-url]
|
||||
[![][stream-img]][stream-url]
|
||||
[![][rollbar-img]][rollbar-url]
|
||||
[![][esg-img]][esg-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]
|
||||
|
||||
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Rollbar][rollbar-url], [ESG][esg-url], [Retool][retool-url], [bit.io][bitio-url], and [PostHog][posthog-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], and [FEZTO][fezto-url].
|
||||
|
||||
---
|
||||
|
||||
|
@ -53,8 +54,8 @@ There is a live example API for testing purposes, [available here][sandbox].
|
|||
|
||||
# Requirements
|
||||
|
||||
* Python (3.5, 3.6, 3.7, 3.8, 3.9)
|
||||
* Django (2.2, 3.0, 3.1, 3.2)
|
||||
* Python 3.6+
|
||||
* Django 4.1, 4.0, 3.2, 3.1, 3.0
|
||||
|
||||
We **highly recommend** and only officially support the latest patch release of
|
||||
each Python and Django series.
|
||||
|
@ -66,11 +67,12 @@ Install using `pip`...
|
|||
pip install djangorestframework
|
||||
|
||||
Add `'rest_framework'` to your `INSTALLED_APPS` setting.
|
||||
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
]
|
||||
```python
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
]
|
||||
```
|
||||
|
||||
# Example
|
||||
|
||||
|
@ -88,9 +90,10 @@ Startup up a new project like so...
|
|||
Now edit the `example/urls.py` module in your project:
|
||||
|
||||
```python
|
||||
from django.urls import path, include
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import serializers, viewsets, routers
|
||||
from django.urls import include, path
|
||||
from rest_framework import routers, serializers, viewsets
|
||||
|
||||
|
||||
# Serializers define the API representation.
|
||||
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||
|
@ -109,7 +112,6 @@ class UserViewSet(viewsets.ModelViewSet):
|
|||
router = routers.DefaultRouter()
|
||||
router.register(r'users', UserViewSet)
|
||||
|
||||
|
||||
# Wire up our API using automatic URL routing.
|
||||
# Additionally, we include login URLs for the browsable API.
|
||||
urlpatterns = [
|
||||
|
@ -183,7 +185,7 @@ Please see the [security policy][security-policy].
|
|||
[codecov]: https://codecov.io/github/encode/django-rest-framework?branch=master
|
||||
[pypi-version]: https://img.shields.io/pypi/v/djangorestframework.svg
|
||||
[pypi]: https://pypi.org/project/djangorestframework/
|
||||
[twitter]: https://twitter.com/_tomchristie
|
||||
[twitter]: https://twitter.com/starletdreaming
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
|
||||
|
@ -192,19 +194,21 @@ Please see the [security policy][security-policy].
|
|||
|
||||
[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
|
||||
[rollbar-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/rollbar-readme.png
|
||||
[esg-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/esg-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
|
||||
|
||||
[sentry-url]: https://getsentry.com/welcome/
|
||||
[stream-url]: https://getstream.io/?utm_source=drf&utm_medium=sponsorship&utm_content=developer
|
||||
[rollbar-url]: https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial
|
||||
[esg-url]: https://software.esg-usa.com/
|
||||
[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
|
||||
|
||||
[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
|
||||
|
|
|
@ -2,8 +2,8 @@
|
|||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you believe you've found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**.
|
||||
Security issues are handled under the supervision of the [Django security team](https://www.djangoproject.com/foundation/teams/#security-team).
|
||||
|
||||
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
**Please report security issues by emailing security@djangoproject.com**.
|
||||
|
||||
[security-mail]: mailto:rest-framework-security@googlegroups.com
|
||||
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
|
|
|
@ -120,6 +120,14 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
|
|||
|
||||
## TokenAuthentication
|
||||
|
||||
---
|
||||
|
||||
**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.
|
||||
|
||||
---
|
||||
|
||||
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.
|
||||
|
||||
To use the `TokenAuthentication` scheme you'll need to [configure the authentication classes](#setting-the-authentication-scheme) to include `TokenAuthentication`, and additionally include `rest_framework.authtoken` in your `INSTALLED_APPS` setting:
|
||||
|
@ -129,11 +137,9 @@ To use the `TokenAuthentication` scheme you'll need to [configure the authentica
|
|||
'rest_framework.authtoken'
|
||||
]
|
||||
|
||||
---
|
||||
Make sure to run `manage.py migrate` after changing your settings.
|
||||
|
||||
**Note:** Make sure to run `manage.py migrate` after changing your settings. The `rest_framework.authtoken` app provides Django database migrations.
|
||||
|
||||
---
|
||||
The `rest_framework.authtoken` app provides Django database migrations.
|
||||
|
||||
You'll also need to create tokens for your users.
|
||||
|
||||
|
@ -146,7 +152,7 @@ For clients to authenticate, the token key should be included in the `Authorizat
|
|||
|
||||
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
|
||||
|
||||
**Note:** If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable.
|
||||
*If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable.*
|
||||
|
||||
If successfully authenticated, `TokenAuthentication` provides the following credentials.
|
||||
|
||||
|
@ -167,9 +173,9 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
|
|||
|
||||
---
|
||||
|
||||
#### Generating Tokens
|
||||
### Generating Tokens
|
||||
|
||||
##### By using signals
|
||||
#### By using signals
|
||||
|
||||
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
|
||||
|
||||
|
@ -193,9 +199,9 @@ If you've already created some users, you can generate tokens for all existing u
|
|||
for user in User.objects.all():
|
||||
Token.objects.get_or_create(user=user)
|
||||
|
||||
##### By exposing an api endpoint
|
||||
#### By exposing an api endpoint
|
||||
|
||||
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behaviour. To use it, add the `obtain_auth_token` view to your URLconf:
|
||||
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
|
||||
|
||||
from rest_framework.authtoken import views
|
||||
urlpatterns += [
|
||||
|
@ -210,7 +216,7 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
|
|||
|
||||
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.
|
||||
|
||||
By default, there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply to throttle you'll need to override the view class,
|
||||
By default, there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
|
||||
and include them using the `throttle_classes` attribute.
|
||||
|
||||
If you need a customized version of the `obtain_auth_token` view, you can do so by subclassing the `ObtainAuthToken` view class, and using that in your url conf instead.
|
||||
|
@ -242,9 +248,9 @@ And in your `urls.py`:
|
|||
]
|
||||
|
||||
|
||||
##### With Django admin
|
||||
#### With Django admin
|
||||
|
||||
It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
||||
It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
||||
|
||||
`your_app/admin.py`:
|
||||
|
||||
|
@ -283,7 +289,7 @@ If you're using an AJAX-style API with SessionAuthentication, you'll need to mak
|
|||
|
||||
**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
|
||||
|
||||
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.
|
||||
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behavior is not suitable for login views, which should always have CSRF validation applied.
|
||||
|
||||
|
||||
## RemoteUserAuthentication
|
||||
|
@ -293,7 +299,7 @@ environment variable.
|
|||
|
||||
To use it, you must have `django.contrib.auth.backends.RemoteUserBackend` (or a subclass) in your
|
||||
`AUTHENTICATION_BACKENDS` setting. By default, `RemoteUserBackend` creates `User` objects for usernames that don't
|
||||
already exist. To change this and other behaviour, consult the
|
||||
already exist. To change this and other behavior, consult the
|
||||
[Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/).
|
||||
|
||||
If successfully authenticated, `RemoteUserAuthentication` provides the following credentials:
|
||||
|
@ -301,7 +307,7 @@ If successfully authenticated, `RemoteUserAuthentication` provides the following
|
|||
* `request.user` will be a Django `User` instance.
|
||||
* `request.auth` will be `None`.
|
||||
|
||||
Consult your web server's documentation for information about configuring an authentication method, e.g.:
|
||||
Consult your web server's documentation for information about configuring an authentication method, for example:
|
||||
|
||||
* [Apache Authentication How-To](https://httpd.apache.org/docs/2.4/howto/auth.html)
|
||||
* [NGINX (Restricting Access)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)
|
||||
|
@ -332,7 +338,7 @@ If the `.authenticate_header()` method is not overridden, the authentication sch
|
|||
|
||||
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'.
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import authentication
|
||||
from rest_framework import exceptions
|
||||
|
||||
|
@ -355,11 +361,15 @@ The following example will authenticate any incoming request as the user given b
|
|||
|
||||
The following third-party packages are also available.
|
||||
|
||||
## django-rest-knox
|
||||
|
||||
[Django-rest-knox][django-rest-knox] library provides models and views to handle token-based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).
|
||||
|
||||
## Django OAuth Toolkit
|
||||
|
||||
The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by [jazzband][jazzband] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
|
||||
|
||||
#### Installation & configuration
|
||||
### Installation & configuration
|
||||
|
||||
Install using `pip`.
|
||||
|
||||
|
@ -386,7 +396,7 @@ The [Django REST framework OAuth][django-rest-framework-oauth] package provides
|
|||
|
||||
This package was previously included directly in the REST framework but is now supported and maintained as a third-party package.
|
||||
|
||||
#### Installation & configuration
|
||||
### Installation & configuration
|
||||
|
||||
Install the package using `pip`.
|
||||
|
||||
|
@ -408,7 +418,7 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
|
|||
|
||||
## Djoser
|
||||
|
||||
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is ready to use REST implementation of the Django authentication system.
|
||||
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.
|
||||
|
||||
## django-rest-auth / dj-rest-auth
|
||||
|
||||
|
@ -420,13 +430,9 @@ There are currently two forks of this project.
|
|||
* [Django-rest-auth][django-rest-auth] is the original project, [but is not currently receiving updates](https://github.com/Tivix/django-rest-auth/issues/568).
|
||||
* [Dj-rest-auth][dj-rest-auth] is a newer fork of the project.
|
||||
|
||||
## django-rest-framework-social-oauth2
|
||||
## drf-social-oauth2
|
||||
|
||||
[Django-rest-framework-social-oauth2][django-rest-framework-social-oauth2] library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to "in-house" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.
|
||||
|
||||
## django-rest-knox
|
||||
|
||||
[Django-rest-knox][django-rest-knox] library provides models and views to handle token-based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).
|
||||
[Drf-social-oauth2][drf-social-oauth2] is a framework that helps you authenticate with major social oauth2 vendors, such as Facebook, Google, Twitter, Orcid, etc. It generates tokens in a JWTed way with an easy setup.
|
||||
|
||||
## drfpasswordless
|
||||
|
||||
|
@ -473,7 +479,7 @@ More information can be found in the [Documentation](https://django-rest-durin.r
|
|||
[djoser]: https://github.com/sunscrapers/djoser
|
||||
[django-rest-auth]: https://github.com/Tivix/django-rest-auth
|
||||
[dj-rest-auth]: https://github.com/jazzband/dj-rest-auth
|
||||
[django-rest-framework-social-oauth2]: https://github.com/PhilipGarnero/django-rest-framework-social-oauth2
|
||||
[drf-social-oauth2]: https://github.com/wagnerdelima/drf-social-oauth2
|
||||
[django-rest-knox]: https://github.com/James1345/django-rest-knox
|
||||
[drfpasswordless]: https://github.com/aaronn/django-rest-framework-passwordless
|
||||
[django-rest-authemail]: https://github.com/celiao/django-rest-authemail
|
||||
|
|
|
@ -82,7 +82,7 @@ The default content negotiation class may be set globally, using the `DEFAULT_CO
|
|||
|
||||
You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class-based views.
|
||||
|
||||
from myapp.negotiation import IgnoreClientContentNegotiation
|
||||
from myapp.negotiation import IgnoreClientContentNegotiation
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
|
|
|
@ -260,6 +260,15 @@ Set as `handler400`:
|
|||
|
||||
handler400 = 'rest_framework.exceptions.bad_request'
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third-party packages are also available.
|
||||
|
||||
## DRF Standardized Errors
|
||||
|
||||
The [drf-standardized-errors][drf-standardized-errors] package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.
|
||||
|
||||
[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
|
||||
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors
|
||||
|
|
|
@ -42,11 +42,11 @@ 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`.
|
||||
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`.
|
||||
|
||||
### `default`
|
||||
|
||||
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
|
||||
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.
|
||||
|
||||
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
|
||||
|
||||
|
@ -78,14 +78,14 @@ Defaults to `False`
|
|||
|
||||
### `source`
|
||||
|
||||
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`.
|
||||
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`.
|
||||
|
||||
When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal. Beware of possible n+1 problems when using source attribute if you are accessing a relational orm model. For example:
|
||||
|
||||
class CommentSerializer(serializers.Serializer):
|
||||
email = serializers.EmailField(source="user.email")
|
||||
|
||||
would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related].
|
||||
This case would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related].
|
||||
|
||||
The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
|
||||
|
||||
|
@ -151,7 +151,7 @@ Prior to Django 2.1 `models.BooleanField` fields were always `blank=True`. Thus
|
|||
since Django 2.1 default `serializers.BooleanField` instances will be generated
|
||||
without the `required` kwarg (i.e. equivalent to `required=True`) whereas with
|
||||
previous versions of Django, default `BooleanField` instances will be generated
|
||||
with a `required=False` option. If you want to control this behaviour manually,
|
||||
with a `required=False` option. If you want to control this behavior manually,
|
||||
explicitly declare the `BooleanField` on the serializer class, or use the
|
||||
`extra_kwargs` option to set the `required` flag.
|
||||
|
||||
|
@ -159,14 +159,6 @@ Corresponds to `django.db.models.fields.BooleanField`.
|
|||
|
||||
**Signature:** `BooleanField()`
|
||||
|
||||
## NullBooleanField
|
||||
|
||||
A boolean representation that also accepts `None` as a valid value.
|
||||
|
||||
Corresponds to `django.db.models.fields.NullBooleanField`.
|
||||
|
||||
**Signature:** `NullBooleanField()`
|
||||
|
||||
---
|
||||
|
||||
# String fields
|
||||
|
@ -179,10 +171,10 @@ Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.T
|
|||
|
||||
**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)`
|
||||
|
||||
- `max_length` - Validates that the input contains no more than this number of characters.
|
||||
- `min_length` - Validates that the input contains no fewer than this number of characters.
|
||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
|
||||
* `max_length` - Validates that the input contains no more than this number of characters.
|
||||
* `min_length` - Validates that the input contains no fewer than this number of characters.
|
||||
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
* `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
|
||||
|
||||
The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.
|
||||
|
||||
|
@ -230,11 +222,11 @@ A field that ensures the input is a valid UUID string. The `to_internal_value` m
|
|||
|
||||
**Signature:** `UUIDField(format='hex_verbose')`
|
||||
|
||||
- `format`: Determines the representation format of the uuid value
|
||||
- `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
- `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
|
||||
- `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
|
||||
- `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
* `format`: Determines the representation format of the uuid value
|
||||
* `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
* `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
|
||||
* `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
|
||||
* `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value`
|
||||
|
||||
## FilePathField
|
||||
|
@ -245,11 +237,11 @@ Corresponds to `django.forms.fields.FilePathField`.
|
|||
|
||||
**Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)`
|
||||
|
||||
- `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
|
||||
- `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
|
||||
- `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
|
||||
- `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
|
||||
- `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
|
||||
* `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
|
||||
* `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
|
||||
* `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
|
||||
* `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
|
||||
* `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
|
||||
|
||||
## IPAddressField
|
||||
|
||||
|
@ -259,8 +251,8 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen
|
|||
|
||||
**Signature**: `IPAddressField(protocol='both', unpack_ipv4=False, **options)`
|
||||
|
||||
- `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
|
||||
- `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
|
||||
* `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
|
||||
* `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
|
||||
|
||||
---
|
||||
|
||||
|
@ -274,8 +266,8 @@ Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.
|
|||
|
||||
**Signature**: `IntegerField(max_value=None, min_value=None)`
|
||||
|
||||
- `max_value` Validate that the number provided is no greater than this value.
|
||||
- `min_value` Validate that the number provided is no less than this value.
|
||||
* `max_value` Validate that the number provided is no greater than this value.
|
||||
* `min_value` Validate that the number provided is no less than this value.
|
||||
|
||||
## FloatField
|
||||
|
||||
|
@ -285,8 +277,8 @@ Corresponds to `django.db.models.fields.FloatField`.
|
|||
|
||||
**Signature**: `FloatField(max_value=None, min_value=None)`
|
||||
|
||||
- `max_value` Validate that the number provided is no greater than this value.
|
||||
- `min_value` Validate that the number provided is no less than this value.
|
||||
* `max_value` Validate that the number provided is no greater than this value.
|
||||
* `min_value` Validate that the number provided is no less than this value.
|
||||
|
||||
## DecimalField
|
||||
|
||||
|
@ -296,13 +288,13 @@ Corresponds to `django.db.models.fields.DecimalField`.
|
|||
|
||||
**Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)`
|
||||
|
||||
- `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
|
||||
- `decimal_places` The number of decimal places to store with the number.
|
||||
- `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
|
||||
- `max_value` Validate that the number provided is no greater than this value.
|
||||
- `min_value` Validate that the number provided is no less than this value.
|
||||
- `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
|
||||
- `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
|
||||
* `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
|
||||
* `decimal_places` The number of decimal places to store with the number.
|
||||
* `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
|
||||
* `max_value` Validate that the number provided is no greater than this value.
|
||||
* `min_value` Validate that the number provided is no less than this value.
|
||||
* `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
|
||||
* `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
|
||||
|
||||
#### Example usage
|
||||
|
||||
|
@ -314,10 +306,6 @@ And to validate numbers up to anything less than one billion with a resolution o
|
|||
|
||||
serializers.DecimalField(max_digits=19, decimal_places=10)
|
||||
|
||||
This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer.
|
||||
|
||||
If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise.
|
||||
|
||||
---
|
||||
|
||||
# Date and time fields
|
||||
|
@ -392,8 +380,8 @@ The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu
|
|||
|
||||
**Signature:** `DurationField(max_value=None, min_value=None)`
|
||||
|
||||
- `max_value` Validate that the duration provided is no greater than this value.
|
||||
- `min_value` Validate that the duration provided is no less than this value.
|
||||
* `max_value` Validate that the duration provided is no greater than this value.
|
||||
* `min_value` Validate that the duration provided is no less than this value.
|
||||
|
||||
---
|
||||
|
||||
|
@ -407,10 +395,10 @@ Used by `ModelSerializer` to automatically generate fields if the corresponding
|
|||
|
||||
**Signature:** `ChoiceField(choices)`
|
||||
|
||||
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
|
||||
Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
|
||||
|
||||
|
@ -420,10 +408,10 @@ A field that can accept a set of zero, one or many values, chosen from a limited
|
|||
|
||||
**Signature:** `MultipleChoiceField(choices)`
|
||||
|
||||
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
|
||||
As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
|
||||
|
||||
|
@ -444,9 +432,9 @@ Corresponds to `django.forms.fields.FileField`.
|
|||
|
||||
**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
||||
|
||||
- `max_length` - Designates the maximum length for the file name.
|
||||
- `allow_empty_file` - Designates if empty files are allowed.
|
||||
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
* `max_length` - Designates the maximum length for the file name.
|
||||
* `allow_empty_file` - Designates if empty files are allowed.
|
||||
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
|
||||
## ImageField
|
||||
|
||||
|
@ -456,9 +444,9 @@ Corresponds to `django.forms.fields.ImageField`.
|
|||
|
||||
**Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
||||
|
||||
- `max_length` - Designates the maximum length for the file name.
|
||||
- `allow_empty_file` - Designates if empty files are allowed.
|
||||
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
* `max_length` - Designates the maximum length for the file name.
|
||||
* `allow_empty_file` - Designates if empty files are allowed.
|
||||
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
|
||||
Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained.
|
||||
|
||||
|
@ -472,10 +460,10 @@ A field class that validates a list of objects.
|
|||
|
||||
**Signature**: `ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)`
|
||||
|
||||
- `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
|
||||
- `allow_empty` - Designates if empty lists are allowed.
|
||||
- `min_length` - Validates that the list contains no fewer than this number of elements.
|
||||
- `max_length` - Validates that the list contains no more than this number of elements.
|
||||
* `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
|
||||
* `allow_empty` - Designates if empty lists are allowed.
|
||||
* `min_length` - Validates that the list contains no fewer than this number of elements.
|
||||
* `max_length` - Validates that the list contains no more than this number of elements.
|
||||
|
||||
For example, to validate a list of integers you might use something like the following:
|
||||
|
||||
|
@ -496,8 +484,8 @@ A field class that validates a dictionary of objects. The keys in `DictField` ar
|
|||
|
||||
**Signature**: `DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
||||
|
||||
- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
|
||||
- `allow_empty` - Designates if empty dictionaries are allowed.
|
||||
* `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
|
||||
* `allow_empty` - Designates if empty dictionaries are allowed.
|
||||
|
||||
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
|
||||
|
||||
|
@ -514,8 +502,8 @@ A preconfigured `DictField` that is compatible with Django's postgres `HStoreFie
|
|||
|
||||
**Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
||||
|
||||
- `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
|
||||
- `allow_empty` - Designates if empty dictionaries are allowed.
|
||||
* `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
|
||||
* `allow_empty` - Designates if empty dictionaries are allowed.
|
||||
|
||||
Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings.
|
||||
|
||||
|
@ -525,8 +513,8 @@ A field class that validates that the incoming data structure consists of valid
|
|||
|
||||
**Signature**: `JSONField(binary, encoder)`
|
||||
|
||||
- `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
|
||||
- `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
|
||||
* `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
|
||||
* `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
|
||||
|
||||
---
|
||||
|
||||
|
@ -577,7 +565,7 @@ This is a read-only field. It gets its value by calling a method on the serializ
|
|||
|
||||
**Signature**: `SerializerMethodField(method_name=None)`
|
||||
|
||||
- `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
|
||||
* `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
|
||||
|
||||
The serializer method referred to by the `method_name` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
|
||||
|
||||
|
@ -783,7 +771,7 @@ Here the mapping between the target and source attribute pairs (`x` and
|
|||
`x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField`
|
||||
declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`.
|
||||
|
||||
Our new `DataPointSerializer` exhibits the same behaviour as the custom field
|
||||
Our new `DataPointSerializer` exhibits the same behavior as the custom field
|
||||
approach.
|
||||
|
||||
Serializing:
|
||||
|
@ -843,7 +831,7 @@ the [djangorestframework-recursive][djangorestframework-recursive] package provi
|
|||
|
||||
## django-rest-framework-gis
|
||||
|
||||
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
|
||||
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
|
||||
|
||||
## django-rest-framework-hstore
|
||||
|
||||
|
|
|
@ -224,7 +224,7 @@ The search behavior may be restricted by prepending various characters to the `s
|
|||
|
||||
* '^' Starts-with search.
|
||||
* '=' Exact matches.
|
||||
* '@' Full-text search. (Currently only supported Django's [PostgreSQL backend](https://docs.djangoproject.com/en/dev/ref/contrib/postgres/search/).)
|
||||
* '@' Full-text search. (Currently only supported Django's [PostgreSQL backend][postgres-search].)
|
||||
* '$' Regex search.
|
||||
|
||||
For example:
|
||||
|
@ -241,7 +241,7 @@ To dynamically change search fields based on request content, it's possible to s
|
|||
def get_search_fields(self, view, request):
|
||||
if request.query_params.get('title_only'):
|
||||
return ['title']
|
||||
return super(CustomSearchFilter, self).get_search_fields(view, request)
|
||||
return super().get_search_fields(view, request)
|
||||
|
||||
For more details, see the [Django documentation][search-django-admin].
|
||||
|
||||
|
@ -374,3 +374,4 @@ The [djangorestframework-word-filter][django-rest-framework-word-search-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
|
||||
[postgres-search]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/search/
|
||||
|
|
|
@ -23,8 +23,8 @@ Returns a URL pattern list which includes format suffix patterns appended to eac
|
|||
Arguments:
|
||||
|
||||
* **urlpatterns**: Required. A URL pattern list.
|
||||
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
|
||||
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
|
||||
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
|
||||
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
|
||||
|
||||
Example:
|
||||
|
||||
|
@ -62,7 +62,7 @@ Also note that `format_suffix_patterns` does not support descending into `includ
|
|||
|
||||
If using the `i18n_patterns` function provided by Django, as well as `format_suffix_patterns` you should make sure that the `i18n_patterns` function is applied as the final, or outermost function. For example:
|
||||
|
||||
url patterns = [
|
||||
urlpatterns = [
|
||||
…
|
||||
]
|
||||
|
||||
|
|
|
@ -65,7 +65,7 @@ The following attributes control the basic view behavior.
|
|||
|
||||
* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. If you are overriding a view method, it is important that you call `get_queryset()` instead of accessing this property directly, as `queryset` will get evaluated once, and those results will be cached for all subsequent requests.
|
||||
* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method.
|
||||
* `lookup_field` - The model field that should be used to for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
|
||||
* `lookup_field` - The model field that should be used for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
|
||||
* `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`.
|
||||
|
||||
**Pagination**:
|
||||
|
@ -98,7 +98,7 @@ For example:
|
|||
|
||||
---
|
||||
|
||||
**Note:** If the serializer_class used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related].
|
||||
**Note:** If the `serializer_class` used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related].
|
||||
|
||||
---
|
||||
|
||||
|
@ -217,7 +217,7 @@ If the request data provided for creating the object was invalid, a `400 Bad Req
|
|||
|
||||
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
|
||||
|
||||
If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`.
|
||||
If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise, it will return a `404 Not Found`.
|
||||
|
||||
## UpdateModelMixin
|
||||
|
||||
|
@ -335,7 +335,7 @@ For example, if you need to lookup objects based on multiple fields in the URL c
|
|||
queryset = self.filter_queryset(queryset) # Apply any filter backends
|
||||
filter = {}
|
||||
for field in self.lookup_fields:
|
||||
if self.kwargs[field]: # Ignore empty fields.
|
||||
if self.kwargs.get(field): # Ignore empty fields.
|
||||
filter[field] = self.kwargs[field]
|
||||
obj = get_object_or_404(queryset, **filter) # Lookup the object
|
||||
self.check_object_permissions(self.request, obj)
|
||||
|
@ -395,4 +395,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/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related
|
||||
|
|
|
@ -78,7 +78,7 @@ This pagination style accepts a single number page number in the request query p
|
|||
|
||||
HTTP 200 OK
|
||||
{
|
||||
"count": 1023
|
||||
"count": 1023,
|
||||
"next": "https://api.example.org/accounts/?page=5",
|
||||
"previous": "https://api.example.org/accounts/?page=3",
|
||||
"results": [
|
||||
|
@ -126,7 +126,7 @@ This pagination style mirrors the syntax used when looking up multiple database
|
|||
|
||||
HTTP 200 OK
|
||||
{
|
||||
"count": 1023
|
||||
"count": 1023,
|
||||
"next": "https://api.example.org/accounts/?limit=100&offset=500",
|
||||
"previous": "https://api.example.org/accounts/?limit=100&offset=300",
|
||||
"results": [
|
||||
|
@ -227,7 +227,7 @@ Note that the `paginate_queryset` method may set state on the pagination instanc
|
|||
|
||||
## Example
|
||||
|
||||
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
|
||||
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
|
||||
|
||||
class CustomPagination(pagination.PageNumberPagination):
|
||||
def get_paginated_response(self, data):
|
||||
|
|
|
@ -15,7 +15,7 @@ REST framework includes a number of built in Parser classes, that allow you to a
|
|||
|
||||
## How the parser is determined
|
||||
|
||||
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
|
||||
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
|
||||
|
||||
---
|
||||
|
||||
|
|
|
@ -171,13 +171,13 @@ This permission is suitable if you want to your API to allow read permissions to
|
|||
|
||||
## DjangoModelPermissions
|
||||
|
||||
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property or `get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned.
|
||||
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property or `get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned. The appropriate model is determined by checking `get_queryset().model` or `queryset.model`.
|
||||
|
||||
* `POST` requests require the user to have the `add` permission on the model.
|
||||
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
|
||||
* `DELETE` requests require the user to have the `delete` permission on the model.
|
||||
|
||||
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
|
||||
The default behavior can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
|
||||
|
||||
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
|
||||
|
||||
|
@ -286,7 +286,7 @@ The following table lists the access restriction methods and the level of contro
|
|||
|
||||
| | `queryset` | `permission_classes` | `serializer_class` |
|
||||
|------------------------------------|------------|----------------------|--------------------|
|
||||
| Action: list | global | no | object-level* |
|
||||
| Action: list | global | global | object-level* |
|
||||
| Action: create | no | global | object-level |
|
||||
| Action: retrieve | global | object-level | object-level |
|
||||
| Action: update | global | object-level | object-level |
|
||||
|
|
|
@ -19,7 +19,7 @@ Relational fields are used to represent model relationships. They can be applie
|
|||
|
||||
---
|
||||
|
||||
**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 object 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:
|
||||
|
||||
|
@ -33,7 +33,7 @@ For example, the following serializer would lead to a database hit each time eva
|
|||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
|
||||
# For each album object, tracks should be fetched from database
|
||||
qs = Album.objects.all()
|
||||
print(AlbumSerializer(qs, many=True).data)
|
||||
|
@ -246,7 +246,7 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e
|
|||
|
||||
## HyperlinkedIdentityField
|
||||
|
||||
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
|
||||
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
|
||||
|
||||
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
|
||||
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
|
||||
|
@ -278,7 +278,7 @@ This field is always read-only.
|
|||
|
||||
As opposed to previously discussed _references_ to another entity, the referred entity can instead also be embedded or _nested_
|
||||
in the representation of the object that refers to it.
|
||||
Such nested relationships can be expressed by using serializers as fields.
|
||||
Such nested relationships can be expressed by using serializers as fields.
|
||||
|
||||
If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field.
|
||||
|
||||
|
@ -494,8 +494,8 @@ This behavior is intended to prevent a template from being unable to render in a
|
|||
|
||||
There are two keyword arguments you can use to control this behavior:
|
||||
|
||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`.
|
||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`.
|
||||
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
|
||||
You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`.
|
||||
|
||||
|
|
|
@ -105,7 +105,7 @@ The TemplateHTMLRenderer will create a `RequestContext`, using the `response.dat
|
|||
|
||||
---
|
||||
|
||||
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example:
|
||||
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the `TemplateHTMLRenderer` to render it. For example:
|
||||
|
||||
```
|
||||
response.data = {'results': response.data}
|
||||
|
@ -192,7 +192,7 @@ By default the response content will be rendered with the highest priority rende
|
|||
def get_default_renderer(self, view):
|
||||
return JSONRenderer()
|
||||
|
||||
## AdminRenderer
|
||||
## AdminRenderer
|
||||
|
||||
Renders data into HTML for an admin-like display:
|
||||
|
||||
|
@ -257,7 +257,7 @@ This renderer is used for rendering HTML multipart form data. **It is not suita
|
|||
|
||||
# Custom renderers
|
||||
|
||||
To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, media_type=None, renderer_context=None)` method.
|
||||
To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, accepted_media_type=None, renderer_context=None)` method.
|
||||
|
||||
The method should return a bytestring, which will be used as the body of the HTTP response.
|
||||
|
||||
|
@ -267,7 +267,7 @@ The arguments passed to the `.render()` method are:
|
|||
|
||||
The request data, as set by the `Response()` instantiation.
|
||||
|
||||
### `media_type=None`
|
||||
### `accepted_media_type=None`
|
||||
|
||||
Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.
|
||||
|
||||
|
@ -291,7 +291,7 @@ The following is an example plaintext renderer that will return a response with
|
|||
media_type = 'text/plain'
|
||||
format = 'txt'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return smart_text(data, encoding=self.charset)
|
||||
|
||||
## Setting the character set
|
||||
|
@ -303,7 +303,7 @@ By default renderer classes are assumed to be using the `UTF-8` encoding. To us
|
|||
format = 'txt'
|
||||
charset = 'iso-8859-1'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return data.encode(self.charset)
|
||||
|
||||
Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the `Response` class, with the `charset` attribute set on the renderer used to determine the encoding.
|
||||
|
@ -318,7 +318,7 @@ In some cases you may also want to set the `render_style` attribute to `'binary'
|
|||
charset = None
|
||||
render_style = 'binary'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return data
|
||||
|
||||
---
|
||||
|
@ -332,7 +332,7 @@ You can do some pretty flexible things using REST framework's renderers. Some e
|
|||
* Specify multiple types of HTML representation for API clients to use.
|
||||
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
|
||||
|
||||
## Varying behaviour by media type
|
||||
## Varying behavior by media type
|
||||
|
||||
In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
|
||||
|
||||
|
@ -470,15 +470,15 @@ Modify your REST framework settings.
|
|||
|
||||
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
|
||||
|
||||
## XLSX (Binary Spreadsheet Endpoints)
|
||||
## Microsoft Excel: XLSX (Binary Spreadsheet Endpoints)
|
||||
|
||||
XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-renderer-xlsx][drf-renderer-xlsx], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
|
||||
XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-excel][drf-excel], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
|
||||
|
||||
#### Installation & configuration
|
||||
|
||||
Install using pip.
|
||||
|
||||
$ pip install drf-renderer-xlsx
|
||||
$ pip install drf-excel
|
||||
|
||||
Modify your REST framework settings.
|
||||
|
||||
|
@ -488,15 +488,15 @@ Modify your REST framework settings.
|
|||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
'drf_renderer_xlsx.renderers.XLSXRenderer',
|
||||
'drf_excel.renderers.XLSXRenderer',
|
||||
],
|
||||
}
|
||||
|
||||
To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the `Content-Disposition` header. If no filename is provided, it will default to `export.xlsx`. For example:
|
||||
|
||||
from rest_framework.viewsets import ReadOnlyModelViewSet
|
||||
from drf_renderer_xlsx.mixins import XLSXFileMixin
|
||||
from drf_renderer_xlsx.renderers import XLSXRenderer
|
||||
from drf_excel.mixins import XLSXFileMixin
|
||||
from drf_excel.renderers import XLSXRenderer
|
||||
|
||||
from .models import MyExampleModel
|
||||
from .serializers import MyExampleSerializer
|
||||
|
@ -549,7 +549,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
|||
[mjumbewu]: https://github.com/mjumbewu
|
||||
[flipperpa]: https://github.com/flipperpa
|
||||
[wharton]: https://github.com/wharton
|
||||
[drf-renderer-xlsx]: https://github.com/wharton/drf-renderer-xlsx
|
||||
[drf-excel]: https://github.com/wharton/drf-excel
|
||||
[vbabiy]: https://github.com/vbabiy
|
||||
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
|
||||
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
|
||||
|
|
|
@ -49,7 +49,7 @@ If a client sends a request with a content-type that cannot be parsed then a `Un
|
|||
|
||||
# Content negotiation
|
||||
|
||||
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialization schemes for different media types.
|
||||
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behavior such as selecting a different serialization schemes for different media types.
|
||||
|
||||
## .accepted_renderer
|
||||
|
||||
|
|
|
@ -32,16 +32,16 @@ You should **include the request as a keyword argument** to the function, for ex
|
|||
|
||||
from rest_framework.reverse import reverse
|
||||
from rest_framework.views import APIView
|
||||
from django.utils.timezone import now
|
||||
from django.utils.timezone import now
|
||||
|
||||
class APIRootView(APIView):
|
||||
def get(self, request):
|
||||
year = now().year
|
||||
data = {
|
||||
...
|
||||
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
||||
class APIRootView(APIView):
|
||||
def get(self, request):
|
||||
year = now().year
|
||||
data = {
|
||||
...
|
||||
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
||||
}
|
||||
return Response(data)
|
||||
return Response(data)
|
||||
|
||||
## reverse_lazy
|
||||
|
||||
|
|
|
@ -338,5 +338,5 @@ 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/1.11/topics/http/urls/#url-namespaces
|
||||
[include-api-reference]: https://docs.djangoproject.com/en/2.0/ref/urls/#include
|
||||
[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
|
||||
|
|
|
@ -122,6 +122,7 @@ The `get_schema_view()` helper takes the following keyword arguments:
|
|||
url='https://www.example.org/api/',
|
||||
patterns=schema_url_patterns,
|
||||
)
|
||||
* `public`: May be used to specify if schema should bypass views permissions. Default to False
|
||||
|
||||
* `generator_class`: May be used to specify a `SchemaGenerator` subclass to be
|
||||
passed to the `SchemaView`.
|
||||
|
@ -165,7 +166,7 @@ In order to customize the top-level schema, subclass
|
|||
as an argument to the `generateschema` command or `get_schema_view()` helper
|
||||
function.
|
||||
|
||||
### get_schema(self, request)
|
||||
### get_schema(self, request=None, public=False)
|
||||
|
||||
Returns a dictionary that represents the OpenAPI schema:
|
||||
|
||||
|
@ -292,7 +293,7 @@ class CustomView(APIView):
|
|||
|
||||
This saves you having to create a custom subclass per-view for a commonly used option.
|
||||
|
||||
Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for
|
||||
Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for
|
||||
the more commonly needed options do.
|
||||
|
||||
### `AutoSchema` methods
|
||||
|
@ -300,7 +301,7 @@ the more commonly needed options do.
|
|||
#### `get_components()`
|
||||
|
||||
Generates the OpenAPI components that describe request and response bodies,
|
||||
deriving their properties from the serializer.
|
||||
deriving their properties from the serializer.
|
||||
|
||||
Returns a dictionary mapping the component name to the generated
|
||||
representation. By default this has just a single pair but you may override
|
||||
|
@ -313,6 +314,11 @@ Computes the component's name from the serializer.
|
|||
|
||||
You may see warnings if your API has duplicate component names. If so you can override `get_component_name()` or pass the `component_name` `__init__()` kwarg (see below) to provide different names.
|
||||
|
||||
#### `get_reference()`
|
||||
|
||||
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
|
||||
|
||||
|
||||
#### `map_serializer()`
|
||||
|
||||
Maps serializers to their OpenAPI representations.
|
||||
|
|
|
@ -524,6 +524,7 @@ You can add extra fields to a `ModelSerializer` or override the default fields b
|
|||
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ['url', 'groups']
|
||||
|
||||
Extra fields can correspond to any property or callable on the model.
|
||||
|
||||
|
@ -593,25 +594,25 @@ The ModelSerializer class also exposes an API that you can override in order to
|
|||
|
||||
Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.
|
||||
|
||||
### `.serializer_field_mapping`
|
||||
### `serializer_field_mapping`
|
||||
|
||||
A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
|
||||
|
||||
### `.serializer_related_field`
|
||||
### `serializer_related_field`
|
||||
|
||||
This property should be the serializer field class, that is used for relational fields by default.
|
||||
|
||||
For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`.
|
||||
For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`.
|
||||
|
||||
For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`.
|
||||
|
||||
### `.serializer_url_field`
|
||||
### `serializer_url_field`
|
||||
|
||||
The serializer field class that should be used for any `url` field on the serializer.
|
||||
|
||||
Defaults to `serializers.HyperlinkedIdentityField`
|
||||
|
||||
### `.serializer_choice_field`
|
||||
### `serializer_choice_field`
|
||||
|
||||
The serializer field class that should be used for any choice fields on the serializer.
|
||||
|
||||
|
@ -621,13 +622,13 @@ Defaults to `serializers.ChoiceField`
|
|||
|
||||
The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`.
|
||||
|
||||
### `.build_standard_field(self, field_name, model_field)`
|
||||
### `build_standard_field(self, field_name, model_field)`
|
||||
|
||||
Called to generate a serializer field that maps to a standard model field.
|
||||
|
||||
The default implementation returns a serializer class based on the `serializer_field_mapping` attribute.
|
||||
|
||||
### `.build_relational_field(self, field_name, relation_info)`
|
||||
### `build_relational_field(self, field_name, relation_info)`
|
||||
|
||||
Called to generate a serializer field that maps to a relational model field.
|
||||
|
||||
|
@ -635,7 +636,7 @@ The default implementation returns a serializer class based on the `serializer_r
|
|||
|
||||
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
||||
|
||||
### `.build_nested_field(self, field_name, relation_info, nested_depth)`
|
||||
### `build_nested_field(self, field_name, relation_info, nested_depth)`
|
||||
|
||||
Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set.
|
||||
|
||||
|
@ -645,17 +646,17 @@ The `nested_depth` will be the value of the `depth` option, minus one.
|
|||
|
||||
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
||||
|
||||
### `.build_property_field(self, field_name, model_class)`
|
||||
### `build_property_field(self, field_name, model_class)`
|
||||
|
||||
Called to generate a serializer field that maps to a property or zero-argument method on the model class.
|
||||
|
||||
The default implementation returns a `ReadOnlyField` class.
|
||||
|
||||
### `.build_url_field(self, field_name, model_class)`
|
||||
### `build_url_field(self, field_name, model_class)`
|
||||
|
||||
Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class.
|
||||
|
||||
### `.build_unknown_field(self, field_name, model_class)`
|
||||
### `build_unknown_field(self, field_name, model_class)`
|
||||
|
||||
Called when the field name did not map to any model field or model property.
|
||||
The default implementation raises an error, although subclasses may customize this behavior.
|
||||
|
@ -885,7 +886,7 @@ Because this class provides the same interface as the `Serializer` class, you ca
|
|||
|
||||
The only difference you'll notice when doing so is the `BaseSerializer` classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.
|
||||
|
||||
##### Read-only `BaseSerializer` classes
|
||||
#### Read-only `BaseSerializer` classes
|
||||
|
||||
To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model:
|
||||
|
||||
|
@ -909,7 +910,7 @@ We can now use this class to serialize single `HighScore` instances:
|
|||
def high_score(request, pk):
|
||||
instance = HighScore.objects.get(pk=pk)
|
||||
serializer = HighScoreSerializer(instance)
|
||||
return Response(serializer.data)
|
||||
return Response(serializer.data)
|
||||
|
||||
Or use it to serialize multiple instances:
|
||||
|
||||
|
@ -917,9 +918,9 @@ Or use it to serialize multiple instances:
|
|||
def all_high_scores(request):
|
||||
queryset = HighScore.objects.order_by('-score')
|
||||
serializer = HighScoreSerializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
return Response(serializer.data)
|
||||
|
||||
##### Read-write `BaseSerializer` classes
|
||||
#### Read-write `BaseSerializer` classes
|
||||
|
||||
To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `serializers.ValidationError` if the supplied data is in an incorrect format.
|
||||
|
||||
|
@ -948,8 +949,8 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
|
|||
'player_name': 'May not be more than 10 characters.'
|
||||
})
|
||||
|
||||
# Return the validated values. This will be available as
|
||||
# the `.validated_data` property.
|
||||
# Return the validated values. This will be available as
|
||||
# the `.validated_data` property.
|
||||
return {
|
||||
'score': int(score),
|
||||
'player_name': player_name
|
||||
|
@ -968,7 +969,7 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
|
|||
|
||||
The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.
|
||||
|
||||
The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
|
||||
The following class is an example of a generic serializer that can handle coercing arbitrary complex objects into primitive representations.
|
||||
|
||||
class ObjectSerializer(serializers.BaseSerializer):
|
||||
"""
|
||||
|
@ -1020,7 +1021,7 @@ Some reasons this might be useful include...
|
|||
|
||||
The signatures for these methods are as follows:
|
||||
|
||||
#### `.to_representation(self, instance)`
|
||||
#### `to_representation(self, instance)`
|
||||
|
||||
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
|
||||
|
||||
|
@ -1032,7 +1033,7 @@ May be overridden in order to modify the representation style. For example:
|
|||
ret['username'] = ret['username'].lower()
|
||||
return ret
|
||||
|
||||
#### ``.to_internal_value(self, data)``
|
||||
#### ``to_internal_value(self, data)``
|
||||
|
||||
Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
|
||||
|
||||
|
@ -1095,7 +1096,7 @@ For example, if you wanted to be able to set which fields should be used by a se
|
|||
fields = kwargs.pop('fields', None)
|
||||
|
||||
# Instantiate the superclass normally
|
||||
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
if fields is not None:
|
||||
# Drop any fields that are not specified in the `fields` argument.
|
||||
|
@ -1188,7 +1189,7 @@ The [drf-writable-nested][drf-writable-nested] package provides writable nested
|
|||
|
||||
## DRF Encrypt Content
|
||||
|
||||
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
|
||||
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
|
||||
|
||||
|
||||
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
|
||||
|
|
|
@ -299,7 +299,7 @@ similar way as with `RequestsClient`.
|
|||
|
||||
# API Test cases
|
||||
|
||||
REST framework includes the following test case classes, that mirror the existing Django test case classes, but use `APIClient` instead of Django's default `Client`.
|
||||
REST framework includes the following test case classes, that mirror the existing [Django's test case classes][provided_test_case_classes], but use `APIClient` instead of Django's default `Client`.
|
||||
|
||||
* `APISimpleTestCase`
|
||||
* `APITransactionTestCase`
|
||||
|
@ -413,5 +413,6 @@ For example, to add support for using `format='html'` in test requests, you migh
|
|||
[client]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#the-test-client
|
||||
[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/1.11/ref/models/instances/#django.db.models.Model.refresh_from_db
|
||||
[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
|
||||
[provided_test_case_classes]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#provided-test-case-classes
|
||||
|
|
|
@ -19,6 +19,10 @@ 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 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
|
||||
|
||||
As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
|
||||
|
@ -46,9 +50,9 @@ The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `mi
|
|||
You can also set the throttling policy on a per-view or per-viewset basis,
|
||||
using the `APIView` class-based views.
|
||||
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.throttling import UserRateThrottle
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.views import APIView
|
||||
|
||||
class ExampleView(APIView):
|
||||
throttle_classes = [UserRateThrottle]
|
||||
|
@ -79,7 +83,7 @@ Throttle classes set in this way will override any viewset level class settings.
|
|||
}
|
||||
return Response(content)
|
||||
|
||||
## How clients are identified
|
||||
## How clients are identified
|
||||
|
||||
The `X-Forwarded-For` HTTP header and `REMOTE_ADDR` WSGI variable are used to uniquely identify client IP addresses for throttling. If the `X-Forwarded-For` header is present then it will be used, otherwise the value of the `REMOTE_ADDR` variable from the WSGI environment will be used.
|
||||
|
||||
|
@ -102,6 +106,12 @@ If you need to use a cache other than `'default'`, you can do so by creating a c
|
|||
|
||||
You'll need to remember to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute.
|
||||
|
||||
## A note on concurrency
|
||||
|
||||
The built-in throttle implementations are open to [race conditions][race], so under high concurrency they may allow a few extra requests through.
|
||||
|
||||
If your project relies on guaranteeing the number of requests during concurrent requests, you will need to implement your own throttle class. See [issue #5181][gh5181] for more details.
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
@ -210,3 +220,5 @@ The following is an example of a rate throttle, that will randomly throttle 1 in
|
|||
[identifying-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster
|
||||
[cache-setting]: https://docs.djangoproject.com/en/stable/ref/settings/#caches
|
||||
[cache-docs]: https://docs.djangoproject.com/en/stable/topics/cache/#setting-up-the-cache
|
||||
[gh5181]: https://github.com/encode/django-rest-framework/issues/5181
|
||||
[race]: https://en.wikipedia.org/wiki/Race_condition#Data_race
|
||||
|
|
|
@ -20,7 +20,7 @@ Validation in Django REST framework serializers is handled a little differently
|
|||
With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
|
||||
|
||||
* It introduces a proper separation of concerns, making your code behavior more obvious.
|
||||
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
|
||||
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
|
||||
* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.
|
||||
|
||||
When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using `Serializer` classes instead, then you need to define the validation rules explicitly.
|
||||
|
@ -208,7 +208,7 @@ by specifying an empty list for the serializer `Meta.validators` attribute.
|
|||
|
||||
By default "unique together" validation enforces that all fields be
|
||||
`required=True`. In some cases, you might want to explicit apply
|
||||
`required=False` to one of the fields, in which case the desired behaviour
|
||||
`required=False` to one of the fields, in which case the desired behavior
|
||||
of the validation is ambiguous.
|
||||
|
||||
In this case you will typically need to exclude the validator from the
|
||||
|
|
|
@ -153,7 +153,7 @@ The core of this functionality is the `api_view` decorator, which takes a list o
|
|||
|
||||
This view will use the default renderers, parsers, authentication classes etc specified in the [settings].
|
||||
|
||||
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behaviour, specify which methods the view allows, like so:
|
||||
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so:
|
||||
|
||||
@api_view(['GET', 'POST'])
|
||||
def hello_world(request):
|
||||
|
|
|
@ -116,7 +116,7 @@ During dispatch, the following attributes are available on the `ViewSet`.
|
|||
* `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`.
|
||||
* `description` - the display description for the individual view of a viewset.
|
||||
|
||||
You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
||||
You may inspect these attributes to adjust behavior based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
||||
|
||||
def get_permissions(self):
|
||||
"""
|
||||
|
@ -125,7 +125,7 @@ You may inspect these attributes to adjust behaviour based on the current action
|
|||
if self.action == 'list':
|
||||
permission_classes = [IsAuthenticated]
|
||||
else:
|
||||
permission_classes = [IsAdmin]
|
||||
permission_classes = [IsAdminUser]
|
||||
return [permission() for permission in permission_classes]
|
||||
|
||||
## Marking extra actions for routing
|
||||
|
@ -247,7 +247,7 @@ In order to use a `GenericViewSet` class you'll override the class and either mi
|
|||
|
||||
The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
|
||||
|
||||
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
|
||||
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
|
||||
|
||||
#### Example
|
||||
|
||||
|
|
|
@ -24,7 +24,7 @@ Notable features of this new release include:
|
|||
* Support for overriding how validation errors are handled by your API.
|
||||
* A metadata API that allows you to customize how `OPTIONS` requests are handled by your API.
|
||||
* A more compact JSON output with unicode style encoding turned on by default.
|
||||
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
|
||||
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
|
||||
|
||||
Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two [Kickstarter stretch goals](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.
|
||||
|
||||
|
@ -632,7 +632,7 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel
|
|||
|
||||
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
|
||||
|
||||
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...
|
||||
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behavior in a way that did not simply lookup the field value from the object. For example...
|
||||
|
||||
def field_to_native(self, obj, field_name):
|
||||
"""A custom read-only field that returns the class name."""
|
||||
|
|
|
@ -30,12 +30,12 @@ in the URL path.
|
|||
|
||||
For example...
|
||||
|
||||
Method | Path | Tags
|
||||
Method | Path | Tags
|
||||
--------------------------------|-----------------|-------------
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']`
|
||||
`GET`, `POST` | `/users/` | `['users']`
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']`
|
||||
`GET`, `POST` | `/orders/` | `['orders']`
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']`
|
||||
`GET`, `POST` | `/users/` | `['users']`
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']`
|
||||
`GET`, `POST` | `/orders/` | `['orders']`
|
||||
|
||||
The tags used for a particular view may also be overridden...
|
||||
|
||||
|
|
55
docs/community/3.13-announcement.md
Normal file
|
@ -0,0 +1,55 @@
|
|||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
# Django REST framework 3.13
|
||||
|
||||
## Django 4.0 support
|
||||
|
||||
The latest release now fully supports Django 4.0.
|
||||
|
||||
Our requirements are now:
|
||||
|
||||
* Python 3.6+
|
||||
* Django 4.0, 3.2, 3.1, 2.2 (LTS)
|
||||
|
||||
## Fields arguments are now keyword-only
|
||||
|
||||
When instantiating fields on serializers, you should always use keyword arguments,
|
||||
such as `serializers.CharField(max_length=200)`. This has always been the case,
|
||||
and all the examples that we have in the documentation use keyword arguments,
|
||||
rather than positional arguments.
|
||||
|
||||
From REST framework 3.13 onwards, this is now *explicitly enforced*.
|
||||
|
||||
The most feasible cases where users might be accidentally omitting the keyword arguments
|
||||
are likely in the composite fields, `ListField` and `DictField`. For instance...
|
||||
|
||||
```python
|
||||
aliases = serializers.ListField(serializers.CharField())
|
||||
```
|
||||
|
||||
They must now use the more explicit keyword argument style...
|
||||
|
||||
```python
|
||||
aliases = serializers.ListField(child=serializers.CharField())
|
||||
```
|
||||
|
||||
This change has been made because using positional arguments here *does not* result in the expected behaviour.
|
||||
|
||||
See Pull Request [#7632](https://github.com/encode/django-rest-framework/pull/7632) for more details.
|
62
docs/community/3.14-announcement.md
Normal file
|
@ -0,0 +1,62 @@
|
|||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
# Django REST framework 3.14
|
||||
|
||||
## Django 4.1 support
|
||||
|
||||
The latest release now fully supports Django 4.1, and drops support for Django 2.2.
|
||||
|
||||
Our requirements are now:
|
||||
|
||||
* Python 3.6+
|
||||
* Django 4.1, 4.0, 3.2, 3.1, 3.0
|
||||
|
||||
## `raise_exceptions` argument for `is_valid` is now keyword-only.
|
||||
|
||||
Calling `serializer_instance.is_valid(True)` is no longer acceptable syntax.
|
||||
If you'd like to use the `raise_exceptions` argument, you must use it as a
|
||||
keyword argument.
|
||||
|
||||
See Pull Request [#7952](https://github.com/encode/django-rest-framework/pull/7952) for more details.
|
||||
|
||||
## `ManyRelatedField` supports returning the default when the source attribute doesn't exist.
|
||||
|
||||
Previously, if you used a serializer field with `many=True` with a dot notated source field
|
||||
that didn't exist, it would raise an `AttributeError`. Now it will return the default or be
|
||||
skipped depending on the other arguments.
|
||||
|
||||
See Pull Request [#7574](https://github.com/encode/django-rest-framework/pull/7574) for more details.
|
||||
|
||||
|
||||
## Make Open API `get_reference` public.
|
||||
|
||||
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
|
||||
|
||||
## Change semantic of OR of two permission classes.
|
||||
|
||||
When OR-ing two permissions, the request has to pass either class's `has_permission() and has_object_permission()`.
|
||||
|
||||
Previously, both class's `has_permission()` was ignored when OR-ing two permissions together.
|
||||
|
||||
See Pull Request [#7522](https://github.com/encode/django-rest-framework/pull/7522) for more details.
|
||||
|
||||
## Minor fixes and improvements
|
||||
|
||||
There are a number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing.
|
|
@ -64,7 +64,7 @@ These are a little subtle and probably won't affect most users, but are worth un
|
|||
|
||||
### ManyToMany fields and blank=True
|
||||
|
||||
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
||||
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
||||
|
||||
As a follow-up to this we are now able to properly mirror the behavior of Django's `ModelForm` with respect to how many-to-many fields are validated.
|
||||
|
||||
|
|
|
@ -38,7 +38,7 @@ The AJAX based support for the browsable API means that there are a number of in
|
|||
|
||||
* To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.
|
||||
* The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class][accept-headers].
|
||||
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
|
||||
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
|
||||
|
||||
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.
|
||||
|
||||
|
|
|
@ -89,7 +89,7 @@ Name | Support | PyPI pa
|
|||
---------------------------------|-------------------------------------|--------------------------------
|
||||
[Core JSON][core-json] | Schema generation & client support. | Built-in support in `coreapi`.
|
||||
[Swagger / OpenAPI][swagger] | Schema generation & client support. | The `openapi-codec` package.
|
||||
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
|
||||
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
|
||||
[API Blueprint][api-blueprint] | Not yet available. | Not yet available.
|
||||
|
||||
---
|
||||
|
|
|
@ -89,7 +89,7 @@ for a complete listing.
|
|||
|
||||
We're currently working towards moving to using [OpenAPI][openapi] as our default schema output. We'll also be revisiting our API documentation generation and client libraries.
|
||||
|
||||
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
|
||||
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
|
||||
|
||||
[funding]: funding.md
|
||||
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886
|
||||
|
|
|
@ -110,7 +110,7 @@ You can now compose permission classes using the and/or operators, `&` and `|`.
|
|||
For example...
|
||||
|
||||
```python
|
||||
permission_classes = [IsAuthenticated & (ReadOnly | IsAdmin)]
|
||||
permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)]
|
||||
```
|
||||
|
||||
If you're using custom permission classes then make sure that you are subclassing
|
||||
|
|
|
@ -6,6 +6,12 @@
|
|||
|
||||
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
|
||||
|
||||
---
|
||||
|
||||
**Note**: At this point in it's 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.
|
||||
|
||||
---
|
||||
|
||||
## Community
|
||||
|
||||
The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
|
||||
|
@ -26,14 +32,13 @@ The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines f
|
|||
|
||||
# Issues
|
||||
|
||||
It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the [discussion group][google-group]. Feature requests, bug reports and other issues should be raised on the GitHub [issue tracker][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 issue reporting:
|
||||
Some tips on good potential issue reporting:
|
||||
|
||||
* When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
|
||||
* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
|
||||
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
|
||||
* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.
|
||||
* Search the GitHub project page for related items, and make sure you're running the latest version of REST framework before reporting an issue.
|
||||
* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation. At this point in it's lifespan we consider Django REST framework to be essentially feature-complete.
|
||||
* Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.
|
||||
|
||||
## Triaging issues
|
||||
|
@ -75,7 +80,7 @@ To run the tests, clone the repository, and then:
|
|||
# Setup the virtual environment
|
||||
python3 -m venv env
|
||||
source env/bin/activate
|
||||
pip install django
|
||||
pip install -e .
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Run the tests
|
||||
|
|
|
@ -124,7 +124,7 @@ REST framework continues to be open-source and permissively licensed, but we fir
|
|||
## What funding has enabled so far
|
||||
|
||||
* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
|
||||
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
|
||||
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
|
||||
* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
|
||||
* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/).
|
||||
* Tom Christie, the creator of Django REST framework, working on the project full-time.
|
||||
|
@ -137,7 +137,7 @@ REST framework continues to be open-source and permissively licensed, but we fir
|
|||
## 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.
|
||||
* 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.
|
||||
|
@ -154,13 +154,13 @@ Sign up for a paid plan today, and help ensure that REST framework becomes a sus
|
|||
|
||||
|
||||
|
||||
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
|
||||
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
|
||||
>
|
||||
> — Filipe Ximenes, Vinta Software
|
||||
|
||||
|
||||
|
||||
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
|
||||
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
|
||||
DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.
|
||||
>
|
||||
> — Andrew Conti, Django REST framework user
|
||||
|
|
|
@ -11,7 +11,7 @@ Looking for a new Django REST Framework related role? On this site we provide a
|
|||
* [https://djangojobs.net/jobs/][django-jobs-net]
|
||||
* [https://findwork.dev/django-rest-framework-jobs][findwork-dev]
|
||||
* [https://www.indeed.com/q-Django-jobs.html][indeed-com]
|
||||
* [https://stackoverflow.com/jobs/developer-jobs-using-django][stackoverflow-com]
|
||||
* [https://stackoverflow.com/jobs/companies?tl=django][stackoverflow-com]
|
||||
* [https://www.upwork.com/o/jobs/browse/skill/django-framework/][upwork-com]
|
||||
* [https://www.technojobs.co.uk/django-jobs][technobjobs-co-uk]
|
||||
* [https://remoteok.io/remote-django-jobs][remoteok-io]
|
||||
|
@ -29,7 +29,7 @@ Wonder how else you can help? One of the best ways you can help Django REST Fram
|
|||
[django-jobs-net]: https://djangojobs.net/jobs/
|
||||
[findwork-dev]: https://findwork.dev/django-rest-framework-jobs
|
||||
[indeed-com]: https://www.indeed.com/q-Django-jobs.html
|
||||
[stackoverflow-com]: https://stackoverflow.com/jobs/developer-jobs-using-django
|
||||
[stackoverflow-com]: https://stackoverflow.com/jobs/companies?tl=django
|
||||
[upwork-com]: https://www.upwork.com/o/jobs/browse/skill/django-framework/
|
||||
[technobjobs-co-uk]: https://www.technojobs.co.uk/django-jobs
|
||||
[remoteok-io]: https://remoteok.io/remote-django-jobs
|
||||
|
|
|
@ -34,6 +34,47 @@ You can determine your currently installed version using `pip show`:
|
|||
|
||||
---
|
||||
|
||||
## 3.14.x series
|
||||
|
||||
### 3.14.0
|
||||
|
||||
Date: 22nd September 2022
|
||||
|
||||
* Django 2.2 is no longer supported. [[#8662](https://github.com/encode/django-rest-framework/pull/8662)]
|
||||
* Django 4.1 compatibility. [[#8591](https://github.com/encode/django-rest-framework/pull/8591)]
|
||||
* Add `--api-version` CLI option to `generateschema` management command. [[#8663](https://github.com/encode/django-rest-framework/pull/8663)]
|
||||
* Enforce `is_valid(raise_exception=False)` as a keyword-only argument. [[#7952](https://github.com/encode/django-rest-framework/pull/7952)]
|
||||
* Stop calling `set_context` on Validators. [[#8589](https://github.com/encode/django-rest-framework/pull/8589)]
|
||||
* Return `NotImplemented` from `ErrorDetails.__ne__`. [[#8538](https://github.com/encode/django-rest-framework/pull/8538)]
|
||||
* Don't evaluate `DateTimeField.default_timezone` when a custom timezone is set. [[#8531](https://github.com/encode/django-rest-framework/pull/8531)]
|
||||
* Make relative URLs clickable in Browseable API. [[#8464](https://github.com/encode/django-rest-framework/pull/8464)]
|
||||
* Support `ManyRelatedField` falling back to the default value when the attribute specified by dot notation doesn't exist. Matches `ManyRelatedField.get_attribute` to `Field.get_attribute`. [[#7574](https://github.com/encode/django-rest-framework/pull/7574)]
|
||||
* Make `schemas.openapi.get_reference` public. [[#7515](https://github.com/encode/django-rest-framework/pull/7515)]
|
||||
* Make `ReturnDict` support `dict` union operators on Python 3.9 and later. [[#8302](https://github.com/encode/django-rest-framework/pull/8302)]
|
||||
* Update throttling to check if `request.user` is set before checking if the user is authenticated. [[#8370](https://github.com/encode/django-rest-framework/pull/8370)]
|
||||
|
||||
## 3.13.x series
|
||||
|
||||
### 3.13.1
|
||||
|
||||
Date: 15th December 2021
|
||||
|
||||
* Revert schema naming changes with function based `@api_view`. [#8297]
|
||||
|
||||
### 3.13.0
|
||||
|
||||
Date: 13th December 2021
|
||||
|
||||
* Django 4.0 compatability. [#8178]
|
||||
* Add `max_length` and `min_length` options to `ListSerializer`. [#8165]
|
||||
* Add `get_request_serializer` and `get_response_serializer` hooks to `AutoSchema`. [#7424]
|
||||
* Fix OpenAPI representation of null-able read only fields. [#8116]
|
||||
* Respect `UNICODE_JSON` setting in API schema outputs. [#7991]
|
||||
* Fix for `RemoteUserAuthentication`. [#7158]
|
||||
* Make Field constructors keyword-only. [#7632]
|
||||
|
||||
---
|
||||
|
||||
## 3.12.x series
|
||||
|
||||
### 3.12.4
|
||||
|
|
|
@ -148,6 +148,8 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [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-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.
|
||||
|
||||
[cite]: http://www.software-ecosystems.com/Software_Ecosystems/Ecosystems.html
|
||||
[cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework
|
||||
|
@ -203,7 +205,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
|
||||
[django-url-filter]: https://github.com/miki725/django-url-filter
|
||||
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
|
||||
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
|
||||
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
|
||||
[drf-haystack]: https://drf-haystack.readthedocs.io/en/latest/
|
||||
[django-rest-framework-version-transforms]: https://github.com/mrhwick/django-rest-framework-version-transforms
|
||||
[djangorestframework-jsonapi]: https://github.com/django-json-api/django-rest-framework-json-api
|
||||
|
@ -237,3 +239,5 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[graphwrap]: https://github.com/PaulGilmartin/graph_wrap
|
||||
[rest-framework-actions]: https://github.com/AlexisMunera98/rest-framework-actions
|
||||
[fast-drf]: https://github.com/iashraful/fast-drf
|
||||
[django-requestlogs]: https://github.com/Raekkeri/django-requestlogs
|
||||
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors
|
||||
|
|
|
@ -1,5 +1,16 @@
|
|||
# Tutorial 7: Schemas & client libraries
|
||||
|
||||
----
|
||||
|
||||
**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details.
|
||||
|
||||
If you are looking for information regarding schemas, you might want to look at these updated resources:
|
||||
|
||||
1. [Schema](../api-guide/schemas.md)
|
||||
2. [Documenting your API](../topics/documenting-your-api.md)
|
||||
|
||||
----
|
||||
|
||||
A schema is a machine-readable document that describes the available API
|
||||
endpoints, their URLS, and what operations they support.
|
||||
|
||||
|
|
|
@ -1,6 +1,17 @@
|
|||
|
||||
## Built-in API documentation
|
||||
|
||||
----
|
||||
|
||||
**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details.
|
||||
|
||||
If you are looking for information regarding schemas, you might want to look at these updated resources:
|
||||
|
||||
1. [Schema](../api-guide/schemas.md)
|
||||
2. [Documenting your API](../topics/documenting-your-api.md)
|
||||
|
||||
----
|
||||
|
||||
The built-in API documentation includes:
|
||||
|
||||
* Documentation of API endpoints.
|
||||
|
@ -32,7 +43,7 @@ This will include two different views:
|
|||
**Note**: By default `include_docs_urls` configures the underlying `SchemaView` to generate _public_ schemas.
|
||||
This means that views will not be instantiated with a `request` instance. i.e. Inside the view `self.request` will be `None`.
|
||||
|
||||
To be compatible with this behaviour, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
|
||||
To be compatible with this behavior, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
|
||||
|
||||
You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:
|
||||
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
# Legacy CoreAPI Schemas Docs
|
||||
|
||||
Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation in Django REST Framework v3.10.
|
||||
Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10.
|
||||
|
||||
See the [Version 3.10 Release Announcement](/community/3.10-announcement.md) for more details.
|
||||
See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details.
|
||||
|
||||
----
|
||||
|
||||
|
|
|
@ -2,6 +2,14 @@ source: schemas.py
|
|||
|
||||
# Schemas
|
||||
|
||||
----
|
||||
|
||||
**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details.
|
||||
|
||||
You are probably looking for [this page](../api-guide/schemas.md) if you want latest information regarding schemas.
|
||||
|
||||
----
|
||||
|
||||
> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.
|
||||
>
|
||||
> — Heroku, [JSON Schema for the Heroku Platform API][cite]
|
||||
|
@ -390,7 +398,7 @@ then you can use the `SchemaGenerator` class directly to auto-generate the
|
|||
`Document` instance, and to return that from a view.
|
||||
|
||||
This option gives you the flexibility of setting up the schema endpoint
|
||||
with whatever behaviour you want. For example, you can apply different
|
||||
with whatever behavior you want. For example, you can apply different
|
||||
permission, throttling, or authentication policies to the schema endpoint.
|
||||
|
||||
Here's an example of using `SchemaGenerator` together with a view to
|
||||
|
@ -564,7 +572,7 @@ A class that deals with introspection of individual views for schema generation.
|
|||
|
||||
`AutoSchema` is attached to `APIView` via the `schema` attribute.
|
||||
|
||||
The `AutoSchema` constructor takes a single keyword argument `manual_fields`.
|
||||
The `AutoSchema` constructor takes a single keyword argument `manual_fields`.
|
||||
|
||||
**`manual_fields`**: a `list` of `coreapi.Field` instances that will be added to
|
||||
the generated fields. Generated fields with a matching `name` will be overwritten.
|
||||
|
@ -641,10 +649,10 @@ def get_manual_fields(self, path, method):
|
|||
"""Example adding per-method fields."""
|
||||
|
||||
extra_fields = []
|
||||
if method=='GET':
|
||||
extra_fields = # ... list of extra fields for GET ...
|
||||
if method=='POST':
|
||||
extra_fields = # ... list of extra fields for POST ...
|
||||
if method == 'GET':
|
||||
extra_fields = ... # list of extra fields for GET
|
||||
if method == 'POST':
|
||||
extra_fields = ... # list of extra fields for POST
|
||||
|
||||
manual_fields = super().get_manual_fields(path, method)
|
||||
return manual_fields + extra_fields
|
||||
|
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
BIN
docs/img/premium/cryptapi-readme.png
Normal file
After Width: | Height: | Size: 17 KiB |
BIN
docs/img/premium/fezto-readme.png
Normal file
After Width: | Height: | Size: 22 KiB |
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 4.8 KiB |
Before Width: | Height: | Size: 8.8 KiB After Width: | Height: | Size: 8.7 KiB |
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 24 KiB |
BIN
docs/img/premium/spacinov-readme.png
Normal file
After Width: | Height: | Size: 56 KiB |
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 19 KiB |
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 27 KiB |
|
@ -67,16 +67,17 @@ continued development by **[signing up for a paid plan][funding]**.
|
|||
|
||||
<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=drf&utm_medium=sponsorship&utm_content=developer" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
<li><a href="https://software.esg-usa.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/esg-new-logo.png)">ESG</a></li>
|
||||
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</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/posthog-130.png)">PostHog</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>
|
||||
</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=drf&utm_medium=sponsorship&utm_content=developer), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.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), and [bit.io](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship).*
|
||||
*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), and [FEZTO](https://www.fezto.xyz/?utm_source=DjangoRESTFramework).*
|
||||
|
||||
---
|
||||
|
||||
|
@ -84,8 +85,8 @@ continued development by **[signing up for a paid plan][funding]**.
|
|||
|
||||
REST framework requires the following:
|
||||
|
||||
* Python (3.5, 3.6, 3.7, 3.8, 3.9)
|
||||
* Django (2.2, 3.0, 3.1, 3.2)
|
||||
* Python (3.6, 3.7, 3.8, 3.9, 3.10)
|
||||
* Django (2.2, 3.0, 3.1, 3.2, 4.0, 4.1)
|
||||
|
||||
We **highly recommend** and only officially support the latest patch release of
|
||||
each Python and Django series.
|
||||
|
@ -187,15 +188,17 @@ Framework.
|
|||
|
||||
## Support
|
||||
|
||||
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.libera.chat`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
|
||||
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.libera.chat`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
|
||||
|
||||
For priority support please sign up for a [professional or premium sponsorship plan](https://fund.django-rest-framework.org/topics/funding/).
|
||||
|
||||
## Security
|
||||
|
||||
If you believe you’ve found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**.
|
||||
Security issues are handled under the supervision of the [Django security team](https://www.djangoproject.com/foundation/teams/#security-team).
|
||||
|
||||
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
**Please report security issues by emailing security@djangoproject.com**.
|
||||
|
||||
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
|
||||
## License
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
|
||||
>
|
||||
> — [Jeff Atwood][cite]
|
||||
> — [Jeff Atwood][cite]
|
||||
|
||||
## Javascript clients
|
||||
|
||||
|
@ -31,11 +31,11 @@ In order to make AJAX requests, you need to include CSRF token in the HTTP heade
|
|||
|
||||
The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.
|
||||
|
||||
[Otto Yiu][ottoyiu] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
|
||||
[Adam Johnson][adamchainz] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
|
||||
|
||||
[cite]: https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/
|
||||
[csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
|
||||
[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax
|
||||
[cors]: https://www.w3.org/TR/cors/
|
||||
[ottoyiu]: https://github.com/ottoyiu/
|
||||
[django-cors-headers]: https://github.com/ottoyiu/django-cors-headers/
|
||||
[adamchainz]: https://github.com/adamchainz
|
||||
[django-cors-headers]: https://github.com/adamchainz/django-cors-headers
|
||||
|
|
|
@ -230,7 +230,7 @@ started.
|
|||
In order to start working with an API, we first need a `Client` instance. The
|
||||
client holds any configuration around which codecs and transports are supported
|
||||
when interacting with an API, which allows you to provide for more advanced
|
||||
kinds of behaviour.
|
||||
kinds of behavior.
|
||||
|
||||
import coreapi
|
||||
client = coreapi.Client()
|
||||
|
|
|
@ -17,7 +17,7 @@ By default, the API will return the format specified by the headers, which in th
|
|||
|
||||
## Customizing
|
||||
|
||||
The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.3.5), making it easy to customize the look-and-feel.
|
||||
The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.4.1), making it easy to customize the look-and-feel.
|
||||
|
||||
To customize the default style, create a template called `rest_framework/api.html` that extends from `rest_framework/base.html`. For example:
|
||||
|
||||
|
@ -35,7 +35,7 @@ To replace the default theme, add a `bootstrap_theme` block to your `api.html` a
|
|||
<link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css">
|
||||
{% endblock %}
|
||||
|
||||
Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above.
|
||||
Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above. Make sure that the Bootstrap version of the new theme matches that of the default theme.
|
||||
|
||||
You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style.
|
||||
|
||||
|
@ -44,7 +44,7 @@ Full example:
|
|||
{% extends "rest_framework/base.html" %}
|
||||
|
||||
{% block bootstrap_theme %}
|
||||
<link rel="stylesheet" href="https://bootswatch.com/flatly/bootstrap.min.css" type="text/css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch@3.4.1/flatly/bootstrap.min.css" type="text/css">
|
||||
{% endblock %}
|
||||
|
||||
{% block bootstrap_navbar_variant %}{% endblock %}
|
||||
|
|
|
@ -207,14 +207,14 @@ Field templates can also use additional style properties, depending on their typ
|
|||
|
||||
The complete list of `base_template` options and their associated style options is listed below.
|
||||
|
||||
base_template | Valid field types | Additional style options
|
||||
----|----|----
|
||||
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
|
||||
textarea.html | `CharField` | rows, placeholder, hide_label
|
||||
select.html | `ChoiceField` or relational field types | hide_label
|
||||
radio.html | `ChoiceField` or relational field types | inline, hide_label
|
||||
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
|
||||
base_template | Valid field types | Additional style options
|
||||
-----------------------|-------------------------------------------------------------|-----------------------------------------------
|
||||
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
|
||||
textarea.html | `CharField` | rows, placeholder, hide_label
|
||||
select.html | `ChoiceField` or relational field types | hide_label
|
||||
radio.html | `ChoiceField` or relational field types | inline, hide_label
|
||||
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
|
||||
checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
|
||||
checkbox.html | `BooleanField` | hide_label
|
||||
fieldset.html | Nested serializer | hide_label
|
||||
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label
|
||||
checkbox.html | `BooleanField` | hide_label
|
||||
fieldset.html | Nested serializer | hide_label
|
||||
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label
|
||||
|
|
|
@ -17,9 +17,9 @@ You can change the default language by using the standard Django `LANGUAGE_CODE`
|
|||
|
||||
LANGUAGE_CODE = "es-es"
|
||||
|
||||
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE_CLASSES` setting:
|
||||
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE` setting:
|
||||
|
||||
MIDDLEWARE_CLASSES = [
|
||||
MIDDLEWARE = [
|
||||
...
|
||||
'django.middleware.locale.LocaleMiddleware'
|
||||
]
|
||||
|
@ -90,7 +90,7 @@ If you're only translating custom error messages that exist inside your project
|
|||
|
||||
## How the language is determined
|
||||
|
||||
If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE_CLASSES` setting.
|
||||
If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE` setting.
|
||||
|
||||
You can find more information on how the language preference is determined in the [Django documentation][django-language-preference]. For reference, the method is:
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@
|
|||
>
|
||||
> — Mike Amundsen, [REST fest 2012 keynote][cite].
|
||||
|
||||
First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
|
||||
First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to ensure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
|
||||
|
||||
If you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices.
|
||||
|
||||
|
|
|
@ -45,7 +45,7 @@ We'll need to add our new `snippets` app and the `rest_framework` app to `INSTAL
|
|||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
'snippets.apps.SnippetsConfig',
|
||||
'snippets',
|
||||
]
|
||||
|
||||
Okay, we're ready to roll.
|
||||
|
@ -77,7 +77,7 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni
|
|||
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
|
||||
python manage.py migrate snippets
|
||||
|
||||
## Creating a Serializer class
|
||||
|
||||
|
@ -179,7 +179,7 @@ We can also serialize querysets instead of model instances. To do so we simply
|
|||
|
||||
## Using ModelSerializers
|
||||
|
||||
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
|
||||
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
|
||||
|
||||
In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes.
|
||||
|
||||
|
@ -307,8 +307,8 @@ Quit out of the shell...
|
|||
Validating models...
|
||||
|
||||
0 errors found
|
||||
Django version 1.11, using settings 'tutorial.settings'
|
||||
Development server is running at http://127.0.0.1:8000/
|
||||
Django version 4.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.
|
||||
|
|
|
@ -29,7 +29,7 @@ REST framework provides two wrappers you can use to write API views.
|
|||
|
||||
These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
|
||||
|
||||
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
|
||||
The wrappers also provide behavior such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
|
||||
|
||||
## Pulling it all together
|
||||
|
||||
|
@ -112,7 +112,7 @@ Now update the `snippets/urls.py` file slightly, to append a set of `format_suff
|
|||
|
||||
urlpatterns = [
|
||||
path('snippets/', views.snippet_list),
|
||||
path('snippets/<int:pk>', views.snippet_detail),
|
||||
path('snippets/<int:pk>/', views.snippet_detail),
|
||||
]
|
||||
|
||||
urlpatterns = format_suffix_patterns(urlpatterns)
|
||||
|
|
|
@ -79,9 +79,9 @@ Okay, we're done. If you run the development server everything should be workin
|
|||
|
||||
## Using mixins
|
||||
|
||||
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behaviour.
|
||||
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behavior.
|
||||
|
||||
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.
|
||||
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behavior are implemented in REST framework's mixin classes.
|
||||
|
||||
Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again.
|
||||
|
||||
|
|
|
@ -38,7 +38,7 @@ And now we can add a `.save()` method to our model class:
|
|||
formatter = HtmlFormatter(style=self.style, linenos=linenos,
|
||||
full=True, **options)
|
||||
self.highlighted = highlight(self.code, lexer, formatter)
|
||||
super(Snippet, self).save(*args, **kwargs)
|
||||
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.
|
||||
|
|
|
@ -112,8 +112,8 @@ Here's our re-wired `snippets/urls.py` file.
|
|||
|
||||
# Create a router and register our viewsets with it.
|
||||
router = DefaultRouter()
|
||||
router.register(r'snippets', views.SnippetViewSet)
|
||||
router.register(r'users', views.UserViewSet)
|
||||
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 = [
|
||||
|
|
|
@ -42,6 +42,7 @@ The project layout should look like:
|
|||
./tutorial/quickstart/models.py
|
||||
./tutorial/quickstart/tests.py
|
||||
./tutorial/quickstart/views.py
|
||||
./tutorial/asgi.py
|
||||
./tutorial/settings.py
|
||||
./tutorial/urls.py
|
||||
./tutorial/wsgi.py
|
||||
|
@ -176,12 +177,6 @@ We can now access our API, both from the command-line, using tools like `curl`..
|
|||
"url": "http://127.0.0.1:8000/users/1/",
|
||||
"username": "admin"
|
||||
},
|
||||
{
|
||||
"email": "tom@example.com",
|
||||
"groups": [],
|
||||
"url": "http://127.0.0.1:8000/users/2/",
|
||||
"username": "tom"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
@ -202,12 +197,6 @@ Or using the [httpie][httpie], command line tool...
|
|||
"url": "http://localhost:8000/users/1/",
|
||||
"username": "paul"
|
||||
},
|
||||
{
|
||||
"email": "tom@example.com",
|
||||
"groups": [],
|
||||
"url": "http://127.0.0.1:8000/users/2/",
|
||||
"username": "tom"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
|
|
@ -66,6 +66,8 @@ nav:
|
|||
- 'Contributing to REST framework': 'community/contributing.md'
|
||||
- 'Project management': 'community/project-management.md'
|
||||
- 'Release Notes': 'community/release-notes.md'
|
||||
- '3.14 Announcement': 'community/3.14-announcement.md'
|
||||
- '3.13 Announcement': 'community/3.13-announcement.md'
|
||||
- '3.12 Announcement': 'community/3.12-announcement.md'
|
||||
- '3.11 Announcement': 'community/3.11-announcement.md'
|
||||
- '3.10 Announcement': 'community/3.10-announcement.md'
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
# The base set of requirements for REST framework is actually
|
||||
# just Django, but for the purposes of development and testing
|
||||
# there are a number of packages that are useful to install.
|
||||
# just Django and pytz, but for the purposes of development
|
||||
# and testing there are a number of packages that are useful
|
||||
# to install.
|
||||
|
||||
# Laying these out as separate requirements files, allows us to
|
||||
# only included the relevant sets when running tox, and ensures
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
# MkDocs to build our documentation.
|
||||
mkdocs>=1.1.2,<1.2
|
||||
jinja2>=2.10,<3.1.0 # contextfilter has been renamed
|
||||
|
|
|
@ -3,8 +3,7 @@ coreapi==2.3.1
|
|||
coreschema==0.0.4
|
||||
django-filter>=2.4.0,<3.0
|
||||
django-guardian>=2.4.0,<2.5
|
||||
markdown==3.3;python_version>="3.6"
|
||||
markdown==3.2.2;python_version=="3.5"
|
||||
markdown==3.3
|
||||
psycopg2-binary>=2.8.5,<2.9
|
||||
pygments>=2.7.1,<2.8
|
||||
pygments==2.12
|
||||
pyyaml>=5.3.1,<5.4
|
||||
|
|
|
@ -2,3 +2,4 @@
|
|||
pytest>=6.1,<7.0
|
||||
pytest-cov>=2.10.1,<3.0
|
||||
pytest-django>=4.1.0,<5.0
|
||||
importlib-metadata<5.0
|
||||
|
|
|
@ -10,7 +10,7 @@ ______ _____ _____ _____ __
|
|||
import django
|
||||
|
||||
__title__ = 'Django REST framework'
|
||||
__version__ = '3.12.4'
|
||||
__version__ = '3.14.0'
|
||||
__author__ = 'Tom Christie'
|
||||
__license__ = 'BSD 3-Clause'
|
||||
__copyright__ = 'Copyright 2011-2019 Encode OSS Ltd'
|
||||
|
@ -29,9 +29,5 @@ if django.VERSION < (3, 2):
|
|||
default_app_config = 'rest_framework.apps.RestFrameworkConfig'
|
||||
|
||||
|
||||
class RemovedInDRF313Warning(DeprecationWarning):
|
||||
pass
|
||||
|
||||
|
||||
class RemovedInDRF314Warning(PendingDeprecationWarning):
|
||||
class RemovedInDRF315Warning(DeprecationWarning):
|
||||
pass
|
||||
|
|
|
@ -2,6 +2,7 @@
|
|||
The `compat` module provides support for backwards compatibility with older
|
||||
versions of Django/Python, and compatibility wrappers around optional packages.
|
||||
"""
|
||||
import django
|
||||
from django.conf import settings
|
||||
from django.views.generic import View
|
||||
|
||||
|
@ -152,6 +153,30 @@ else:
|
|||
return False
|
||||
|
||||
|
||||
if django.VERSION >= (4, 2):
|
||||
# Django 4.2+: use the stock parse_header_parameters function
|
||||
# Note: Django 4.1 also has an implementation of parse_header_parameters
|
||||
# which is slightly different from the one in 4.2, it needs
|
||||
# the compatibility shim as well.
|
||||
from django.utils.http import parse_header_parameters
|
||||
else:
|
||||
# Django <= 4.1: create a compatibility shim for parse_header_parameters
|
||||
from django.http.multipartparser import parse_header
|
||||
|
||||
def parse_header_parameters(line):
|
||||
# parse_header works with bytes, but parse_header_parameters
|
||||
# works with strings. Call encode to convert the line to bytes.
|
||||
main_value_pair, params = parse_header(line.encode())
|
||||
return main_value_pair, {
|
||||
# parse_header will convert *some* values to string.
|
||||
# parse_header_parameters converts *all* values to string.
|
||||
# Make sure all values are converted by calling decode on
|
||||
# any remaining non-string values.
|
||||
k: v if isinstance(v, str) else v.decode()
|
||||
for k, v in params.items()
|
||||
}
|
||||
|
||||
|
||||
# `separators` argument to `json.dumps()` differs between 2.x and 3.x
|
||||
# See: https://bugs.python.org/issue22767
|
||||
SHORT_SEPARATORS = (',', ':')
|
||||
|
|
|
@ -142,7 +142,7 @@ def action(methods=None, detail=None, url_path=None, url_name=None, **kwargs):
|
|||
how the `@renderer_classes` etc. decorators work for function-
|
||||
based API views.
|
||||
"""
|
||||
methods = ['get'] if (methods is None) else methods
|
||||
methods = ['get'] if methods is None else methods
|
||||
methods = [method.lower() for method in methods]
|
||||
|
||||
assert detail is not None, (
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
"""
|
||||
Handled exceptions raised by REST framework.
|
||||
|
||||
In addition Django's built in 403 and 404 exceptions are handled.
|
||||
In addition, Django's built in 403 and 404 exceptions are handled.
|
||||
(`django.http.Http404` and `django.core.exceptions.PermissionDenied`)
|
||||
"""
|
||||
import math
|
||||
|
@ -72,16 +72,19 @@ class ErrorDetail(str):
|
|||
return self
|
||||
|
||||
def __eq__(self, other):
|
||||
r = super().__eq__(other)
|
||||
if r is NotImplemented:
|
||||
result = super().__eq__(other)
|
||||
if result is NotImplemented:
|
||||
return NotImplemented
|
||||
try:
|
||||
return r and self.code == other.code
|
||||
return result and self.code == other.code
|
||||
except AttributeError:
|
||||
return r
|
||||
return result
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self.__eq__(other)
|
||||
result = self.__eq__(other)
|
||||
if result is NotImplemented:
|
||||
return NotImplemented
|
||||
return not result
|
||||
|
||||
def __repr__(self):
|
||||
return 'ErrorDetail(string=%r, code=%r)' % (
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
import contextlib
|
||||
import copy
|
||||
import datetime
|
||||
import decimal
|
||||
|
@ -5,7 +6,6 @@ import functools
|
|||
import inspect
|
||||
import re
|
||||
import uuid
|
||||
import warnings
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Mapping
|
||||
|
||||
|
@ -27,13 +27,10 @@ from django.utils.duration import 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
|
||||
from django.utils.timezone import utc
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from pytz.exceptions import InvalidTimeError
|
||||
|
||||
from rest_framework import (
|
||||
ISO_8601, RemovedInDRF313Warning, RemovedInDRF314Warning
|
||||
)
|
||||
from rest_framework import ISO_8601
|
||||
from rest_framework.exceptions import ErrorDetail, ValidationError
|
||||
from rest_framework.settings import api_settings
|
||||
from rest_framework.utils import html, humanize_datetime, json, representation
|
||||
|
@ -63,6 +60,9 @@ def is_simple_callable(obj):
|
|||
"""
|
||||
True if the object is a callable that takes no arguments.
|
||||
"""
|
||||
if not callable(obj):
|
||||
return False
|
||||
|
||||
# Bail early since we cannot inspect built-in function signatures.
|
||||
if inspect.isbuiltin(obj):
|
||||
raise BuiltinSignatureError(
|
||||
|
@ -263,16 +263,6 @@ class CreateOnlyDefault:
|
|||
if is_update:
|
||||
raise SkipField()
|
||||
if callable(self.default):
|
||||
if hasattr(self.default, 'set_context'):
|
||||
warnings.warn(
|
||||
"Method `set_context` on defaults is deprecated and will "
|
||||
"no longer be called starting with 3.13. Instead set "
|
||||
"`requires_context = True` on the class, and accept the "
|
||||
"context as an additional argument.",
|
||||
RemovedInDRF313Warning, stacklevel=2
|
||||
)
|
||||
self.default.set_context(self)
|
||||
|
||||
if getattr(self.default, 'requires_context', False):
|
||||
return self.default(serializer_field)
|
||||
else:
|
||||
|
@ -502,16 +492,6 @@ class Field:
|
|||
# No default, or this is a partial update.
|
||||
raise SkipField()
|
||||
if callable(self.default):
|
||||
if hasattr(self.default, 'set_context'):
|
||||
warnings.warn(
|
||||
"Method `set_context` on defaults is deprecated and will "
|
||||
"no longer be called starting with 3.13. Instead set "
|
||||
"`requires_context = True` on the class, and accept the "
|
||||
"context as an additional argument.",
|
||||
RemovedInDRF313Warning, stacklevel=2
|
||||
)
|
||||
self.default.set_context(self)
|
||||
|
||||
if getattr(self.default, 'requires_context', False):
|
||||
return self.default(self)
|
||||
else:
|
||||
|
@ -576,16 +556,6 @@ class Field:
|
|||
"""
|
||||
errors = []
|
||||
for validator in self.validators:
|
||||
if hasattr(validator, 'set_context'):
|
||||
warnings.warn(
|
||||
"Method `set_context` on validators is deprecated and will "
|
||||
"no longer be called starting with 3.13. Instead set "
|
||||
"`requires_context = True` on the class, and accept the "
|
||||
"context as an additional argument.",
|
||||
RemovedInDRF313Warning, stacklevel=2
|
||||
)
|
||||
validator.set_context(self)
|
||||
|
||||
try:
|
||||
if getattr(validator, 'requires_context', False):
|
||||
validator(value, self)
|
||||
|
@ -727,15 +697,13 @@ class BooleanField(Field):
|
|||
super().__init__(**kwargs)
|
||||
|
||||
def to_internal_value(self, data):
|
||||
try:
|
||||
with contextlib.suppress(TypeError):
|
||||
if data in self.TRUE_VALUES:
|
||||
return True
|
||||
elif data in self.FALSE_VALUES:
|
||||
return False
|
||||
elif data in self.NULL_VALUES and self.allow_null:
|
||||
return None
|
||||
except TypeError: # Input is an unhashable type
|
||||
pass
|
||||
self.fail('invalid', input=data)
|
||||
|
||||
def to_representation(self, value):
|
||||
|
@ -748,23 +716,6 @@ class BooleanField(Field):
|
|||
return bool(value)
|
||||
|
||||
|
||||
class NullBooleanField(BooleanField):
|
||||
initial = None
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
warnings.warn(
|
||||
"The `NullBooleanField` is deprecated and will be removed starting "
|
||||
"with 3.14. Instead use the `BooleanField` field and set "
|
||||
"`allow_null=True` which does the same thing.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
|
||||
assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.'
|
||||
kwargs['allow_null'] = True
|
||||
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
# String types...
|
||||
|
||||
class CharField(Field):
|
||||
|
@ -1183,7 +1134,7 @@ class DateTimeField(Field):
|
|||
When `self.default_timezone` is `None`, always return naive datetimes.
|
||||
When `self.default_timezone` is not `None`, always return aware datetimes.
|
||||
"""
|
||||
field_timezone = getattr(self, 'timezone', self.default_timezone())
|
||||
field_timezone = self.timezone if hasattr(self, 'timezone') else self.default_timezone()
|
||||
|
||||
if field_timezone is not None:
|
||||
if timezone.is_aware(value):
|
||||
|
@ -1196,7 +1147,7 @@ class DateTimeField(Field):
|
|||
except InvalidTimeError:
|
||||
self.fail('make_aware', timezone=field_timezone)
|
||||
elif (field_timezone is None) and timezone.is_aware(value):
|
||||
return timezone.make_naive(value, utc)
|
||||
return timezone.make_naive(value, datetime.timezone.utc)
|
||||
return value
|
||||
|
||||
def default_timezone(self):
|
||||
|
@ -1212,19 +1163,14 @@ class DateTimeField(Field):
|
|||
return self.enforce_timezone(value)
|
||||
|
||||
for input_format in input_formats:
|
||||
if input_format.lower() == ISO_8601:
|
||||
try:
|
||||
with contextlib.suppress(ValueError, TypeError):
|
||||
if input_format.lower() == ISO_8601:
|
||||
parsed = parse_datetime(value)
|
||||
if parsed is not None:
|
||||
return self.enforce_timezone(parsed)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
parsed = self.datetime_parser(value, input_format)
|
||||
return self.enforce_timezone(parsed)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
parsed = self.datetime_parser(value, input_format)
|
||||
return self.enforce_timezone(parsed)
|
||||
|
||||
humanized_format = humanize_datetime.datetime_formats(input_formats)
|
||||
self.fail('invalid', format=humanized_format)
|
||||
|
@ -1497,6 +1443,8 @@ class MultipleChoiceField(ChoiceField):
|
|||
self.fail('empty')
|
||||
|
||||
return {
|
||||
# Arguments for super() are needed because of scoping inside
|
||||
# comprehensions.
|
||||
super(MultipleChoiceField, self).to_internal_value(item)
|
||||
for item in data
|
||||
}
|
||||
|
@ -1866,7 +1814,7 @@ class SerializerMethodField(Field):
|
|||
|
||||
For example:
|
||||
|
||||
class ExampleSerializer(self):
|
||||
class ExampleSerializer(Serializer):
|
||||
extra_info = SerializerMethodField()
|
||||
|
||||
def get_extra_info(self, obj):
|
||||
|
|
|
@ -26,6 +26,7 @@ class Command(BaseCommand):
|
|||
parser.add_argument('--urlconf', dest="urlconf", default=None, type=str)
|
||||
parser.add_argument('--generator_class', dest="generator_class", default=None, type=str)
|
||||
parser.add_argument('--file', dest="file", default=None, type=str)
|
||||
parser.add_argument('--api_version', dest="api_version", default='', type=str)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
if options['generator_class']:
|
||||
|
@ -37,6 +38,7 @@ class Command(BaseCommand):
|
|||
title=options['title'],
|
||||
description=options['description'],
|
||||
urlconf=options['urlconf'],
|
||||
version=options['api_version'],
|
||||
)
|
||||
schema = generator.get_schema(request=None, public=True)
|
||||
renderer = self.get_renderer(options['format'])
|
||||
|
|
|
@ -36,7 +36,6 @@ class SimpleMetadata(BaseMetadata):
|
|||
label_lookup = ClassLookupDict({
|
||||
serializers.Field: 'field',
|
||||
serializers.BooleanField: 'boolean',
|
||||
serializers.NullBooleanField: 'boolean',
|
||||
serializers.CharField: 'string',
|
||||
serializers.UUIDField: 'string',
|
||||
serializers.URLField: 'url',
|
||||
|
|
|
@ -4,7 +4,7 @@ incoming request. Typically this will be based on the request's Accept header.
|
|||
"""
|
||||
from django.http import Http404
|
||||
|
||||
from rest_framework import HTTP_HEADER_ENCODING, exceptions
|
||||
from rest_framework import exceptions
|
||||
from rest_framework.settings import api_settings
|
||||
from rest_framework.utils.mediatypes import (
|
||||
_MediaType, media_type_matches, order_by_precedence
|
||||
|
@ -64,9 +64,11 @@ class DefaultContentNegotiation(BaseContentNegotiation):
|
|||
# Accepted media type is 'application/json'
|
||||
full_media_type = ';'.join(
|
||||
(renderer.media_type,) +
|
||||
tuple('{}={}'.format(
|
||||
key, value.decode(HTTP_HEADER_ENCODING))
|
||||
for key, value in media_type_wrapper.params.items()))
|
||||
tuple(
|
||||
'{}={}'.format(key, value)
|
||||
for key, value in media_type_wrapper.params.items()
|
||||
)
|
||||
)
|
||||
return renderer, full_media_type
|
||||
else:
|
||||
# Eg client requests 'application/json; indent=8'
|
||||
|
|
|
@ -2,6 +2,8 @@
|
|||
Pagination serializers determine the structure of the output that should
|
||||
be used for paginated responses.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
from base64 import b64decode, b64encode
|
||||
from collections import OrderedDict, namedtuple
|
||||
from urllib import parse
|
||||
|
@ -257,15 +259,12 @@ class PageNumberPagination(BasePagination):
|
|||
|
||||
def get_page_size(self, request):
|
||||
if self.page_size_query_param:
|
||||
try:
|
||||
with contextlib.suppress(KeyError, ValueError):
|
||||
return _positive_int(
|
||||
request.query_params[self.page_size_query_param],
|
||||
strict=True,
|
||||
cutoff=self.max_page_size
|
||||
)
|
||||
except (KeyError, ValueError):
|
||||
pass
|
||||
|
||||
return self.page_size
|
||||
|
||||
def get_next_link(self):
|
||||
|
@ -430,15 +429,12 @@ class LimitOffsetPagination(BasePagination):
|
|||
|
||||
def get_limit(self, request):
|
||||
if self.limit_query_param:
|
||||
try:
|
||||
with contextlib.suppress(KeyError, ValueError):
|
||||
return _positive_int(
|
||||
request.query_params[self.limit_query_param],
|
||||
strict=True,
|
||||
cutoff=self.max_limit
|
||||
)
|
||||
except (KeyError, ValueError):
|
||||
pass
|
||||
|
||||
return self.default_limit
|
||||
|
||||
def get_offset(self, request):
|
||||
|
@ -680,15 +676,12 @@ class CursorPagination(BasePagination):
|
|||
|
||||
def get_page_size(self, request):
|
||||
if self.page_size_query_param:
|
||||
try:
|
||||
with contextlib.suppress(KeyError, ValueError):
|
||||
return _positive_int(
|
||||
request.query_params[self.page_size_query_param],
|
||||
strict=True,
|
||||
cutoff=self.max_page_size
|
||||
)
|
||||
except (KeyError, ValueError):
|
||||
pass
|
||||
|
||||
return self.page_size
|
||||
|
||||
def get_next_link(self):
|
||||
|
@ -905,10 +898,16 @@ class CursorPagination(BasePagination):
|
|||
'next': {
|
||||
'type': 'string',
|
||||
'nullable': True,
|
||||
'format': 'uri',
|
||||
'example': 'http://api.example.org/accounts/?{cursor_query_param}=cD00ODY%3D"'.format(
|
||||
cursor_query_param=self.cursor_query_param)
|
||||
},
|
||||
'previous': {
|
||||
'type': 'string',
|
||||
'nullable': True,
|
||||
'format': 'uri',
|
||||
'example': 'http://api.example.org/accounts/?{cursor_query_param}=cj0xJnA9NDg3'.format(
|
||||
cursor_query_param=self.cursor_query_param)
|
||||
},
|
||||
'results': schema,
|
||||
},
|
||||
|
@ -961,7 +960,7 @@ class CursorPagination(BasePagination):
|
|||
'in': 'query',
|
||||
'description': force_str(self.cursor_query_description),
|
||||
'schema': {
|
||||
'type': 'integer',
|
||||
'type': 'string',
|
||||
},
|
||||
}
|
||||
]
|
||||
|
|
|
@ -4,8 +4,9 @@ Parsers are used to parse the content of incoming HTTP requests.
|
|||
They give us a generic way of being able to handle various media types
|
||||
on the request, such as form content or json encoded data.
|
||||
"""
|
||||
|
||||
import codecs
|
||||
from urllib import parse
|
||||
import contextlib
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.files.uploadhandler import StopFutureHandlers
|
||||
|
@ -13,10 +14,10 @@ from django.http import QueryDict
|
|||
from django.http.multipartparser import ChunkIter
|
||||
from django.http.multipartparser import \
|
||||
MultiPartParser as DjangoMultiPartParser
|
||||
from django.http.multipartparser import MultiPartParserError, parse_header
|
||||
from django.utils.encoding import force_str
|
||||
from django.http.multipartparser import MultiPartParserError
|
||||
|
||||
from rest_framework import renderers
|
||||
from rest_framework.compat import parse_header_parameters
|
||||
from rest_framework.exceptions import ParseError
|
||||
from rest_framework.settings import api_settings
|
||||
from rest_framework.utils import json
|
||||
|
@ -194,30 +195,12 @@ class FileUploadParser(BaseParser):
|
|||
Detects the uploaded file name. First searches a 'filename' url kwarg.
|
||||
Then tries to parse Content-Disposition header.
|
||||
"""
|
||||
try:
|
||||
with contextlib.suppress(KeyError):
|
||||
return parser_context['kwargs']['filename']
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
try:
|
||||
with contextlib.suppress(AttributeError, KeyError, ValueError):
|
||||
meta = parser_context['request'].META
|
||||
disposition = parse_header(meta['HTTP_CONTENT_DISPOSITION'].encode())
|
||||
filename_parm = disposition[1]
|
||||
if 'filename*' in filename_parm:
|
||||
return self.get_encoded_filename(filename_parm)
|
||||
return force_str(filename_parm['filename'])
|
||||
except (AttributeError, KeyError, ValueError):
|
||||
pass
|
||||
|
||||
def get_encoded_filename(self, filename_parm):
|
||||
"""
|
||||
Handle encoded filenames per RFC6266. See also:
|
||||
https://tools.ietf.org/html/rfc2231#section-4
|
||||
"""
|
||||
encoded_filename = force_str(filename_parm['filename*'])
|
||||
try:
|
||||
charset, lang, filename = encoded_filename.split('\'', 2)
|
||||
filename = parse.unquote(filename)
|
||||
except (ValueError, LookupError):
|
||||
filename = force_str(filename_parm['filename'])
|
||||
return filename
|
||||
disposition, params = parse_header_parameters(meta['HTTP_CONTENT_DISPOSITION'])
|
||||
if 'filename*' in params:
|
||||
return params['filename*']
|
||||
return params['filename']
|
||||
|
|
|
@ -46,6 +46,14 @@ class OperandHolder(OperationHolderMixin):
|
|||
op2 = self.op2_class(*args, **kwargs)
|
||||
return self.operator_class(op1, op2)
|
||||
|
||||
def __eq__(self, other):
|
||||
return (
|
||||
isinstance(other, OperandHolder) and
|
||||
self.operator_class == other.operator_class and
|
||||
self.op1_class == other.op1_class and
|
||||
self.op2_class == other.op2_class
|
||||
)
|
||||
|
||||
|
||||
class AND:
|
||||
def __init__(self, op1, op2):
|
||||
|
@ -78,8 +86,11 @@ class OR:
|
|||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
return (
|
||||
self.op1.has_object_permission(request, view, obj) or
|
||||
self.op2.has_object_permission(request, view, obj)
|
||||
self.op1.has_permission(request, view)
|
||||
and self.op1.has_object_permission(request, view, obj)
|
||||
) or (
|
||||
self.op2.has_permission(request, view)
|
||||
and self.op2.has_object_permission(request, view, obj)
|
||||
)
|
||||
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
import contextlib
|
||||
import sys
|
||||
from collections import OrderedDict
|
||||
from urllib import parse
|
||||
|
@ -10,7 +11,7 @@ from django.utils.encoding import smart_str, uri_to_iri
|
|||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from rest_framework.fields import (
|
||||
Field, empty, get_attribute, is_simple_callable, iter_options
|
||||
Field, SkipField, empty, get_attribute, is_simple_callable, iter_options
|
||||
)
|
||||
from rest_framework.reverse import reverse
|
||||
from rest_framework.settings import api_settings
|
||||
|
@ -170,7 +171,7 @@ class RelatedField(Field):
|
|||
def get_attribute(self, instance):
|
||||
if self.use_pk_only_optimization() and self.source_attrs:
|
||||
# Optimized case, return a mock object only containing the pk attribute.
|
||||
try:
|
||||
with contextlib.suppress(AttributeError):
|
||||
attribute_instance = get_attribute(instance, self.source_attrs[:-1])
|
||||
value = attribute_instance.serializable_value(self.source_attrs[-1])
|
||||
if is_simple_callable(value):
|
||||
|
@ -183,9 +184,6 @@ class RelatedField(Field):
|
|||
value = getattr(value, 'pk', value)
|
||||
|
||||
return PKOnlyObject(pk=value)
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
# Standard case, return the object instance.
|
||||
return super().get_attribute(instance)
|
||||
|
||||
|
@ -535,7 +533,30 @@ class ManyRelatedField(Field):
|
|||
if hasattr(instance, 'pk') and instance.pk is None:
|
||||
return []
|
||||
|
||||
relationship = get_attribute(instance, self.source_attrs)
|
||||
try:
|
||||
relationship = get_attribute(instance, self.source_attrs)
|
||||
except (KeyError, AttributeError) as exc:
|
||||
if self.default is not empty:
|
||||
return self.get_default()
|
||||
if self.allow_null:
|
||||
return None
|
||||
if not self.required:
|
||||
raise SkipField()
|
||||
msg = (
|
||||
'Got {exc_type} when attempting to get a value for field '
|
||||
'`{field}` on serializer `{serializer}`.\nThe serializer '
|
||||
'field might be named incorrectly and not match '
|
||||
'any attribute or key on the `{instance}` instance.\n'
|
||||
'Original exception text was: {exc}.'.format(
|
||||
exc_type=type(exc).__name__,
|
||||
field=self.field_name,
|
||||
serializer=self.parent.__class__.__name__,
|
||||
instance=instance.__class__.__name__,
|
||||
exc=exc
|
||||
)
|
||||
)
|
||||
raise type(exc)(msg)
|
||||
|
||||
return relationship.all() if hasattr(relationship, 'all') else relationship
|
||||
|
||||
def to_representation(self, iterable):
|
||||
|
|
|
@ -6,7 +6,9 @@ on the response, such as JSON encoded data or HTML output.
|
|||
|
||||
REST framework also provides an HTML renderer that renders the browsable API.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import contextlib
|
||||
from collections import OrderedDict
|
||||
from urllib import parse
|
||||
|
||||
|
@ -14,7 +16,6 @@ from django import forms
|
|||
from django.conf import settings
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.core.paginator import Page
|
||||
from django.http.multipartparser import parse_header
|
||||
from django.template import engines, loader
|
||||
from django.urls import NoReverseMatch
|
||||
from django.utils.html import mark_safe
|
||||
|
@ -22,7 +23,7 @@ from django.utils.html import mark_safe
|
|||
from rest_framework import VERSION, exceptions, serializers, status
|
||||
from rest_framework.compat import (
|
||||
INDENT_SEPARATORS, LONG_SEPARATORS, SHORT_SEPARATORS, coreapi, coreschema,
|
||||
pygments_css, yaml
|
||||
parse_header_parameters, pygments_css, yaml
|
||||
)
|
||||
from rest_framework.exceptions import ParseError
|
||||
from rest_framework.request import is_form_media_type, override_method
|
||||
|
@ -72,12 +73,9 @@ class JSONRenderer(BaseRenderer):
|
|||
# If the media type looks like 'application/json; indent=4',
|
||||
# then pretty print the result.
|
||||
# Note that we coerce `indent=0` into `indent=None`.
|
||||
base_media_type, params = parse_header(accepted_media_type.encode('ascii'))
|
||||
try:
|
||||
base_media_type, params = parse_header_parameters(accepted_media_type)
|
||||
with contextlib.suppress(KeyError, ValueError, TypeError):
|
||||
return zero_as_none(max(min(int(params['indent']), 8), 0))
|
||||
except (KeyError, ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# If 'indent' is provided in the context, then pretty print the result.
|
||||
# E.g. If we're being called by the BrowsableAPIRenderer.
|
||||
return renderer_context.get('indent', None)
|
||||
|
@ -105,7 +103,7 @@ class JSONRenderer(BaseRenderer):
|
|||
|
||||
# We always fully escape \u2028 and \u2029 to ensure we output JSON
|
||||
# that is a strict javascript subset.
|
||||
# See: http://timelessrepo.com/json-isnt-a-javascript-subset
|
||||
# See: https://gist.github.com/damncabbage/623b879af56f850a6ddc
|
||||
ret = ret.replace('\u2028', '\\u2028').replace('\u2029', '\\u2029')
|
||||
return ret.encode()
|
||||
|
||||
|
@ -489,11 +487,8 @@ class BrowsableAPIRenderer(BaseRenderer):
|
|||
return
|
||||
|
||||
if existing_serializer is not None:
|
||||
try:
|
||||
with contextlib.suppress(TypeError):
|
||||
return self.render_form_for_serializer(existing_serializer)
|
||||
except TypeError:
|
||||
pass
|
||||
|
||||
if has_serializer:
|
||||
if method in ('PUT', 'PATCH'):
|
||||
serializer = view.get_serializer(instance=instance, **kwargs)
|
||||
|
@ -1035,13 +1030,16 @@ class CoreAPIJSONOpenAPIRenderer(_BaseOpenAPIRenderer):
|
|||
media_type = 'application/vnd.oai.openapi+json'
|
||||
charset = None
|
||||
format = 'openapi-json'
|
||||
ensure_ascii = not api_settings.UNICODE_JSON
|
||||
|
||||
def __init__(self):
|
||||
assert coreapi, 'Using CoreAPIJSONOpenAPIRenderer, but `coreapi` is not installed.'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
structure = self.get_structure(data)
|
||||
return json.dumps(structure, indent=4).encode('utf-8')
|
||||
return json.dumps(
|
||||
structure, indent=4,
|
||||
ensure_ascii=self.ensure_ascii).encode('utf-8')
|
||||
|
||||
|
||||
class OpenAPIRenderer(BaseRenderer):
|
||||
|
@ -1065,6 +1063,9 @@ class JSONOpenAPIRenderer(BaseRenderer):
|
|||
charset = None
|
||||
encoder_class = encoders.JSONEncoder
|
||||
format = 'openapi-json'
|
||||
ensure_ascii = not api_settings.UNICODE_JSON
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
return json.dumps(data, cls=self.encoder_class, indent=2).encode('utf-8')
|
||||
return json.dumps(
|
||||
data, cls=self.encoder_class, indent=2,
|
||||
ensure_ascii=self.ensure_ascii).encode('utf-8')
|
||||
|
|
|
@ -14,11 +14,11 @@ from contextlib import contextmanager
|
|||
|
||||
from django.conf import settings
|
||||
from django.http import HttpRequest, QueryDict
|
||||
from django.http.multipartparser import parse_header
|
||||
from django.http.request import RawPostDataException
|
||||
from django.utils.datastructures import MultiValueDict
|
||||
|
||||
from rest_framework import HTTP_HEADER_ENCODING, exceptions
|
||||
from rest_framework import exceptions
|
||||
from rest_framework.compat import parse_header_parameters
|
||||
from rest_framework.settings import api_settings
|
||||
|
||||
|
||||
|
@ -26,7 +26,7 @@ def is_form_media_type(media_type):
|
|||
"""
|
||||
Return True if the media type is a valid form media type.
|
||||
"""
|
||||
base_media_type, params = parse_header(media_type.encode(HTTP_HEADER_ENCODING))
|
||||
base_media_type, params = parse_header_parameters(media_type)
|
||||
return (base_media_type == 'application/x-www-form-urlencoded' or
|
||||
base_media_type == 'multipart/form-data')
|
||||
|
||||
|
@ -413,7 +413,8 @@ class Request:
|
|||
to proxy it to the underlying HttpRequest object.
|
||||
"""
|
||||
try:
|
||||
return getattr(self._request, attr)
|
||||
_request = self.__getattribute__("_request")
|
||||
return getattr(_request, attr)
|
||||
except AttributeError:
|
||||
return self.__getattribute__(attr)
|
||||
|
||||
|
|
|
@ -58,7 +58,7 @@ class LinkNode(OrderedDict):
|
|||
def __init__(self):
|
||||
self.links = []
|
||||
self.methods_counter = Counter()
|
||||
super(LinkNode, self).__init__()
|
||||
super().__init__()
|
||||
|
||||
def get_available_key(self, preferred_key):
|
||||
if preferred_key not in self:
|
||||
|
@ -120,7 +120,7 @@ class SchemaGenerator(BaseSchemaGenerator):
|
|||
assert coreapi, '`coreapi` must be installed for schema support.'
|
||||
assert coreschema, '`coreschema` must be installed for schema support.'
|
||||
|
||||
super(SchemaGenerator, self).__init__(title, url, description, patterns, urlconf)
|
||||
super().__init__(title, url, description, patterns, urlconf)
|
||||
self.coerce_method_names = api_settings.SCHEMA_COERCE_METHOD_NAMES
|
||||
|
||||
def get_links(self, request=None):
|
||||
|
@ -198,7 +198,11 @@ class SchemaGenerator(BaseSchemaGenerator):
|
|||
|
||||
if is_custom_action(action):
|
||||
# Custom action, eg "/users/{pk}/activate/", "/users/active/"
|
||||
if len(view.action_map) > 1:
|
||||
mapped_methods = {
|
||||
# Don't count head mapping, e.g. not part of the schema
|
||||
method for method in view.action_map if method != 'head'
|
||||
}
|
||||
if len(mapped_methods) > 1:
|
||||
action = self.default_mapping[method.lower()]
|
||||
if action in self.coerce_method_names:
|
||||
action = self.coerce_method_names[action]
|
||||
|
@ -346,7 +350,7 @@ class AutoSchema(ViewInspector):
|
|||
* `manual_fields`: list of `coreapi.Field` instances that
|
||||
will be added to auto-generated fields, overwriting on `Field.name`
|
||||
"""
|
||||
super(AutoSchema, self).__init__()
|
||||
super().__init__()
|
||||
if manual_fields is None:
|
||||
manual_fields = []
|
||||
self._manual_fields = manual_fields
|
||||
|
@ -587,7 +591,7 @@ class ManualSchema(ViewInspector):
|
|||
* `fields`: list of `coreapi.Field` instances.
|
||||
* `description`: String description for view. Optional.
|
||||
"""
|
||||
super(ManualSchema, self).__init__()
|
||||
super().__init__()
|
||||
assert all(isinstance(f, coreapi.Field) for f in fields), "`fields` must be a list of coreapi.Field instances"
|
||||
self._fields = fields
|
||||
self._description = description
|
||||
|
|
|
@ -88,7 +88,7 @@ class ViewInspector:
|
|||
view.get_view_description())
|
||||
|
||||
def _get_description_section(self, view, header, description):
|
||||
lines = [line for line in description.splitlines()]
|
||||
lines = description.splitlines()
|
||||
current_section = ''
|
||||
sections = {'': ''}
|
||||
|
||||
|
|
|
@ -13,7 +13,7 @@ from django.db import models
|
|||
from django.utils.encoding import force_str
|
||||
|
||||
from rest_framework import (
|
||||
RemovedInDRF314Warning, exceptions, renderers, serializers
|
||||
RemovedInDRF315Warning, exceptions, renderers, serializers
|
||||
)
|
||||
from rest_framework.compat import uritemplate
|
||||
from rest_framework.fields import _UnvalidatedField, empty
|
||||
|
@ -523,7 +523,7 @@ class AutoSchema(ViewInspector):
|
|||
continue
|
||||
|
||||
if field.required:
|
||||
required.append(field.field_name)
|
||||
required.append(self.get_field_name(field))
|
||||
|
||||
schema = self.map_field(field)
|
||||
if field.read_only:
|
||||
|
@ -538,7 +538,7 @@ class AutoSchema(ViewInspector):
|
|||
schema['description'] = str(field.help_text)
|
||||
self.map_field_validators(field, schema)
|
||||
|
||||
properties[field.field_name] = schema
|
||||
properties[self.get_field_name(field)] = schema
|
||||
|
||||
result = {
|
||||
'type': 'object',
|
||||
|
@ -589,6 +589,13 @@ class AutoSchema(ViewInspector):
|
|||
schema['maximum'] = int(digits * '9') + 1
|
||||
schema['minimum'] = -schema['maximum']
|
||||
|
||||
def get_field_name(self, field):
|
||||
"""
|
||||
Override this method if you want to change schema field name.
|
||||
For example, convert snake_case field name to camelCase.
|
||||
"""
|
||||
return field.field_name
|
||||
|
||||
def get_paginator(self):
|
||||
pagination_class = getattr(self.view, 'pagination_class', None)
|
||||
if pagination_class:
|
||||
|
@ -636,7 +643,7 @@ class AutoSchema(ViewInspector):
|
|||
"""
|
||||
return self.get_serializer(path, method)
|
||||
|
||||
def _get_reference(self, serializer):
|
||||
def get_reference(self, serializer):
|
||||
return {'$ref': '#/components/schemas/{}'.format(self.get_component_name(serializer))}
|
||||
|
||||
def get_request_body(self, path, method):
|
||||
|
@ -650,7 +657,7 @@ class AutoSchema(ViewInspector):
|
|||
if not isinstance(serializer, serializers.Serializer):
|
||||
item_schema = {}
|
||||
else:
|
||||
item_schema = self._get_reference(serializer)
|
||||
item_schema = self.get_reference(serializer)
|
||||
|
||||
return {
|
||||
'content': {
|
||||
|
@ -674,7 +681,7 @@ class AutoSchema(ViewInspector):
|
|||
if not isinstance(serializer, serializers.Serializer):
|
||||
item_schema = {}
|
||||
else:
|
||||
item_schema = self._get_reference(serializer)
|
||||
item_schema = self.get_reference(serializer)
|
||||
|
||||
if is_list_view(path, method, self.view):
|
||||
response_schema = {
|
||||
|
@ -713,98 +720,10 @@ class AutoSchema(ViewInspector):
|
|||
|
||||
return [path.split('/')[0].replace('_', '-')]
|
||||
|
||||
def _get_path_parameters(self, path, method):
|
||||
def _get_reference(self, serializer):
|
||||
warnings.warn(
|
||||
"Method `_get_path_parameters()` has been renamed to `get_path_parameters()`. "
|
||||
"The old name will be removed in DRF v3.14.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
"Method `_get_reference()` has been renamed to `get_reference()`. "
|
||||
"The old name will be removed in DRF v3.15.",
|
||||
RemovedInDRF315Warning, stacklevel=2
|
||||
)
|
||||
return self.get_path_parameters(path, method)
|
||||
|
||||
def _get_filter_parameters(self, path, method):
|
||||
warnings.warn(
|
||||
"Method `_get_filter_parameters()` has been renamed to `get_filter_parameters()`. "
|
||||
"The old name will be removed in DRF v3.14.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
return self.get_filter_parameters(path, method)
|
||||
|
||||
def _get_responses(self, path, method):
|
||||
warnings.warn(
|
||||
"Method `_get_responses()` has been renamed to `get_responses()`. "
|
||||
"The old name will be removed in DRF v3.14.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
return self.get_responses(path, method)
|
||||
|
||||
def _get_request_body(self, path, method):
|
||||
warnings.warn(
|
||||
"Method `_get_request_body()` has been renamed to `get_request_body()`. "
|
||||
"The old name will be removed in DRF v3.14.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
return self.get_request_body(path, method)
|
||||
|
||||
def _get_serializer(self, path, method):
|
||||
warnings.warn(
|
||||
"Method `_get_serializer()` has been renamed to `get_serializer()`. "
|
||||
"The old name will be removed in DRF v3.14.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
return self.get_serializer(path, method)
|
||||
|
||||
def _get_paginator(self):
|
||||
warnings.warn(
|
||||
"Method `_get_paginator()` has been renamed to `get_paginator()`. "
|
||||
"The old name will be removed in DRF v3.14.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
return self.get_paginator()
|
||||
|
||||
def _map_field_validators(self, field, schema):
|
||||
warnings.warn(
|
||||
"Method `_map_field_validators()` has been renamed to `map_field_validators()`. "
|
||||
"The old name will be removed in DRF v3.14.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
return self.map_field_validators(field, schema)
|
||||
|
||||
def _map_serializer(self, serializer):
|
||||
warnings.warn(
|
||||
"Method `_map_serializer()` has been renamed to `map_serializer()`. "
|
||||
"The old name will be removed in DRF v3.14.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
return self.map_serializer(serializer)
|
||||
|
||||
def _map_field(self, field):
|
||||
warnings.warn(
|
||||
"Method `_map_field()` has been renamed to `map_field()`. "
|
||||
"The old name will be removed in DRF v3.14.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
return self.map_field(field)
|
||||
|
||||
def _map_choicefield(self, field):
|
||||
warnings.warn(
|
||||
"Method `_map_choicefield()` has been renamed to `map_choicefield()`. "
|
||||
"The old name will be removed in DRF v3.14.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
return self.map_choicefield(field)
|
||||
|
||||
def _get_pagination_parameters(self, path, method):
|
||||
warnings.warn(
|
||||
"Method `_get_pagination_parameters()` has been renamed to `get_pagination_parameters()`. "
|
||||
"The old name will be removed in DRF v3.14.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
return self.get_pagination_parameters(path, method)
|
||||
|
||||
def _allows_filters(self, path, method):
|
||||
warnings.warn(
|
||||
"Method `_allows_filters()` has been renamed to `allows_filters()`. "
|
||||
"The old name will be removed in DRF v3.14.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
return self.allows_filters(path, method)
|
||||
return self.get_reference(serializer)
|
||||
|
|
|
@ -10,6 +10,8 @@ python primitives.
|
|||
2. The process of marshalling between python primitives and request and
|
||||
response content is handled by parsers and renderers.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import copy
|
||||
import inspect
|
||||
import traceback
|
||||
|
@ -52,7 +54,7 @@ from rest_framework.fields import ( # NOQA # isort:skip
|
|||
BooleanField, CharField, ChoiceField, DateField, DateTimeField, DecimalField,
|
||||
DictField, DurationField, EmailField, Field, FileField, FilePathField, FloatField,
|
||||
HiddenField, HStoreField, IPAddressField, ImageField, IntegerField, JSONField,
|
||||
ListField, ModelField, MultipleChoiceField, NullBooleanField, ReadOnlyField,
|
||||
ListField, ModelField, MultipleChoiceField, ReadOnlyField,
|
||||
RegexField, SerializerMethodField, SlugField, TimeField, URLField, UUIDField,
|
||||
)
|
||||
from rest_framework.relations import ( # NOQA # isort:skip
|
||||
|
@ -216,7 +218,7 @@ class BaseSerializer(Field):
|
|||
|
||||
return self.instance
|
||||
|
||||
def is_valid(self, raise_exception=False):
|
||||
def is_valid(self, *, raise_exception=False):
|
||||
assert hasattr(self, 'initial_data'), (
|
||||
'Cannot call `.is_valid()` as no `data=` keyword argument was '
|
||||
'passed when instantiating the serializer instance.'
|
||||
|
@ -735,7 +737,7 @@ class ListSerializer(BaseSerializer):
|
|||
|
||||
return self.instance
|
||||
|
||||
def is_valid(self, raise_exception=False):
|
||||
def is_valid(self, *, raise_exception=False):
|
||||
# This implementation is the same as the default,
|
||||
# except that we use lists, rather than dicts, as the empty case.
|
||||
assert hasattr(self, 'initial_data'), (
|
||||
|
@ -1496,12 +1498,10 @@ class ModelSerializer(Serializer):
|
|||
# they can't be nested attribute lookups.
|
||||
continue
|
||||
|
||||
try:
|
||||
with contextlib.suppress(FieldDoesNotExist):
|
||||
field = model._meta.get_field(source)
|
||||
if isinstance(field, DjangoModelField):
|
||||
model_fields[source] = field
|
||||
except FieldDoesNotExist:
|
||||
pass
|
||||
|
||||
return model_fields
|
||||
|
||||
|
|
|
@ -19,7 +19,9 @@ REST framework settings, checking for user settings first, then falling
|
|||
back to the defaults.
|
||||
"""
|
||||
from django.conf import settings
|
||||
from django.test.signals import setting_changed
|
||||
# Import from `django.core.signals` instead of the official location
|
||||
# `django.test.signals` to avoid importing the test module unnecessarily.
|
||||
from django.core.signals import setting_changed
|
||||
from django.utils.module_loading import import_string
|
||||
|
||||
from rest_framework import ISO_8601
|
||||
|
|
|
@ -131,13 +131,7 @@ $(function () {
|
|||
if (value !== undefined) {
|
||||
params[paramKey] = value
|
||||
}
|
||||
} else if (dataType === 'array' && paramValue) {
|
||||
try {
|
||||
params[paramKey] = JSON.parse(paramValue)
|
||||
} catch (err) {
|
||||
// Ignore malformed JSON
|
||||
}
|
||||
} else if (dataType === 'object' && paramValue) {
|
||||
} else if ((dataType === 'array' && paramValue) || (dataType === 'object' && paramValue)) {
|
||||
try {
|
||||
params[paramKey] = JSON.parse(paramValue)
|
||||
} catch (err) {
|
||||
|
|
|
@ -29,6 +29,8 @@ def is_server_error(code):
|
|||
|
||||
HTTP_100_CONTINUE = 100
|
||||
HTTP_101_SWITCHING_PROTOCOLS = 101
|
||||
HTTP_102_PROCESSING = 102
|
||||
HTTP_103_EARLY_HINTS = 103
|
||||
HTTP_200_OK = 200
|
||||
HTTP_201_CREATED = 201
|
||||
HTTP_202_ACCEPTED = 202
|
||||
|
@ -67,9 +69,11 @@ HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415
|
|||
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE = 416
|
||||
HTTP_417_EXPECTATION_FAILED = 417
|
||||
HTTP_418_IM_A_TEAPOT = 418
|
||||
HTTP_421_MISDIRECTED_REQUEST = 421
|
||||
HTTP_422_UNPROCESSABLE_ENTITY = 422
|
||||
HTTP_423_LOCKED = 423
|
||||
HTTP_424_FAILED_DEPENDENCY = 424
|
||||
HTTP_425_TOO_EARLY = 425
|
||||
HTTP_426_UPGRADE_REQUIRED = 426
|
||||
HTTP_428_PRECONDITION_REQUIRED = 428
|
||||
HTTP_429_TOO_MANY_REQUESTS = 429
|
||||
|
|
|
@ -218,7 +218,7 @@ def format_value(value):
|
|||
return template.render(context)
|
||||
elif isinstance(value, str):
|
||||
if (
|
||||
(value.startswith('http:') or value.startswith('https:')) and not
|
||||
(value.startswith('http:') or value.startswith('https:') or value.startswith('/')) and not
|
||||
re.search(r'\s', value)
|
||||
):
|
||||
return mark_safe('<a href="{value}">{value}</a>'.format(value=escape(value)))
|
||||
|
|
|
@ -277,7 +277,7 @@ class APIClient(APIRequestFactory, DjangoClient):
|
|||
"""
|
||||
self.handler._force_user = user
|
||||
self.handler._force_token = token
|
||||
if user is None:
|
||||
if user is None and token is None:
|
||||
self.logout() # Also clear any possible session info if required
|
||||
|
||||
def request(self, **kwargs):
|
||||
|
@ -288,7 +288,7 @@ class APIClient(APIRequestFactory, DjangoClient):
|
|||
def get(self, path, data=None, follow=False, **extra):
|
||||
response = super().get(path, data=data, **extra)
|
||||
if follow:
|
||||
response = self._handle_redirects(response, **extra)
|
||||
response = self._handle_redirects(response, data=data, **extra)
|
||||
return response
|
||||
|
||||
def post(self, path, data=None, format=None, content_type=None,
|
||||
|
@ -296,7 +296,7 @@ class APIClient(APIRequestFactory, DjangoClient):
|
|||
response = super().post(
|
||||
path, data=data, format=format, content_type=content_type, **extra)
|
||||
if follow:
|
||||
response = self._handle_redirects(response, **extra)
|
||||
response = self._handle_redirects(response, data=data, format=format, content_type=content_type, **extra)
|
||||
return response
|
||||
|
||||
def put(self, path, data=None, format=None, content_type=None,
|
||||
|
@ -304,7 +304,7 @@ class APIClient(APIRequestFactory, DjangoClient):
|
|||
response = super().put(
|
||||
path, data=data, format=format, content_type=content_type, **extra)
|
||||
if follow:
|
||||
response = self._handle_redirects(response, **extra)
|
||||
response = self._handle_redirects(response, data=data, format=format, content_type=content_type, **extra)
|
||||
return response
|
||||
|
||||
def patch(self, path, data=None, format=None, content_type=None,
|
||||
|
@ -312,7 +312,7 @@ class APIClient(APIRequestFactory, DjangoClient):
|
|||
response = super().patch(
|
||||
path, data=data, format=format, content_type=content_type, **extra)
|
||||
if follow:
|
||||
response = self._handle_redirects(response, **extra)
|
||||
response = self._handle_redirects(response, data=data, format=format, content_type=content_type, **extra)
|
||||
return response
|
||||
|
||||
def delete(self, path, data=None, format=None, content_type=None,
|
||||
|
@ -320,7 +320,7 @@ class APIClient(APIRequestFactory, DjangoClient):
|
|||
response = super().delete(
|
||||
path, data=data, format=format, content_type=content_type, **extra)
|
||||
if follow:
|
||||
response = self._handle_redirects(response, **extra)
|
||||
response = self._handle_redirects(response, data=data, format=format, content_type=content_type, **extra)
|
||||
return response
|
||||
|
||||
def options(self, path, data=None, format=None, content_type=None,
|
||||
|
@ -328,7 +328,7 @@ class APIClient(APIRequestFactory, DjangoClient):
|
|||
response = super().options(
|
||||
path, data=data, format=format, content_type=content_type, **extra)
|
||||
if follow:
|
||||
response = self._handle_redirects(response, **extra)
|
||||
response = self._handle_redirects(response, data=data, format=format, content_type=content_type, **extra)
|
||||
return response
|
||||
|
||||
def logout(self):
|
||||
|
|