Compare commits
No commits in common. "master" and "2.1.15" have entirely different histories.
2
.github/FUNDING.yml
vendored
|
@ -1,2 +0,0 @@
|
|||
github: encode
|
||||
custom: https://fund.django-rest-framework.org/topics/funding/
|
13
.github/dependabot.yml
vendored
|
@ -1,13 +0,0 @@
|
|||
# Keep GitHub Actions up to date with GitHub's Dependabot...
|
||||
# https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot
|
||||
# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
groups:
|
||||
github-actions:
|
||||
patterns:
|
||||
- "*" # Group all Action updates into a single larger pull request
|
||||
schedule:
|
||||
interval: weekly
|
22
.github/stale.yml
vendored
|
@ -1,22 +0,0 @@
|
|||
# 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
|
73
.github/workflows/main.yml
vendored
|
@ -1,73 +0,0 @@
|
|||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
tests:
|
||||
name: Python ${{ matrix.python-version }}
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
python-version:
|
||||
- '3.9'
|
||||
- '3.10'
|
||||
- '3.11'
|
||||
- '3.12'
|
||||
- '3.13'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: 'pip'
|
||||
cache-dependency-path: 'requirements/*.txt'
|
||||
|
||||
- name: Upgrade packaging tools
|
||||
run: python -m pip install --upgrade pip setuptools virtualenv wheel
|
||||
|
||||
- name: Install dependencies
|
||||
run: python -m pip install --upgrade tox
|
||||
|
||||
- name: Run tox targets for ${{ matrix.python-version }}
|
||||
run: tox run -f py$(echo ${{ matrix.python-version }} | tr -d . | cut -f 1 -d '-')
|
||||
|
||||
- name: Run extra tox targets
|
||||
if: ${{ matrix.python-version == '3.9' }}
|
||||
run: |
|
||||
tox -e base,dist,docs
|
||||
|
||||
- name: Upload coverage
|
||||
uses: codecov/codecov-action@v5
|
||||
with:
|
||||
env_vars: TOXENV,DJANGO
|
||||
|
||||
test-docs:
|
||||
name: Test documentation links
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.9'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements/requirements-documentation.txt
|
||||
|
||||
# Start mkdocs server and wait for it to be ready
|
||||
- run: mkdocs serve &
|
||||
- run: WAIT_TIME=0 && until nc -vzw 2 localhost 8000 || [ $WAIT_TIME -eq 5 ]; do sleep $(( WAIT_TIME++ )); done
|
||||
- run: if [ $WAIT_TIME == 5 ]; then echo cannot start mkdocs server on http://localhost:8000; exit 1; fi
|
||||
|
||||
- name: Check links
|
||||
continue-on-error: true
|
||||
run: pylinkvalidate.py -P http://localhost:8000/
|
||||
|
||||
- run: echo "Done"
|
22
.github/workflows/pre-commit.yml
vendored
|
@ -1,22 +0,0 @@
|
|||
name: pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.10"
|
||||
|
||||
- uses: pre-commit/action@v3.0.1
|
23
.gitignore
vendored
|
@ -2,19 +2,18 @@
|
|||
*.db
|
||||
*~
|
||||
.*
|
||||
*.py.bak
|
||||
|
||||
|
||||
/site/
|
||||
/htmlcov/
|
||||
/coverage/
|
||||
/build/
|
||||
/dist/
|
||||
/*.egg-info/
|
||||
/env/
|
||||
html/
|
||||
coverage/
|
||||
build/
|
||||
dist/
|
||||
*.egg-info/
|
||||
MANIFEST
|
||||
coverage.*
|
||||
|
||||
!.github
|
||||
bin/
|
||||
include/
|
||||
lib/
|
||||
local/
|
||||
|
||||
!.gitignore
|
||||
!.pre-commit-config.yaml
|
||||
!.travis.yml
|
||||
|
|
|
@ -1,39 +0,0 @@
|
|||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.5.0
|
||||
hooks:
|
||||
- id: check-added-large-files
|
||||
- id: check-case-conflict
|
||||
- id: check-json
|
||||
- id: check-merge-conflict
|
||||
- id: check-symlinks
|
||||
- id: check-toml
|
||||
- repo: https://github.com/pycqa/isort
|
||||
rev: 5.13.2
|
||||
hooks:
|
||||
- id: isort
|
||||
- repo: https://github.com/PyCQA/flake8
|
||||
rev: 7.0.0
|
||||
hooks:
|
||||
- id: flake8
|
||||
additional_dependencies:
|
||||
- flake8-tidy-imports
|
||||
- repo: https://github.com/adamchainz/blacken-docs
|
||||
rev: 1.16.0
|
||||
hooks:
|
||||
- id: blacken-docs
|
||||
exclude: ^(?!docs).*$
|
||||
additional_dependencies:
|
||||
- black==23.1.0
|
||||
- repo: https://github.com/codespell-project/codespell
|
||||
# Configuration for codespell is in .codespellrc
|
||||
rev: v2.2.6
|
||||
hooks:
|
||||
- id: codespell
|
||||
exclude: locale|kickstarter-announcement.md|coreapi-0.1.1.js
|
||||
|
||||
- repo: https://github.com/asottile/pyupgrade
|
||||
rev: v3.19.1
|
||||
hooks:
|
||||
- id: pyupgrade
|
||||
args: ["--py39-plus", "--keep-percent-format"]
|
18
.travis.yml
Normal file
|
@ -0,0 +1,18 @@
|
|||
language: python
|
||||
|
||||
python:
|
||||
- "2.6"
|
||||
- "2.7"
|
||||
|
||||
env:
|
||||
- DJANGO=https://github.com/django/django/zipball/master
|
||||
- DJANGO=django==1.4.3 --use-mirrors
|
||||
- DJANGO=django==1.3.5 --use-mirrors
|
||||
|
||||
install:
|
||||
- pip install $DJANGO
|
||||
- pip install django-filter==0.5.4 --use-mirrors
|
||||
- export PYTHONPATH=.
|
||||
|
||||
script:
|
||||
- python rest_framework/runtests/runtests.py
|
|
@ -1,9 +0,0 @@
|
|||
[main]
|
||||
host = https://www.transifex.com
|
||||
lang_map = sr@latin:sr_Latn, zh-Hans:zh_Hans, zh-Hant:zh_Hant
|
||||
|
||||
[django-rest-framework.djangopo]
|
||||
file_filter = rest_framework/locale/<lang>/LC_MESSAGES/django.po
|
||||
source_file = rest_framework/locale/en_US/LC_MESSAGES/django.po
|
||||
source_lang = en_US
|
||||
type = PO
|
|
@ -1,5 +0,0 @@
|
|||
# Contributing to REST framework
|
||||
|
||||
At this point in its lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes.
|
||||
|
||||
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.
|
29
LICENSE.md
|
@ -1,29 +0,0 @@
|
|||
# License
|
||||
|
||||
Copyright © 2011-present, [Encode OSS Ltd](https://www.encode.io/).
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
10
MANIFEST.in
|
@ -1,8 +1,2 @@
|
|||
include README.md
|
||||
include LICENSE.md
|
||||
recursive-include tests/ *
|
||||
recursive-include rest_framework/static *.js *.css *.map *.png *.ico *.eot *.svg *.ttf *.woff *.woff2
|
||||
recursive-include rest_framework/templates *.html schema.js
|
||||
recursive-include rest_framework/locale *.mo
|
||||
global-exclude __pycache__
|
||||
global-exclude *.py[co]
|
||||
recursive-include rest_framework/static *.js *.css *.png
|
||||
recursive-include rest_framework/templates *.txt *.html
|
||||
|
|
|
@ -1,5 +0,0 @@
|
|||
*Note*: Before submitting a code change, please review our [contributing guidelines](https://www.django-rest-framework.org/community/contributing/#pull-requests).
|
||||
|
||||
## Description
|
||||
|
||||
Please describe your pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue. When linking to an issue, please use `refs #...` in the description of the pull request.
|
394
README.md
|
@ -1,226 +1,288 @@
|
|||
# [Django REST framework][docs]
|
||||
# Django REST framework
|
||||
|
||||
[![build-status-image]][build-status]
|
||||
[![coverage-status-image]][codecov]
|
||||
[![pypi-version]][pypi]
|
||||
**A toolkit for building well-connected, self-describing web APIs.**
|
||||
|
||||
**Awesome web-browsable Web APIs.**
|
||||
**Author:** Tom Christie. [Follow me on Twitter][twitter].
|
||||
|
||||
Full documentation for the project is available at [https://www.django-rest-framework.org/][docs].
|
||||
**Support:** [REST framework discussion group][group].
|
||||
|
||||
[![build-status-image]][travis]
|
||||
|
||||
---
|
||||
|
||||
# Funding
|
||||
**Full documentation for REST framework is available on [http://django-rest-framework.org][docs].**
|
||||
|
||||
REST framework is a *collaboratively funded project*. If you use
|
||||
REST framework commercially we strongly encourage you to invest in its
|
||||
continued development by [signing up for a paid plan][funding].
|
||||
|
||||
The initial aim is to provide a single full-time position on REST framework.
|
||||
*Every single sign-up makes a significant impact towards making that possible.*
|
||||
|
||||
[![][sentry-img]][sentry-url]
|
||||
[![][stream-img]][stream-url]
|
||||
[![][spacinov-img]][spacinov-url]
|
||||
[![][retool-img]][retool-url]
|
||||
[![][bitio-img]][bitio-url]
|
||||
[![][posthog-img]][posthog-url]
|
||||
[![][cryptapi-img]][cryptapi-url]
|
||||
[![][fezto-img]][fezto-url]
|
||||
[![][svix-img]][svix-url]
|
||||
[![][zuplo-img]][zuplo-url]
|
||||
|
||||
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Spacinov][spacinov-url], [Retool][retool-url], [bit.io][bitio-url], [PostHog][posthog-url], [CryptAPI][cryptapi-url], [FEZTO][fezto-url], [Svix][svix-url], and [Zuplo][zuplo-url].
|
||||
Note that this is the 2.0 version of REST framework. If you are looking for earlier versions please see the [0.4.x branch][0.4] on GitHub.
|
||||
|
||||
---
|
||||
|
||||
# Overview
|
||||
|
||||
Django REST framework is a powerful and flexible toolkit for building Web APIs.
|
||||
Django REST framework is a lightweight library that makes it easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views.
|
||||
|
||||
Some reasons you might want to use REST framework:
|
||||
Web APIs built using REST framework are fully self-describing and web browseable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box.
|
||||
|
||||
* The Web browsable API is a huge usability win for your developers.
|
||||
* [Authentication policies][authentication] including optional packages for [OAuth1a][oauth1-section] and [OAuth2][oauth2-section].
|
||||
* [Serialization][serializers] that supports both [ORM][modelserializer-section] and [non-ORM][serializer-section] data sources.
|
||||
* Customizable all the way down - just use [regular function-based views][functionview-section] if you don't need the [more][generic-views] [powerful][viewsets] [features][routers].
|
||||
* [Extensive documentation][docs], and [great community support][group].
|
||||
If you are considering using REST framework for your API, we recommend reading the [REST framework 2 announcment][rest-framework-2-announcement] which gives a good overview of the framework and it's capabilities.
|
||||
|
||||
**Below**: *Screenshot from the browsable API*
|
||||
|
||||
![Screenshot][image]
|
||||
|
||||
----
|
||||
There is also a sandbox API you can use for testing purposes, [available here][sandbox].
|
||||
|
||||
# Requirements
|
||||
|
||||
* Python 3.9+
|
||||
* Django 4.2, 5.0, 5.1, 5.2
|
||||
* Python (2.6, 2.7)
|
||||
* Django (1.3, 1.4, 1.5)
|
||||
|
||||
We **highly recommend** and only officially support the latest patch release of
|
||||
each Python and Django series.
|
||||
**Optional:**
|
||||
|
||||
* [Markdown] - Markdown support for the self describing API.
|
||||
* [PyYAML] - YAML content type support.
|
||||
* [django-filter] - Filtering support.
|
||||
|
||||
# Installation
|
||||
|
||||
Install using `pip`...
|
||||
Install using `pip`, including any optional packages you want...
|
||||
|
||||
pip install djangorestframework
|
||||
pip install markdown # Markdown support for the browseable API.
|
||||
pip install pyyaml # YAML content-type support.
|
||||
pip install django-filter # Filtering support
|
||||
|
||||
...or clone the project from github.
|
||||
|
||||
git clone git@github.com:tomchristie/django-rest-framework.git
|
||||
cd django-rest-framework
|
||||
pip install -r requirements.txt
|
||||
pip install -r optionals.txt
|
||||
|
||||
Add `'rest_framework'` to your `INSTALLED_APPS` setting.
|
||||
```python
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
]
|
||||
```
|
||||
|
||||
# Example
|
||||
INSTALLED_APPS = (
|
||||
...
|
||||
'rest_framework',
|
||||
)
|
||||
|
||||
Let's take a look at a quick example of using REST framework to build a simple model-backed API for accessing users and groups.
|
||||
If you're intending to use the browseable API you'll probably also want to add REST framework's login and logout views. Add the following to your root `urls.py` file.
|
||||
|
||||
Startup up a new project like so...
|
||||
urlpatterns = patterns('',
|
||||
...
|
||||
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
||||
)
|
||||
|
||||
pip install django
|
||||
pip install djangorestframework
|
||||
django-admin startproject example .
|
||||
./manage.py migrate
|
||||
./manage.py createsuperuser
|
||||
Note that the URL path can be whatever you want, but you must include `'rest_framework.urls'` with the `'rest_framework'` namespace.
|
||||
|
||||
# Development
|
||||
|
||||
Now edit the `example/urls.py` module in your project:
|
||||
To build the docs.
|
||||
|
||||
```python
|
||||
from django.contrib.auth.models import User
|
||||
from django.urls import include, path
|
||||
from rest_framework import routers, serializers, viewsets
|
||||
./mkdocs.py
|
||||
|
||||
To run the tests.
|
||||
|
||||
# Serializers define the API representation.
|
||||
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ['url', 'username', 'email', 'is_staff']
|
||||
./rest_framework/runtests/runtests.py
|
||||
|
||||
# Changelog
|
||||
|
||||
# ViewSets define the view behavior.
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
### 2.1.15
|
||||
|
||||
**Date**: 3rd Jan 2013
|
||||
|
||||
# Routers provide a way of automatically determining the URL conf.
|
||||
router = routers.DefaultRouter()
|
||||
router.register(r'users', UserViewSet)
|
||||
* Added `PATCH` support.
|
||||
* Added `RetrieveUpdateAPIView`.
|
||||
* Relation changes are now persisted in `save` instead of in `.restore_object`.
|
||||
* Remove unused internal `save_m2m` flag on `ModelSerializer.save()`.
|
||||
* Tweak behavior of hyperlinked fields with an explicit format suffix.
|
||||
* Relation changes are now persisted in `.save()` instead of in `.restore_object()`.
|
||||
* Bugfix: Fix issue with FileField raising exception instead of validation error when files=None.
|
||||
* Bugfix: Partial updates should not set default values if field is not included.
|
||||
|
||||
# Wire up our API using automatic URL routing.
|
||||
# Additionally, we include login URLs for the browsable API.
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
|
||||
]
|
||||
```
|
||||
### 2.1.14
|
||||
|
||||
We'd also like to configure a couple of settings for our API.
|
||||
**Date**: 31st Dec 2012
|
||||
|
||||
Add the following to your `settings.py` module:
|
||||
* Bugfix: ModelSerializers now include reverse FK fields on creation.
|
||||
* Bugfix: Model fields with `blank=True` are now `required=False` by default.
|
||||
* Bugfix: Nested serializers now support nullable relationships.
|
||||
|
||||
```python
|
||||
INSTALLED_APPS = [
|
||||
... # Make sure to include the default installed apps here.
|
||||
'rest_framework',
|
||||
]
|
||||
**Note**: From 2.1.14 onwards, relational fields move out of the `fields.py` module and into the new `relations.py` module, in order to seperate them from regular data type fields, such as `CharField` and `IntegerField`.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
# Use Django's standard `django.contrib.auth` permissions,
|
||||
# or allow read-only access for unauthenticated users.
|
||||
'DEFAULT_PERMISSION_CLASSES': [
|
||||
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
|
||||
]
|
||||
}
|
||||
```
|
||||
This change will not affect user code, so long as it's following the recommended import style of `from rest_framework import serializers` and refering to fields using the style `serializers.PrimaryKeyRelatedField`.
|
||||
|
||||
That's it, we're done!
|
||||
### 2.1.13
|
||||
|
||||
./manage.py runserver
|
||||
**Date**: 28th Dec 2012
|
||||
|
||||
You can now open the API in your browser at `http://127.0.0.1:8000/`, and view your new 'users' API. If you use the `Login` control in the top right corner you'll also be able to add, create and delete users from the system.
|
||||
* Support configurable `STATICFILES_STORAGE` storage.
|
||||
* Bugfix: Related fields now respect the required flag, and may be required=False.
|
||||
|
||||
You can also interact with the API using command line tools such as [`curl`](https://curl.haxx.se/). For example, to list the users endpoint:
|
||||
### 2.1.12
|
||||
|
||||
$ curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
|
||||
[
|
||||
{
|
||||
"url": "http://127.0.0.1:8000/users/1/",
|
||||
"username": "admin",
|
||||
"email": "admin@example.com",
|
||||
"is_staff": true,
|
||||
}
|
||||
]
|
||||
**Date**: 21st Dec 2012
|
||||
|
||||
Or to create a new user:
|
||||
* Bugfix: Fix bug that could occur using ChoiceField.
|
||||
* Bugfix: Fix exception in browseable API on DELETE.
|
||||
* Bugfix: Fix issue where pk was was being set to a string if set by URL kwarg.
|
||||
|
||||
$ curl -X POST -d username=new -d email=new@example.com -d is_staff=false -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
|
||||
{
|
||||
"url": "http://127.0.0.1:8000/users/2/",
|
||||
"username": "new",
|
||||
"email": "new@example.com",
|
||||
"is_staff": false,
|
||||
}
|
||||
## 2.1.11
|
||||
|
||||
# Documentation & Support
|
||||
**Date**: 17th Dec 2012
|
||||
|
||||
Full documentation for the project is available at [https://www.django-rest-framework.org/][docs].
|
||||
* Bugfix: Fix issue with M2M fields in browseable API.
|
||||
|
||||
For questions and support, use the [REST framework discussion group][group], or `#restframework` on libera.chat IRC.
|
||||
## 2.1.10
|
||||
|
||||
# Security
|
||||
**Date**: 17th Dec 2012
|
||||
|
||||
Please see the [security policy][security-policy].
|
||||
* Bugfix: Ensure read-only fields don't have model validation applied.
|
||||
* Bugfix: Fix hyperlinked fields in paginated results.
|
||||
|
||||
[build-status-image]: https://github.com/encode/django-rest-framework/actions/workflows/main.yml/badge.svg
|
||||
[build-status]: https://github.com/encode/django-rest-framework/actions/workflows/main.yml
|
||||
[coverage-status-image]: https://img.shields.io/codecov/c/github/encode/django-rest-framework/master.svg
|
||||
[codecov]: https://codecov.io/github/encode/django-rest-framework?branch=master
|
||||
[pypi-version]: https://img.shields.io/pypi/v/djangorestframework.svg
|
||||
[pypi]: https://pypi.org/project/djangorestframework/
|
||||
## 2.1.9
|
||||
|
||||
**Date**: 11th Dec 2012
|
||||
|
||||
* Bugfix: Fix broken nested serialization.
|
||||
* Bugfix: Fix `Meta.fields` only working as tuple not as list.
|
||||
* Bugfix: Edge case if unnecessarily specifying `required=False` on read only field.
|
||||
|
||||
## 2.1.8
|
||||
|
||||
**Date**: 8th Dec 2012
|
||||
|
||||
* Fix for creating nullable Foreign Keys with `''` as well as `None`.
|
||||
* Added `null=<bool>` related field option.
|
||||
|
||||
## 2.1.7
|
||||
|
||||
**Date**: 7th Dec 2012
|
||||
|
||||
* Serializers now properly support nullable Foreign Keys.
|
||||
* Serializer validation now includes model field validation, such as uniqueness constraints.
|
||||
* Support 'true' and 'false' string values for BooleanField.
|
||||
* Added pickle support for serialized data.
|
||||
* Support `source='dotted.notation'` style for nested serializers.
|
||||
* Make `Request.user` settable.
|
||||
* Bugfix: Fix `RegexField` to work with `BrowsableAPIRenderer`
|
||||
|
||||
## 2.1.6
|
||||
|
||||
**Date**: 23rd Nov 2012
|
||||
|
||||
* Bugfix: Unfix DjangoModelPermissions. (I am a doofus.)
|
||||
|
||||
## 2.1.5
|
||||
|
||||
**Date**: 23rd Nov 2012
|
||||
|
||||
* Bugfix: Fix DjangoModelPermissions.
|
||||
|
||||
## 2.1.4
|
||||
|
||||
**Date**: 22nd Nov 2012
|
||||
|
||||
* Support for partial updates with serializers.
|
||||
* Added `RegexField`.
|
||||
* Added `SerializerMethodField`.
|
||||
* Serializer performance improvements.
|
||||
* Added `obtain_token_view` to get tokens when using `TokenAuthentication`.
|
||||
* Bugfix: Django 1.5 configurable user support for `TokenAuthentication`.
|
||||
|
||||
## 2.1.3
|
||||
|
||||
**Date**: 16th Nov 2012
|
||||
|
||||
* Added `FileField` and `ImageField`. For use with `MultiPartParser`.
|
||||
* Added `URLField` and `SlugField`.
|
||||
* Support for `read_only_fields` on `ModelSerializer` classes.
|
||||
* Support for clients overriding the pagination page sizes. Use the `PAGINATE_BY_PARAM` setting or set the `paginate_by_param` attribute on a generic view.
|
||||
* 201 Responses now return a 'Location' header.
|
||||
* Bugfix: Serializer fields now respect `max_length`.
|
||||
|
||||
## 2.1.2
|
||||
|
||||
**Date**: 9th Nov 2012
|
||||
|
||||
* **Filtering support.**
|
||||
* Bugfix: Support creation of objects with reverse M2M relations.
|
||||
|
||||
## 2.1.1
|
||||
|
||||
**Date**: 7th Nov 2012
|
||||
|
||||
* Support use of HTML exception templates. Eg. `403.html`
|
||||
* Hyperlinked fields take optional `slug_field`, `slug_url_kwarg` and `pk_url_kwarg` arguments.
|
||||
* Bugfix: Deal with optional trailing slashs properly when generating breadcrumbs.
|
||||
* Bugfix: Make textareas same width as other fields in browsable API.
|
||||
* Private API change: `.get_serializer` now uses same `instance` and `data` ordering as serializer initialization.
|
||||
|
||||
## 2.1.0
|
||||
|
||||
**Date**: 5th Nov 2012
|
||||
|
||||
**Warning**: Please read [this thread][2.1.0-notes] regarding the `instance` and `data` keyword args before updating to 2.1.0.
|
||||
|
||||
* **Serializer `instance` and `data` keyword args have their position swapped.**
|
||||
* `queryset` argument is now optional on writable model fields.
|
||||
* Hyperlinked related fields optionally take `slug_field` and `slug_field_kwarg` arguments.
|
||||
* Support Django's cache framework.
|
||||
* Minor field improvements. (Don't stringify dicts, more robust many-pk fields.)
|
||||
* Bugfixes (Support choice field in Browseable API)
|
||||
|
||||
## 2.0.2
|
||||
|
||||
**Date**: 2nd Nov 2012
|
||||
|
||||
* Fix issues with pk related fields in the browsable API.
|
||||
|
||||
## 2.0.1
|
||||
|
||||
**Date**: 1st Nov 2012
|
||||
|
||||
* Add support for relational fields in the browsable API.
|
||||
* Added SlugRelatedField and ManySlugRelatedField.
|
||||
* If PUT creates an instance return '201 Created', instead of '200 OK'.
|
||||
|
||||
## 2.0.0
|
||||
|
||||
**Date**: 30th Oct 2012
|
||||
|
||||
* Redesign of core components.
|
||||
* Fix **all of the things**.
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2011-2013, Tom Christie
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
Redistributions in binary form must reproduce the above copyright notice, this
|
||||
list of conditions and the following disclaimer in the documentation and/or
|
||||
other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
[build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master
|
||||
[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master
|
||||
[twitter]: https://twitter.com/_tomchristie
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X
|
||||
[sandbox]: http://restframework.herokuapp.com/
|
||||
[rest-framework-2-announcement]: http://django-rest-framework.org/topics/rest-framework-2-announcement.html
|
||||
[2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion
|
||||
|
||||
[funding]: https://fund.django-rest-framework.org/topics/funding/
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[docs]: http://django-rest-framework.org/
|
||||
[urlobject]: https://github.com/zacharyvoase/urlobject
|
||||
[markdown]: http://pypi.python.org/pypi/Markdown/
|
||||
[pyyaml]: http://pypi.python.org/pypi/PyYAML
|
||||
[django-filter]: https://github.com/alex/django-filter
|
||||
|
||||
[sentry-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/sentry-readme.png
|
||||
[stream-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/stream-readme.png
|
||||
[spacinov-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/spacinov-readme.png
|
||||
[retool-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/retool-readme.png
|
||||
[bitio-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/bitio-readme.png
|
||||
[posthog-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/posthog-readme.png
|
||||
[cryptapi-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cryptapi-readme.png
|
||||
[fezto-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/fezto-readme.png
|
||||
[svix-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/svix-premium.png
|
||||
[zuplo-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/zuplo-readme.png
|
||||
|
||||
[sentry-url]: https://getsentry.com/welcome/
|
||||
[stream-url]: https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage
|
||||
[spacinov-url]: https://www.spacinov.com/
|
||||
[retool-url]: https://retool.com/?utm_source=djangorest&utm_medium=sponsorship
|
||||
[bitio-url]: https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship
|
||||
[posthog-url]: https://posthog.com?utm_source=drf&utm_medium=sponsorship&utm_campaign=open-source-sponsorship
|
||||
[cryptapi-url]: https://cryptapi.io
|
||||
[fezto-url]: https://www.fezto.xyz/?utm_source=DjangoRESTFramework
|
||||
[svix-url]: https://www.svix.com/?utm_source=django-REST&utm_medium=sponsorship
|
||||
[zuplo-url]: https://zuplo.link/django-gh
|
||||
|
||||
[oauth1-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth
|
||||
[oauth2-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit
|
||||
[serializer-section]: https://www.django-rest-framework.org/api-guide/serializers/#serializers
|
||||
[modelserializer-section]: https://www.django-rest-framework.org/api-guide/serializers/#modelserializer
|
||||
[functionview-section]: https://www.django-rest-framework.org/api-guide/views/#function-based-views
|
||||
[generic-views]: https://www.django-rest-framework.org/api-guide/generic-views/
|
||||
[viewsets]: https://www.django-rest-framework.org/api-guide/viewsets/
|
||||
[routers]: https://www.django-rest-framework.org/api-guide/routers/
|
||||
[serializers]: https://www.django-rest-framework.org/api-guide/serializers/
|
||||
[authentication]: https://www.django-rest-framework.org/api-guide/authentication/
|
||||
[image]: https://www.django-rest-framework.org/img/quickstart.png
|
||||
|
||||
[docs]: https://www.django-rest-framework.org/
|
||||
[security-policy]: https://github.com/encode/django-rest-framework/security/policy
|
||||
|
|
|
@ -1,7 +0,0 @@
|
|||
# Security Policy
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
**Please report security issues by emailing security@encode.io**.
|
||||
|
||||
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
11
codecov.yml
|
@ -1,11 +0,0 @@
|
|||
coverage:
|
||||
precision: 2
|
||||
round: down
|
||||
range: "80...100"
|
||||
|
||||
status:
|
||||
project: yes
|
||||
patch: no
|
||||
changes: no
|
||||
|
||||
comment: off
|
|
@ -1 +0,0 @@
|
|||
www.django-rest-framework.org
|
|
@ -1,7 +1,4 @@
|
|||
---
|
||||
source:
|
||||
- authentication.py
|
||||
---
|
||||
<a class="github" href="authentication.py"></a>
|
||||
|
||||
# Authentication
|
||||
|
||||
|
@ -11,192 +8,102 @@ source:
|
|||
|
||||
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted.
|
||||
|
||||
REST framework provides several authentication schemes out of the box, and also allows you to implement custom schemes.
|
||||
REST framework provides a number of authentication policies out of the box, and also allows you to implement custom policies.
|
||||
|
||||
Authentication always runs at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.
|
||||
Authentication will run the first time either the `request.user` or `request.auth` properties are accessed, and determines how those properties are initialized.
|
||||
|
||||
The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class.
|
||||
|
||||
The `request.auth` property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.
|
||||
|
||||
---
|
||||
|
||||
**Note:** Don't forget that **authentication by itself won't allow or disallow an incoming request**, it simply identifies the credentials that the request was made with.
|
||||
|
||||
For information on how to set up the permission policies for your API please see the [permissions documentation][permission].
|
||||
|
||||
---
|
||||
|
||||
## How authentication is determined
|
||||
|
||||
The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set `request.user` and `request.auth` using the return value of the first class that successfully authenticates.
|
||||
The authentication policy is always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set `request.user` and `request.auth` using the return value of the first class that successfully authenticates.
|
||||
|
||||
If no class authenticates, `request.user` will be set to an instance of `django.contrib.auth.models.AnonymousUser`, and `request.auth` will be set to `None`.
|
||||
|
||||
The value of `request.user` and `request.auth` for unauthenticated requests can be modified using the `UNAUTHENTICATED_USER` and `UNAUTHENTICATED_TOKEN` settings.
|
||||
|
||||
## Setting the authentication scheme
|
||||
## Setting the authentication policy
|
||||
|
||||
The default authentication schemes may be set globally, using the `DEFAULT_AUTHENTICATION_CLASSES` setting. For example.
|
||||
The default authentication policy may be set globally, using the `DEFAULT_AUTHENTICATION_CLASSES` setting. For example.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': [
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': (
|
||||
'rest_framework.authentication.BasicAuthentication',
|
||||
'rest_framework.authentication.SessionAuthentication',
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
You can also set the authentication scheme on a per-view or per-viewset basis,
|
||||
using the `APIView` class-based views.
|
||||
|
||||
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
|
||||
|
||||
class ExampleView(APIView):
|
||||
authentication_classes = [SessionAuthentication, BasicAuthentication]
|
||||
permission_classes = [IsAuthenticated]
|
||||
authentication_classes = (SessionAuthentication, BasicAuthentication)
|
||||
permission_classes = (IsAuthenticated,)
|
||||
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
'user': str(request.user), # `django.contrib.auth.User` instance.
|
||||
'auth': str(request.auth), # None
|
||||
'user': unicode(request.user), # `django.contrib.auth.User` instance.
|
||||
'auth': unicode(request.auth), # None
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
|
||||
@api_view(['GET'])
|
||||
@authentication_classes([SessionAuthentication, BasicAuthentication])
|
||||
@permission_classes([IsAuthenticated])
|
||||
@authentication_classes((SessionAuthentication, BasicAuthentication))
|
||||
@permissions_classes((IsAuthenticated,))
|
||||
def example_view(request, format=None):
|
||||
content = {
|
||||
'user': str(request.user), # `django.contrib.auth.User` instance.
|
||||
'auth': str(request.auth), # None
|
||||
'user': unicode(request.user), # `django.contrib.auth.User` instance.
|
||||
'auth': unicode(request.auth), # None
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
## Unauthorized and Forbidden responses
|
||||
|
||||
When an unauthenticated request is denied permission there are two different error codes that may be appropriate.
|
||||
|
||||
* [HTTP 401 Unauthorized][http401]
|
||||
* [HTTP 403 Permission Denied][http403]
|
||||
|
||||
HTTP 401 responses must always include a `WWW-Authenticate` header, that instructs the client how to authenticate. HTTP 403 responses do not include the `WWW-Authenticate` header.
|
||||
|
||||
The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. **The first authentication class set on the view is used when determining the type of response**.
|
||||
|
||||
Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a `403 Permission Denied` response will always be used, regardless of the authentication scheme.
|
||||
|
||||
## Django 5.1+ `LoginRequiredMiddleware`
|
||||
|
||||
If you're running Django 5.1+ and use the [`LoginRequiredMiddleware`][login-required-middleware], please note that all views from DRF are opted-out of this middleware. This is because the authentication in DRF is based authentication and permissions classes, which may be determined after the middleware has been applied. Additionally, when the request is not authenticated, the middleware redirects the user to the login page, which is not suitable for API requests, where it's preferable to return a 401 status code.
|
||||
|
||||
REST framework offers an equivalent mechanism for DRF views via the global settings, `DEFAULT_AUTHENTICATION_CLASSES` and `DEFAULT_PERMISSION_CLASSES`. They should be changed accordingly if you need to enforce that API requests are logged in.
|
||||
|
||||
## Apache mod_wsgi specific configuration
|
||||
|
||||
Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.
|
||||
|
||||
If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the `WSGIPassAuthorization` directive in the appropriate context and setting it to `'On'`.
|
||||
|
||||
# this can go in either server config, virtual host, directory or .htaccess
|
||||
WSGIPassAuthorization On
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## BasicAuthentication
|
||||
|
||||
This authentication scheme uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
|
||||
This policy uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
|
||||
|
||||
If successfully authenticated, `BasicAuthentication` provides the following credentials.
|
||||
|
||||
* `request.user` will be a Django `User` instance.
|
||||
* `request.auth` will be `None`.
|
||||
|
||||
Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
|
||||
|
||||
WWW-Authenticate: Basic realm="api"
|
||||
|
||||
**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https`. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
|
||||
**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https` only. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
|
||||
|
||||
## TokenAuthentication
|
||||
|
||||
---
|
||||
This policy uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
|
||||
|
||||
**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:
|
||||
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework.authtoken'
|
||||
]
|
||||
|
||||
Make sure to run `manage.py migrate` after changing your settings.
|
||||
|
||||
The `rest_framework.authtoken` app provides Django database migrations.
|
||||
To use the `TokenAuthentication` policy, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting.
|
||||
|
||||
You'll also need to create tokens for your users.
|
||||
|
||||
from rest_framework.authtoken.models import Token
|
||||
|
||||
token = Token.objects.create(user=...)
|
||||
print(token.key)
|
||||
print token.key
|
||||
|
||||
For clients to authenticate, the token key should be included in the `Authorization` HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example:
|
||||
|
||||
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
|
||||
|
||||
*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.
|
||||
|
||||
* `request.user` will be a Django `User` instance.
|
||||
* `request.auth` will be a `rest_framework.authtoken.models.Token` instance.
|
||||
* `request.auth` will be a `rest_framework.tokenauth.models.BasicToken` instance.
|
||||
|
||||
Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
|
||||
|
||||
WWW-Authenticate: Token
|
||||
|
||||
The `curl` command line tool may be useful for testing token authenticated APIs. For example:
|
||||
|
||||
curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
|
||||
|
||||
---
|
||||
|
||||
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https`.
|
||||
|
||||
---
|
||||
|
||||
### Generating Tokens
|
||||
|
||||
#### By using signals
|
||||
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
|
||||
|
||||
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
|
||||
|
||||
from django.conf import settings
|
||||
from django.db.models.signals import post_save
|
||||
from django.dispatch import receiver
|
||||
from rest_framework.authtoken.models import Token
|
||||
|
||||
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
|
||||
@receiver(post_save, sender=User)
|
||||
def create_auth_token(sender, instance=None, created=False, **kwargs):
|
||||
if created:
|
||||
Token.objects.create(user=instance)
|
||||
|
||||
Note that you'll want to ensure you place this code snippet in an installed `models.py` module, or some other location that will be imported by Django on startup.
|
||||
|
||||
If you've already created some users, you can generate tokens for all existing users like this:
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
|
@ -205,14 +112,12 @@ 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
|
||||
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:
|
||||
|
||||
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 += [
|
||||
path('api-token-auth/', views.obtain_auth_token)
|
||||
]
|
||||
urlpatterns += patterns('',
|
||||
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')
|
||||
)
|
||||
|
||||
Note that the URL part of the pattern can be whatever you want to use.
|
||||
|
||||
|
@ -220,281 +125,32 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
|
|||
|
||||
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
|
||||
|
||||
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.
|
||||
<!--
|
||||
## OAuthAuthentication
|
||||
|
||||
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.
|
||||
This policy uses the [OAuth 2.0][oauth] protocol to authenticate requests. OAuth is appropriate for server-server setups, such as when you want to allow a third-party service to access your API on a user's behalf.
|
||||
|
||||
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.
|
||||
|
||||
For example, you may return additional user information beyond the `token` value:
|
||||
|
||||
from rest_framework.authtoken.views import ObtainAuthToken
|
||||
from rest_framework.authtoken.models import Token
|
||||
from rest_framework.response import Response
|
||||
|
||||
class CustomAuthToken(ObtainAuthToken):
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
serializer = self.serializer_class(data=request.data,
|
||||
context={'request': request})
|
||||
serializer.is_valid(raise_exception=True)
|
||||
user = serializer.validated_data['user']
|
||||
token, created = Token.objects.get_or_create(user=user)
|
||||
return Response({
|
||||
'token': token.key,
|
||||
'user_id': user.pk,
|
||||
'email': user.email
|
||||
})
|
||||
|
||||
And in your `urls.py`:
|
||||
|
||||
urlpatterns += [
|
||||
path('api-token-auth/', CustomAuthToken.as_view())
|
||||
]
|
||||
|
||||
|
||||
#### 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 to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
||||
|
||||
`your_app/admin.py`:
|
||||
|
||||
from rest_framework.authtoken.admin import TokenAdmin
|
||||
|
||||
TokenAdmin.raw_id_fields = ['user']
|
||||
|
||||
|
||||
#### Using Django manage.py command
|
||||
|
||||
Since version 3.6.4 it's possible to generate a user token using the following command:
|
||||
|
||||
./manage.py drf_create_token <username>
|
||||
|
||||
this command will return the API token for the given user, creating it if it doesn't exist:
|
||||
|
||||
Generated token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b for user user1
|
||||
|
||||
In case you want to regenerate the token (for example if it has been compromised or leaked) you can pass an additional parameter:
|
||||
|
||||
./manage.py drf_create_token -r <username>
|
||||
If successfully authenticated, `OAuthAuthentication` provides the following credentials.
|
||||
|
||||
* `request.user` will be a Django `User` instance.
|
||||
* `request.auth` will be a `rest_framework.models.OAuthToken` instance.
|
||||
-->
|
||||
|
||||
## SessionAuthentication
|
||||
|
||||
This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
|
||||
This policy uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
|
||||
|
||||
If successfully authenticated, `SessionAuthentication` provides the following credentials.
|
||||
|
||||
* `request.user` will be a Django `User` instance.
|
||||
* `request.auth` will be `None`.
|
||||
|
||||
Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response.
|
||||
|
||||
If you're using an AJAX-style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
|
||||
|
||||
**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
|
||||
|
||||
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
|
||||
|
||||
This authentication scheme allows you to delegate authentication to your web server, which sets the `REMOTE_USER`
|
||||
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 behavior, consult the
|
||||
[Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/).
|
||||
|
||||
If successfully authenticated, `RemoteUserAuthentication` provides the following credentials:
|
||||
|
||||
* `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, 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/)
|
||||
|
||||
|
||||
# Custom authentication
|
||||
|
||||
To implement a custom authentication scheme, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
|
||||
To implement a custom authentication policy, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
|
||||
|
||||
In some circumstances instead of returning `None`, you may want to raise an `AuthenticationFailed` exception from the `.authenticate()` method.
|
||||
|
||||
Typically the approach you should take is:
|
||||
|
||||
* If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked.
|
||||
* If authentication is attempted but fails, raise an `AuthenticationFailed` exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.
|
||||
|
||||
You *may* also override the `.authenticate_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
|
||||
|
||||
If the `.authenticate_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access.
|
||||
|
||||
---
|
||||
|
||||
**Note:** When your custom authenticator is invoked by the request object's `.user` or `.auth` properties, you may see an `AttributeError` re-raised as a `WrappedAttributeError`. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from your custom authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. These errors should be fixed or otherwise handled by your authenticator.
|
||||
|
||||
---
|
||||
|
||||
## Example
|
||||
|
||||
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 rest_framework import authentication
|
||||
from rest_framework import exceptions
|
||||
|
||||
class ExampleAuthentication(authentication.BaseAuthentication):
|
||||
def authenticate(self, request):
|
||||
username = request.META.get('HTTP_X_USERNAME')
|
||||
if not username:
|
||||
return None
|
||||
|
||||
try:
|
||||
user = User.objects.get(username=username)
|
||||
except User.DoesNotExist:
|
||||
raise exceptions.AuthenticationFailed('No such user')
|
||||
|
||||
return (user, None)
|
||||
|
||||
---
|
||||
|
||||
# Third party packages
|
||||
|
||||
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
|
||||
|
||||
Install using `pip`.
|
||||
|
||||
pip install django-oauth-toolkit
|
||||
|
||||
Add the package to your `INSTALLED_APPS` and modify your REST framework settings.
|
||||
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'oauth2_provider',
|
||||
]
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': [
|
||||
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
|
||||
]
|
||||
}
|
||||
|
||||
For more details see the [Django REST framework - Getting started][django-oauth-toolkit-getting-started] documentation.
|
||||
|
||||
## Django REST framework OAuth
|
||||
|
||||
The [Django REST framework OAuth][django-rest-framework-oauth] package provides both OAuth1 and OAuth2 support for REST framework.
|
||||
|
||||
This package was previously included directly in the REST framework but is now supported and maintained as a third-party package.
|
||||
|
||||
### Installation & configuration
|
||||
|
||||
Install the package using `pip`.
|
||||
|
||||
pip install djangorestframework-oauth
|
||||
|
||||
For details on configuration and usage see the Django REST framework OAuth documentation for [authentication][django-rest-framework-oauth-authentication] and [permissions][django-rest-framework-oauth-permissions].
|
||||
|
||||
## JSON Web Token Authentication
|
||||
|
||||
JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. A package for JWT authentication is [djangorestframework-simplejwt][djangorestframework-simplejwt] which provides some features as well as a pluggable token blacklist app.
|
||||
|
||||
## Hawk HTTP Authentication
|
||||
|
||||
The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let you work with [Hawk][hawk] signed requests and responses in your API. [Hawk][hawk] lets two parties securely communicate with each other using messages signed by a shared key. It is based on [HTTP MAC access authentication][mac] (which was based on parts of [OAuth 1.0][oauth-1.0a]).
|
||||
|
||||
## HTTP Signature Authentication
|
||||
|
||||
HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] (outdated) package which provides an easy-to-use HTTP Signature Authentication mechanism. You can use the updated fork version of [djangorestframework-httpsignature][djangorestframework-httpsignature], which is [drf-httpsig][drf-httpsig].
|
||||
|
||||
## 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 a ready to use REST implementation of the Django authentication system.
|
||||
|
||||
## django-rest-auth / dj-rest-auth
|
||||
|
||||
This library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.
|
||||
|
||||
|
||||
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.
|
||||
|
||||
## drf-social-oauth2
|
||||
|
||||
[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
|
||||
|
||||
[drfpasswordless][drfpasswordless] adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.
|
||||
|
||||
## django-rest-authemail
|
||||
|
||||
[django-rest-authemail][django-rest-authemail] provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully functional example project and detailed instructions are included.
|
||||
|
||||
## Django-Rest-Durin
|
||||
|
||||
[Django-Rest-Durin][django-rest-durin] is built with the idea to have one library that does token auth for multiple Web/CLI/Mobile API clients via one interface but allows different token configuration for each API Client that consumes the API. It provides support for multiple tokens per user via custom models, views, permissions that work with Django-Rest-Framework. The token expiration time can be different per API client and is customizable via the Django Admin Interface.
|
||||
|
||||
More information can be found in the [Documentation](https://django-rest-durin.readthedocs.io/en/latest/index.html).
|
||||
|
||||
## django-pyoidc
|
||||
|
||||
[dango-pyoidc][django_pyoidc] adds support for OpenID Connect (OIDC) authentication. This allows you to delegate user management to an Identity Provider, which can be used to implement Single-Sign-On (SSO). It provides support for most uses-cases, such as customizing how token info are mapped to user models, using OIDC audiences for access control, etc.
|
||||
|
||||
More information can be found in the [Documentation](https://django-pyoidc.readthedocs.io/latest/index.html).
|
||||
|
||||
[cite]: https://jacobian.org/writing/rest-worst-practices/
|
||||
[http401]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
|
||||
[http403]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4
|
||||
[basicauth]: https://tools.ietf.org/html/rfc2617
|
||||
[cite]: http://jacobian.org/writing/rest-worst-practices/
|
||||
[basicauth]: http://tools.ietf.org/html/rfc2617
|
||||
[oauth]: http://oauth.net/2/
|
||||
[permission]: permissions.md
|
||||
[throttling]: throttling.md
|
||||
[csrf-ajax]: https://docs.djangoproject.com/en/stable/howto/csrf/#using-csrf-protection-with-ajax
|
||||
[mod_wsgi_official]: https://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGIPassAuthorization.html
|
||||
[django-oauth-toolkit-getting-started]: https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html
|
||||
[django-rest-framework-oauth]: https://jpadilla.github.io/django-rest-framework-oauth/
|
||||
[django-rest-framework-oauth-authentication]: https://jpadilla.github.io/django-rest-framework-oauth/authentication/
|
||||
[django-rest-framework-oauth-permissions]: https://jpadilla.github.io/django-rest-framework-oauth/permissions/
|
||||
[juanriaza]: https://github.com/juanriaza
|
||||
[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
|
||||
[oauth-1.0a]: https://oauth.net/core/1.0a/
|
||||
[django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
|
||||
[jazzband]: https://github.com/jazzband/
|
||||
[oauthlib]: https://github.com/idan/oauthlib
|
||||
[djangorestframework-simplejwt]: https://github.com/davesque/django-rest-framework-simplejwt
|
||||
[etoccalino]: https://github.com/etoccalino/
|
||||
[djangorestframework-httpsignature]: https://github.com/etoccalino/django-rest-framework-httpsignature
|
||||
[drf-httpsig]: https://github.com/ahknight/drf-httpsig
|
||||
[amazon-http-signature]: https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
|
||||
[http-signature-ietf-draft]: https://datatracker.ietf.org/doc/draft-cavage-http-signatures/
|
||||
[hawkrest]: https://hawkrest.readthedocs.io/en/latest/
|
||||
[hawk]: https://github.com/hueniverse/hawk
|
||||
[mohawk]: https://mohawk.readthedocs.io/en/latest/
|
||||
[mac]: https://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05
|
||||
[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
|
||||
[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
|
||||
[django-rest-durin]: https://github.com/eshaan7/django-rest-durin
|
||||
[login-required-middleware]: https://docs.djangoproject.com/en/stable/ref/middleware/#django.contrib.auth.middleware.LoginRequiredMiddleware
|
||||
[django-pyoidc] : https://github.com/makinacorpus/django_pyoidc
|
||||
|
|
|
@ -1,91 +0,0 @@
|
|||
# Caching
|
||||
|
||||
> A certain woman had a very sharp consciousness but almost no
|
||||
> memory ... She remembered enough to work, and she worked hard.
|
||||
> - Lydia Davis
|
||||
|
||||
Caching in REST Framework works well with the cache utilities
|
||||
provided in Django.
|
||||
|
||||
---
|
||||
|
||||
## Using cache with apiview and viewsets
|
||||
|
||||
Django provides a [`method_decorator`][decorator] to use
|
||||
decorators with class based views. This can be used with
|
||||
other cache decorators such as [`cache_page`][page],
|
||||
[`vary_on_cookie`][cookie] and [`vary_on_headers`][headers].
|
||||
|
||||
```python
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.cache import cache_page
|
||||
from django.views.decorators.vary import vary_on_cookie, vary_on_headers
|
||||
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework import viewsets
|
||||
|
||||
|
||||
class UserViewSet(viewsets.ViewSet):
|
||||
# With cookie: cache requested url for each user for 2 hours
|
||||
@method_decorator(cache_page(60 * 60 * 2))
|
||||
@method_decorator(vary_on_cookie)
|
||||
def list(self, request, format=None):
|
||||
content = {
|
||||
"user_feed": request.user.get_user_feed(),
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
|
||||
class ProfileView(APIView):
|
||||
# With auth: cache requested url for each user for 2 hours
|
||||
@method_decorator(cache_page(60 * 60 * 2))
|
||||
@method_decorator(vary_on_headers("Authorization"))
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
"user_feed": request.user.get_user_feed(),
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
|
||||
class PostView(APIView):
|
||||
# Cache page for the requested url
|
||||
@method_decorator(cache_page(60 * 60 * 2))
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
"title": "Post title",
|
||||
"body": "Post content",
|
||||
}
|
||||
return Response(content)
|
||||
```
|
||||
|
||||
|
||||
## Using cache with @api_view decorator
|
||||
|
||||
When using @api_view decorator, the Django-provided method-based cache decorators such as [`cache_page`][page],
|
||||
[`vary_on_cookie`][cookie] and [`vary_on_headers`][headers] can be called directly.
|
||||
|
||||
```python
|
||||
from django.views.decorators.cache import cache_page
|
||||
from django.views.decorators.vary import vary_on_cookie
|
||||
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.response import Response
|
||||
|
||||
|
||||
@cache_page(60 * 15)
|
||||
@vary_on_cookie
|
||||
@api_view(["GET"])
|
||||
def get_user_list(request):
|
||||
content = {"user_feed": request.user.get_user_feed()}
|
||||
return Response(content)
|
||||
```
|
||||
|
||||
|
||||
**NOTE:** The [`cache_page`][page] decorator only caches the
|
||||
`GET` and `HEAD` responses with status 200.
|
||||
|
||||
[page]: https://docs.djangoproject.com/en/stable/topics/cache/#the-per-view-cache
|
||||
[cookie]: https://docs.djangoproject.com/en/stable/topics/http/decorators/#django.views.decorators.vary.vary_on_cookie
|
||||
[headers]: https://docs.djangoproject.com/en/stable/topics/http/decorators/#django.views.decorators.vary.vary_on_headers
|
||||
[decorator]: https://docs.djangoproject.com/en/stable/topics/class-based-views/intro/#decorating-the-class
|
|
@ -1,7 +1,4 @@
|
|||
---
|
||||
source:
|
||||
- negotiation.py
|
||||
---
|
||||
<a class="github" href="negotiation.py"></a>
|
||||
|
||||
# Content negotiation
|
||||
|
||||
|
@ -9,7 +6,7 @@ source:
|
|||
>
|
||||
> — [RFC 2616][cite], Fielding et al.
|
||||
|
||||
[cite]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html
|
||||
[cite]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html
|
||||
|
||||
Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences.
|
||||
|
||||
|
@ -32,7 +29,7 @@ The priorities for each of the given media types would be:
|
|||
|
||||
If the requested view was only configured with renderers for `YAML` and `HTML`, then REST framework would select whichever renderer was listed first in the `renderer_classes` list or `DEFAULT_RENDERER_CLASSES` setting.
|
||||
|
||||
For more information on the `HTTP Accept` header, see [RFC 2616][accept-header]
|
||||
For more information on the `HTTP Accept` header, see [RFC 2616][accept-header]
|
||||
|
||||
---
|
||||
|
||||
|
@ -46,55 +43,24 @@ This is a valid approach as the HTTP spec deliberately underspecifies how a serv
|
|||
|
||||
It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override `BaseContentNegotiation`.
|
||||
|
||||
REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the `.select_parser(request, parsers)` and `.select_renderer(request, renderers, format_suffix)` methods.
|
||||
|
||||
The `select_parser()` method should return one of the parser instances from the list of available parsers, or `None` if none of the parsers can handle the incoming request.
|
||||
|
||||
The `select_renderer()` method should return a two-tuple of (renderer instance, media type), or raise a `NotAcceptable` exception.
|
||||
REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the `.select_parser(request, parsers)` and `.select_renderer(request, renderers, format_suffix)` methods.
|
||||
|
||||
## Example
|
||||
|
||||
The following is a custom content negotiation class which ignores the client
|
||||
request when selecting the appropriate parser or renderer.
|
||||
|
||||
from rest_framework.negotiation import BaseContentNegotiation
|
||||
|
||||
class IgnoreClientContentNegotiation(BaseContentNegotiation):
|
||||
def select_parser(self, request, parsers):
|
||||
"""
|
||||
Select the first parser in the `.parser_classes` list.
|
||||
"""
|
||||
return parsers[0]
|
||||
|
||||
|
||||
def select_renderer(self, request, renderers, format_suffix):
|
||||
"""
|
||||
Select the first renderer in the `.renderer_classes` list.
|
||||
"""
|
||||
return (renderers[0], renderers[0].media_type)
|
||||
return renderers[0]
|
||||
|
||||
## Setting the content negotiation
|
||||
|
||||
The default content negotiation class may be set globally, using the `DEFAULT_CONTENT_NEGOTIATION_CLASS` setting. For example, the following settings would use our example `IgnoreClientContentNegotiation` class.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation',
|
||||
}
|
||||
|
||||
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 rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
class NoNegotiationView(APIView):
|
||||
"""
|
||||
An example view that does not perform content negotiation.
|
||||
"""
|
||||
content_negotiation_class = IgnoreClientContentNegotiation
|
||||
|
||||
def get(self, request, format=None):
|
||||
return Response({
|
||||
'accepted media type': request.accepted_renderer.media_type
|
||||
})
|
||||
|
||||
[accept-header]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
|
||||
[accept-header]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
|
||||
|
|
|
@ -1,7 +1,4 @@
|
|||
---
|
||||
source:
|
||||
- exceptions.py
|
||||
---
|
||||
<a class="github" href="exceptions.py"></a>
|
||||
|
||||
# Exceptions
|
||||
|
||||
|
@ -21,7 +18,7 @@ The handled exceptions are:
|
|||
|
||||
In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error.
|
||||
|
||||
Most error responses will include a key `detail` in the body of the response.
|
||||
By default all error responses will include a key `details` in the body of the response, but other keys may also be included.
|
||||
|
||||
For example, the following request:
|
||||
|
||||
|
@ -31,243 +28,61 @@ For example, the following request:
|
|||
Might receive an error response indicating that the `DELETE` method is not allowed on that resource:
|
||||
|
||||
HTTP/1.1 405 Method Not Allowed
|
||||
Content-Type: application/json
|
||||
Content-Type: application/json; charset=utf-8
|
||||
Content-Length: 42
|
||||
|
||||
|
||||
{"detail": "Method 'DELETE' not allowed."}
|
||||
|
||||
Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the `NON_FIELD_ERRORS_KEY` setting.
|
||||
|
||||
An example validation error might look like this:
|
||||
|
||||
HTTP/1.1 400 Bad Request
|
||||
Content-Type: application/json
|
||||
Content-Length: 94
|
||||
|
||||
{"amount": ["A valid integer is required."], "description": ["This field may not be blank."]}
|
||||
|
||||
## Custom exception handling
|
||||
|
||||
You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.
|
||||
|
||||
The function must take a pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a `Response` object, or return `None` if the exception cannot be handled. If the handler returns `None` then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.
|
||||
|
||||
For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:
|
||||
|
||||
HTTP/1.1 405 Method Not Allowed
|
||||
Content-Type: application/json
|
||||
Content-Length: 62
|
||||
|
||||
{"status_code": 405, "detail": "Method 'DELETE' not allowed."}
|
||||
|
||||
In order to alter the style of the response, you could write the following custom exception handler:
|
||||
|
||||
from rest_framework.views import exception_handler
|
||||
|
||||
def custom_exception_handler(exc, context):
|
||||
# Call REST framework's default exception handler first,
|
||||
# to get the standard error response.
|
||||
response = exception_handler(exc, context)
|
||||
|
||||
# Now add the HTTP status code to the response.
|
||||
if response is not None:
|
||||
response.data['status_code'] = response.status_code
|
||||
|
||||
return response
|
||||
|
||||
The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as `context['view']`.
|
||||
|
||||
The exception handler must also be configured in your settings, using the `EXCEPTION_HANDLER` setting key. For example:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
|
||||
}
|
||||
|
||||
If not specified, the `'EXCEPTION_HANDLER'` setting defaults to the standard exception handler provided by REST framework:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
|
||||
}
|
||||
|
||||
Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the `HTTP_400_BAD_REQUEST` responses that are returned by the generic views when serializer validation fails.
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## APIException
|
||||
|
||||
**Signature:** `APIException()`
|
||||
**Signature:** `APIException(detail=None)`
|
||||
|
||||
The **base class** for all exceptions raised inside an `APIView` class or `@api_view`.
|
||||
The **base class** for all exceptions raised inside REST framework.
|
||||
|
||||
To provide a custom exception, subclass `APIException` and set the `.status_code`, `.default_detail`, and `.default_code` attributes on the class.
|
||||
|
||||
For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so:
|
||||
|
||||
from rest_framework.exceptions import APIException
|
||||
|
||||
class ServiceUnavailable(APIException):
|
||||
status_code = 503
|
||||
default_detail = 'Service temporarily unavailable, try again later.'
|
||||
default_code = 'service_unavailable'
|
||||
|
||||
#### Inspecting API exceptions
|
||||
|
||||
There are a number of different properties available for inspecting the status
|
||||
of an API exception. You can use these to build custom exception handling
|
||||
for your project.
|
||||
|
||||
The available attributes and methods are:
|
||||
|
||||
* `.detail` - Return the textual description of the error.
|
||||
* `.get_codes()` - Return the code identifier of the error.
|
||||
* `.get_full_details()` - Return both the textual description and the code identifier.
|
||||
|
||||
In most cases the error detail will be a simple item:
|
||||
|
||||
>>> print(exc.detail)
|
||||
You do not have permission to perform this action.
|
||||
>>> print(exc.get_codes())
|
||||
permission_denied
|
||||
>>> print(exc.get_full_details())
|
||||
{'message':'You do not have permission to perform this action.','code':'permission_denied'}
|
||||
|
||||
In the case of validation errors the error detail will be either a list or
|
||||
dictionary of items:
|
||||
|
||||
>>> print(exc.detail)
|
||||
{"name":"This field is required.","age":"A valid integer is required."}
|
||||
>>> print(exc.get_codes())
|
||||
{"name":"required","age":"invalid"}
|
||||
>>> print(exc.get_full_details())
|
||||
{"name":{"message":"This field is required.","code":"required"},"age":{"message":"A valid integer is required.","code":"invalid"}}
|
||||
To provide a custom exception, subclass `APIException` and set the `.status_code` and `.detail` properties on the class.
|
||||
|
||||
## ParseError
|
||||
|
||||
**Signature:** `ParseError(detail=None, code=None)`
|
||||
**Signature:** `ParseError(detail=None)`
|
||||
|
||||
Raised if the request contains malformed data when accessing `request.data`.
|
||||
Raised if the request contains malformed data when accessing `request.DATA` or `request.FILES`.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "400 Bad Request".
|
||||
|
||||
## AuthenticationFailed
|
||||
|
||||
**Signature:** `AuthenticationFailed(detail=None, code=None)`
|
||||
|
||||
Raised when an incoming request includes incorrect authentication.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
|
||||
|
||||
## NotAuthenticated
|
||||
|
||||
**Signature:** `NotAuthenticated(detail=None, code=None)`
|
||||
|
||||
Raised when an unauthenticated request fails the permission checks.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
|
||||
|
||||
## PermissionDenied
|
||||
|
||||
**Signature:** `PermissionDenied(detail=None, code=None)`
|
||||
**Signature:** `PermissionDenied(detail=None)`
|
||||
|
||||
Raised when an authenticated request fails the permission checks.
|
||||
Raised when an incoming request fails the permission checks.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "403 Forbidden".
|
||||
|
||||
## NotFound
|
||||
|
||||
**Signature:** `NotFound(detail=None, code=None)`
|
||||
|
||||
Raised when a resource does not exist at the given URL. This exception is equivalent to the standard `Http404` Django exception.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "404 Not Found".
|
||||
|
||||
## MethodNotAllowed
|
||||
|
||||
**Signature:** `MethodNotAllowed(method, detail=None, code=None)`
|
||||
**Signature:** `MethodNotAllowed(method, detail=None)`
|
||||
|
||||
Raised when an incoming request occurs that does not map to a handler method on the view.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "405 Method Not Allowed".
|
||||
|
||||
## NotAcceptable
|
||||
|
||||
**Signature:** `NotAcceptable(detail=None, code=None)`
|
||||
|
||||
Raised when an incoming request occurs with an `Accept` header that cannot be satisfied by any of the available renderers.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "406 Not Acceptable".
|
||||
|
||||
## UnsupportedMediaType
|
||||
|
||||
**Signature:** `UnsupportedMediaType(media_type, detail=None, code=None)`
|
||||
**Signature:** `UnsupportedMediaType(media_type, detail=None)`
|
||||
|
||||
Raised if there are no parsers that can handle the content type of the request data when accessing `request.data`.
|
||||
Raised if there are no parsers that can handle the content type of the request data when accessing `request.DATA` or `request.FILES`.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".
|
||||
|
||||
## Throttled
|
||||
|
||||
**Signature:** `Throttled(wait=None, detail=None, code=None)`
|
||||
**Signature:** `Throttled(wait=None, detail=None)`
|
||||
|
||||
Raised when an incoming request fails the throttling checks.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "429 Too Many Requests".
|
||||
|
||||
## ValidationError
|
||||
|
||||
**Signature:** `ValidationError(detail=None, code=None)`
|
||||
|
||||
The `ValidationError` exception is slightly different from the other `APIException` classes:
|
||||
|
||||
* The `detail` argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the `validate()` method of a serializer. For example. `raise serializers.ValidationError({'name': 'Please enter a valid name.'})`
|
||||
* By convention you should import the serializers module and use a fully qualified `ValidationError` style, in order to differentiate it from Django's built-in validation error. For example. `raise serializers.ValidationError('This field must be an integer value.')`
|
||||
|
||||
The `ValidationError` class should be used for serializer and field validation, and by validator classes. It is also raised when calling `serializer.is_valid` with the `raise_exception` keyword argument:
|
||||
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
The generic views use the `raise_exception=True` flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "400 Bad Request".
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Generic Error Views
|
||||
|
||||
Django REST Framework provides two error views suitable for providing generic JSON `500` Server Error and
|
||||
`400` Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an
|
||||
API-only application.)
|
||||
|
||||
Use these as per [Django's Customizing error views documentation][django-custom-error-views].
|
||||
|
||||
## `rest_framework.exceptions.server_error`
|
||||
|
||||
Returns a response with status code `500` and `application/json` content type.
|
||||
|
||||
Set as `handler500`:
|
||||
|
||||
handler500 = 'rest_framework.exceptions.server_error'
|
||||
|
||||
## `rest_framework.exceptions.bad_request`
|
||||
|
||||
Returns a response with status code `400` and `application/json` content type.
|
||||
|
||||
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/stable/topics/http/views/#customizing-error-views
|
||||
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors
|
||||
[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html
|
||||
|
|
|
@ -1,11 +1,8 @@
|
|||
---
|
||||
source:
|
||||
- fields.py
|
||||
---
|
||||
<a class="github" href="fields.py"></a>
|
||||
|
||||
# Serializer fields
|
||||
|
||||
> Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format.
|
||||
> Each field in a Form class is responsible not only for validating data, but also for "cleaning" it -- normalizing it to a consistent format.
|
||||
>
|
||||
> — [Django documentation][cite]
|
||||
|
||||
|
@ -13,25 +10,25 @@ Serializer fields handle converting between primitive values and internal dataty
|
|||
|
||||
---
|
||||
|
||||
**Note:** The serializer fields are declared in `fields.py`, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
|
||||
**Note:** The serializer fields are declared in fields.py, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
|
||||
|
||||
---
|
||||
|
||||
## Core arguments
|
||||
|
||||
Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
|
||||
Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
|
||||
|
||||
### `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 `Field(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `Field(source='user.email')`.
|
||||
|
||||
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. (See the implementation of the `PaginationSerializer` class for an example.)
|
||||
|
||||
Defaults to the name of the field.
|
||||
|
||||
### `read_only`
|
||||
|
||||
Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.
|
||||
|
||||
Set this to `True` to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.
|
||||
|
||||
Defaults to `False`
|
||||
|
||||
### `write_only`
|
||||
|
||||
Set this to `True` to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.
|
||||
Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance during deserialization.
|
||||
|
||||
Defaults to `False`
|
||||
|
||||
|
@ -40,143 +37,133 @@ Defaults to `False`
|
|||
Normally an error will be raised if a field is not supplied during deserialization.
|
||||
Set to false if this field is not required to be present during deserialization.
|
||||
|
||||
Setting this to `False` also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.
|
||||
|
||||
Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer), the default value will be `False` when you have specified a `default`, or when the corresponding `Model` field has `blank=True` or `null=True` and is not part of a unique constraint at the same time. (Note that without a `default` value, [unique constraints will cause the field to be required](https://www.django-rest-framework.org/api-guide/validators/#optional-fields).)
|
||||
Defaults to `True`.
|
||||
|
||||
### `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 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.
|
||||
|
||||
May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a `requires_context = True` attribute, then the serializer field will be passed as an argument.
|
||||
|
||||
For example:
|
||||
|
||||
class CurrentUserDefault:
|
||||
"""
|
||||
May be applied as a `default=...` value on a serializer field.
|
||||
Returns the current user.
|
||||
"""
|
||||
requires_context = True
|
||||
|
||||
def __call__(self, serializer_field):
|
||||
return serializer_field.context['request'].user
|
||||
|
||||
When serializing the instance, default will be used if the object attribute or dictionary key is not present in the instance.
|
||||
|
||||
Note that setting a `default` value implies that the field is not required. Including both the `default` and `required` keyword arguments is invalid and will raise an error.
|
||||
|
||||
### `allow_null`
|
||||
|
||||
Normally an error will be raised if `None` is passed to a serializer field. Set this keyword argument to `True` if `None` should be considered a valid value.
|
||||
|
||||
Note that, without an explicit `default`, setting this argument to `True` will imply a `default` value of `null` for serialization output, but does not imply a default for input deserialization.
|
||||
|
||||
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')`.
|
||||
|
||||
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")
|
||||
|
||||
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.
|
||||
|
||||
Defaults to the name of the field.
|
||||
If set, this gives the default value that will be used for the field if none is supplied. If not set the default behavior is to not populate the attribute at all.
|
||||
|
||||
### `validators`
|
||||
|
||||
A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise `serializers.ValidationError`, but Django's built-in `ValidationError` is also supported for compatibility with validators defined in the Django codebase or third party Django packages.
|
||||
A list of Django validators that should be used to validate deserialized values.
|
||||
|
||||
### `error_messages`
|
||||
|
||||
A dictionary of error codes to error messages.
|
||||
|
||||
### `label`
|
||||
### `widget`
|
||||
|
||||
A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
|
||||
Used only if rendering the field to HTML.
|
||||
This argument sets the widget that should be used to render the field.
|
||||
|
||||
### `help_text`
|
||||
|
||||
A text string that may be used as a description of the field in HTML form fields or other descriptive elements.
|
||||
|
||||
### `initial`
|
||||
|
||||
A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as
|
||||
you may do with any regular Django `Field`:
|
||||
|
||||
import datetime
|
||||
from rest_framework import serializers
|
||||
class ExampleSerializer(serializers.Serializer):
|
||||
day = serializers.DateField(initial=datetime.date.today)
|
||||
|
||||
### `style`
|
||||
|
||||
A dictionary of key-value pairs that can be used to control how renderers should render the field.
|
||||
|
||||
Two examples here are `'input_type'` and `'base_template'`:
|
||||
|
||||
# Use <input type="password"> for the input.
|
||||
password = serializers.CharField(
|
||||
style={'input_type': 'password'}
|
||||
)
|
||||
|
||||
# Use a radio input instead of a select input.
|
||||
color_channel = serializers.ChoiceField(
|
||||
choices=['red', 'green', 'blue'],
|
||||
style={'base_template': 'radio.html'}
|
||||
)
|
||||
|
||||
For more details see the [HTML & Forms][html-and-forms] documentation.
|
||||
|
||||
---
|
||||
|
||||
# Boolean fields
|
||||
# Generic Fields
|
||||
|
||||
These generic fields are used for representing arbitrary model fields or the output of model methods.
|
||||
|
||||
## Field
|
||||
|
||||
A generic, **read-only** field. You can use this field for any attribute that does not need to support write operations.
|
||||
|
||||
For example, using the following model.
|
||||
|
||||
class Account(models.Model):
|
||||
owner = models.ForeignKey('auth.user')
|
||||
name = models.CharField(max_length=100)
|
||||
created = models.DateTimeField(auto_now_add=True)
|
||||
payment_expiry = models.DateTimeField()
|
||||
|
||||
def has_expired(self):
|
||||
now = datetime.datetime.now()
|
||||
return now > self.payment_expiry
|
||||
|
||||
A serializer definition that looked like this:
|
||||
|
||||
class AccountSerializer(serializers.HyperlinkedModelSerializer):
|
||||
expired = Field(source='has_expired')
|
||||
|
||||
class Meta:
|
||||
fields = ('url', 'owner', 'name', 'expired')
|
||||
|
||||
Would produce output similar to:
|
||||
|
||||
{
|
||||
'url': 'http://example.com/api/accounts/3/',
|
||||
'owner': 'http://example.com/api/users/12/',
|
||||
'name': 'FooCorp business account',
|
||||
'expired': True
|
||||
}
|
||||
|
||||
By default, the `Field` class will perform a basic translation of the source value into primitive datatypes, falling back to unicode representations of complex datatypes when necessary.
|
||||
|
||||
You can customize this behavior by overriding the `.to_native(self, value)` method.
|
||||
|
||||
## WritableField
|
||||
|
||||
A field that supports both read and write operations. By itself `WriteableField` does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the `.to_native(self, value)` and `.from_native(self, value)` methods.
|
||||
|
||||
## ModelField
|
||||
|
||||
A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to it's associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.
|
||||
|
||||
**Signature:** `ModelField(model_field=<Django ModelField class>)`
|
||||
|
||||
## SerializerMethodField
|
||||
|
||||
This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method 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:
|
||||
|
||||
from rest_framework import serializers
|
||||
from django.contrib.auth.models import User
|
||||
from django.utils.timezone import now
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer):
|
||||
|
||||
days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
|
||||
def get_days_since_joined(self, obj):
|
||||
return (now() - obj.date_joined).days
|
||||
|
||||
---
|
||||
|
||||
# Typed Fields
|
||||
|
||||
These fields represent basic datatypes, and support both reading and writing values.
|
||||
|
||||
## BooleanField
|
||||
|
||||
A boolean representation.
|
||||
|
||||
When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to `False`, even if it has a `default=True` option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.
|
||||
|
||||
Note that Django 2.1 removed the `blank` kwarg from `models.BooleanField`.
|
||||
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 behavior manually,
|
||||
explicitly declare the `BooleanField` on the serializer class, or use the
|
||||
`extra_kwargs` option to set the `required` flag.
|
||||
A Boolean representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.BooleanField`.
|
||||
|
||||
**Signature:** `BooleanField()`
|
||||
|
||||
---
|
||||
|
||||
# String fields
|
||||
|
||||
## CharField
|
||||
|
||||
A text representation. Optionally validates the text to be shorter than `max_length` and longer than `min_length`.
|
||||
A text representation, optionally validates the text to be shorter than `max_length` and longer than `min_length`.
|
||||
|
||||
Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.TextField`.
|
||||
Corresponds to `django.db.models.fields.CharField`
|
||||
or `django.db.models.fields.TextField`.
|
||||
|
||||
**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)`
|
||||
**Signature:** `CharField(max_length=None, min_length=None)`
|
||||
|
||||
* `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`.
|
||||
## URLField
|
||||
|
||||
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.
|
||||
Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation.
|
||||
|
||||
**Signature:** `CharField(max_length=200, min_length=None)`
|
||||
|
||||
## SlugField
|
||||
|
||||
Corresponds to `django.db.models.fields.SlugField`.
|
||||
|
||||
**Signature:** `CharField(max_length=50, min_length=None)`
|
||||
|
||||
## ChoiceField
|
||||
|
||||
A field that can accept a value out of a limited set of choices.
|
||||
|
||||
## EmailField
|
||||
|
||||
|
@ -184,162 +171,15 @@ A text representation, validates the text to be a valid e-mail address.
|
|||
|
||||
Corresponds to `django.db.models.fields.EmailField`
|
||||
|
||||
**Signature:** `EmailField(max_length=None, min_length=None, allow_blank=False)`
|
||||
|
||||
## RegexField
|
||||
|
||||
A text representation, that validates the given value matches against a certain regular expression.
|
||||
|
||||
Corresponds to `django.forms.fields.RegexField`.
|
||||
|
||||
**Signature:** `RegexField(regex, max_length=None, min_length=None, allow_blank=False)`
|
||||
|
||||
The mandatory `regex` argument may either be a string, or a compiled python regular expression object.
|
||||
|
||||
Uses Django's `django.core.validators.RegexValidator` for validation.
|
||||
|
||||
## SlugField
|
||||
Corresponds to `django.forms.fields.RegexField`
|
||||
|
||||
A `RegexField` that validates the input against the pattern `[a-zA-Z0-9_-]+`.
|
||||
|
||||
Corresponds to `django.db.models.fields.SlugField`.
|
||||
|
||||
**Signature:** `SlugField(max_length=50, min_length=None, allow_blank=False)`
|
||||
|
||||
## URLField
|
||||
|
||||
A `RegexField` that validates the input against a URL matching pattern. Expects fully qualified URLs of the form `http://<host>/<path>`.
|
||||
|
||||
Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation.
|
||||
|
||||
**Signature:** `URLField(max_length=200, min_length=None, allow_blank=False)`
|
||||
|
||||
## UUIDField
|
||||
|
||||
A field that ensures the input is a valid UUID string. The `to_internal_value` method will return a `uuid.UUID` instance. On output the field will return a string in the canonical hyphenated format, for example:
|
||||
|
||||
"de305d54-75b4-431b-adb2-eb6b9e546013"
|
||||
|
||||
**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"`
|
||||
Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value`
|
||||
|
||||
## FilePathField
|
||||
|
||||
A field whose choices are limited to the filenames in a certain directory on the filesystem
|
||||
|
||||
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`.
|
||||
|
||||
## IPAddressField
|
||||
|
||||
A field that ensures the input is a valid IPv4 or IPv6 string.
|
||||
|
||||
Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.GenericIPAddressField`.
|
||||
|
||||
**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'.
|
||||
|
||||
---
|
||||
|
||||
# Numeric fields
|
||||
|
||||
## IntegerField
|
||||
|
||||
An integer representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField`.
|
||||
|
||||
**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.
|
||||
|
||||
## FloatField
|
||||
|
||||
A floating point representation.
|
||||
|
||||
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.
|
||||
|
||||
## DecimalField
|
||||
|
||||
A decimal representation, represented in Python by a `Decimal` instance.
|
||||
|
||||
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. Should be an integer or `Decimal` object.
|
||||
* `min_value` Validate that the number provided is no less than this value. Should be an integer or `Decimal` object.
|
||||
* `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 quantizing to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
|
||||
* `normalize_output` Will normalize the decimal value when serialized. This will strip all trailing zeroes and change the value's precision to the minimum required precision to be able to represent the value without losing data. Defaults to `False`.
|
||||
|
||||
#### Example usage
|
||||
|
||||
To validate numbers up to 999 with a resolution of 2 decimal places, you would use:
|
||||
|
||||
serializers.DecimalField(max_digits=5, decimal_places=2)
|
||||
|
||||
And to validate numbers up to anything less than one billion with a resolution of 10 decimal places:
|
||||
|
||||
serializers.DecimalField(max_digits=19, decimal_places=10)
|
||||
|
||||
---
|
||||
|
||||
# Date and time fields
|
||||
|
||||
## DateTimeField
|
||||
|
||||
A date and time representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.DateTimeField`.
|
||||
|
||||
**Signature:** `DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None, default_timezone=None)`
|
||||
|
||||
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. In this case the datetime encoding will be determined by the renderer.
|
||||
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
|
||||
* `default_timezone` - A `tzinfo` subclass (`zoneinfo` or `pytz`) representing the timezone. If not specified and the `USE_TZ` setting is enabled, this defaults to the [current timezone][django-current-timezone]. If `USE_TZ` is disabled, then datetime objects will be naive.
|
||||
|
||||
#### `DateTimeField` format strings.
|
||||
|
||||
Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`)
|
||||
|
||||
When a value of `None` is used for the format `datetime` objects will be returned by `to_representation` and the final output representation will be determined by the renderer class.
|
||||
|
||||
#### `auto_now` and `auto_now_add` model fields.
|
||||
|
||||
When using `ModelSerializer` or `HyperlinkedModelSerializer`, note that any model fields with `auto_now=True` or `auto_now_add=True` will use serializer fields that are `read_only=True` by default.
|
||||
|
||||
If you want to override this behavior, you'll need to declare the `DateTimeField` explicitly on the serializer. For example:
|
||||
|
||||
class CommentSerializer(serializers.ModelSerializer):
|
||||
created = serializers.DateTimeField()
|
||||
|
||||
class Meta:
|
||||
model = Comment
|
||||
**Signature:** `RegexField(regex, max_length=None, min_length=None)`
|
||||
|
||||
## DateField
|
||||
|
||||
|
@ -347,514 +187,50 @@ A date representation.
|
|||
|
||||
Corresponds to `django.db.models.fields.DateField`
|
||||
|
||||
**Signature:** `DateField(format=api_settings.DATE_FORMAT, input_formats=None)`
|
||||
## DateTimeField
|
||||
|
||||
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATE_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `date` objects should be returned by `to_representation`. In this case the date encoding will be determined by the renderer.
|
||||
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
|
||||
A date and time representation.
|
||||
|
||||
#### `DateField` format strings
|
||||
Corresponds to `django.db.models.fields.DateTimeField`
|
||||
|
||||
Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`)
|
||||
## IntegerField
|
||||
|
||||
## TimeField
|
||||
An integer representation.
|
||||
|
||||
A time representation.
|
||||
Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField`
|
||||
|
||||
Corresponds to `django.db.models.fields.TimeField`
|
||||
## FloatField
|
||||
|
||||
**Signature:** `TimeField(format=api_settings.TIME_FORMAT, input_formats=None)`
|
||||
A floating point representation.
|
||||
|
||||
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `TIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `time` objects should be returned by `to_representation`. In this case the time encoding will be determined by the renderer.
|
||||
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
|
||||
|
||||
#### `TimeField` format strings
|
||||
|
||||
Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`)
|
||||
|
||||
## DurationField
|
||||
|
||||
A Duration representation.
|
||||
Corresponds to `django.db.models.fields.DurationField`
|
||||
|
||||
The `validated_data` for these fields will contain a `datetime.timedelta` instance.
|
||||
The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu]'`.
|
||||
|
||||
**Signature:** `DurationField(max_value=None, min_value=None)`
|
||||
|
||||
* `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.
|
||||
|
||||
---
|
||||
|
||||
# Choice selection fields
|
||||
|
||||
## ChoiceField
|
||||
|
||||
A field that can accept a value out of a limited set of choices.
|
||||
|
||||
Used by `ModelSerializer` to automatically generate fields if the corresponding model field includes a `choices=…` argument.
|
||||
|
||||
**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…"`
|
||||
|
||||
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.
|
||||
|
||||
## MultipleChoiceField
|
||||
|
||||
A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. `to_internal_value` returns a `set` containing the selected values.
|
||||
|
||||
**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…"`
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
# File upload fields
|
||||
|
||||
#### Parsers and file uploads.
|
||||
|
||||
The `FileField` and `ImageField` classes are only suitable for use with `MultiPartParser` or `FileUploadParser`. Most parsers, such as e.g. JSON don't support file uploads.
|
||||
Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
|
||||
Corresponds to `django.db.models.fields.FloatField`.
|
||||
|
||||
## FileField
|
||||
|
||||
A file representation. Performs Django's standard FileField validation.
|
||||
A file representation. Performs Django's standard FileField validation.
|
||||
|
||||
Corresponds to `django.forms.fields.FileField`.
|
||||
|
||||
**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
||||
**Signature:** `FileField(max_length=None, allow_empty_file=False)`
|
||||
|
||||
* `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.
|
||||
|
||||
## ImageField
|
||||
|
||||
An image representation. Validates the uploaded file content as matching a known image format.
|
||||
An image representation.
|
||||
|
||||
Corresponds to `django.forms.fields.ImageField`.
|
||||
|
||||
**Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
||||
Requires the `PIL` package.
|
||||
|
||||
* `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.
|
||||
Signature and validation is the same as with `FileField`.
|
||||
|
||||
---
|
||||
|
||||
# Composite fields
|
||||
**Note:** `FileFields` and `ImageFields` are only suitable for use with MultiPartParser, since e.g. json doesn't support file uploads.
|
||||
Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
|
||||
|
||||
## ListField
|
||||
|
||||
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.
|
||||
|
||||
For example, to validate a list of integers you might use something like the following:
|
||||
|
||||
scores = serializers.ListField(
|
||||
child=serializers.IntegerField(min_value=0, max_value=100)
|
||||
)
|
||||
|
||||
The `ListField` class also supports a declarative style that allows you to write reusable list field classes.
|
||||
|
||||
class StringListField(serializers.ListField):
|
||||
child = serializers.CharField()
|
||||
|
||||
We can now reuse our custom `StringListField` class throughout our application, without having to provide a `child` argument to it.
|
||||
|
||||
## DictField
|
||||
|
||||
A field class that validates a dictionary of objects. The keys in `DictField` are always assumed to be string values.
|
||||
|
||||
**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.
|
||||
|
||||
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
|
||||
|
||||
document = DictField(child=CharField())
|
||||
|
||||
You can also use the declarative style, as with `ListField`. For example:
|
||||
|
||||
class DocumentField(DictField):
|
||||
child = CharField()
|
||||
|
||||
## HStoreField
|
||||
|
||||
A preconfigured `DictField` that is compatible with Django's postgres `HStoreField`.
|
||||
|
||||
**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.
|
||||
|
||||
Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings.
|
||||
|
||||
## JSONField
|
||||
|
||||
A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.
|
||||
|
||||
**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`.
|
||||
|
||||
---
|
||||
|
||||
# Miscellaneous fields
|
||||
|
||||
## ReadOnlyField
|
||||
|
||||
A field class that simply returns the value of the field without modification.
|
||||
|
||||
This field is used by default with `ModelSerializer` when including field names that relate to an attribute rather than a model field.
|
||||
|
||||
**Signature**: `ReadOnlyField()`
|
||||
|
||||
For example, if `has_expired` was a property on the `Account` model, then the following serializer would automatically generate it as a `ReadOnlyField`:
|
||||
|
||||
class AccountSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ['id', 'account_name', 'has_expired']
|
||||
|
||||
## HiddenField
|
||||
|
||||
A field class that does not take a value based on user input, but instead takes its value from a default value or callable.
|
||||
|
||||
**Signature**: `HiddenField()`
|
||||
|
||||
For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:
|
||||
|
||||
modified = serializers.HiddenField(default=timezone.now)
|
||||
|
||||
The `HiddenField` class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.
|
||||
|
||||
For further examples on `HiddenField` see the [validators](validators.md) documentation.
|
||||
|
||||
---
|
||||
|
||||
**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request).
|
||||
|
||||
---
|
||||
|
||||
## ModelField
|
||||
|
||||
A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.
|
||||
|
||||
This field is used by `ModelSerializer` to correspond to custom model field classes.
|
||||
|
||||
**Signature:** `ModelField(model_field=<Django ModelField instance>)`
|
||||
|
||||
The `ModelField` class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model. For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))`
|
||||
|
||||
## SerializerMethodField
|
||||
|
||||
This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.
|
||||
|
||||
**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>`.
|
||||
|
||||
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:
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.utils.timezone import now
|
||||
from rest_framework import serializers
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer):
|
||||
days_since_joined = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = '__all__'
|
||||
|
||||
def get_days_since_joined(self, obj):
|
||||
return (now() - obj.date_joined).days
|
||||
|
||||
---
|
||||
|
||||
# Custom fields
|
||||
|
||||
If you want to create a custom field, you'll need to subclass `Field` and then override either one or both of the `.to_representation()` and `.to_internal_value()` methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, `date`/`time`/`datetime` or `None`. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.
|
||||
|
||||
The `.to_representation()` method is called to convert the initial datatype into a primitive, serializable datatype.
|
||||
|
||||
The `.to_internal_value()` method is called to restore a primitive datatype into its internal python representation. This method should raise a `serializers.ValidationError` if the data is invalid.
|
||||
|
||||
## Examples
|
||||
|
||||
### A Basic Custom Field
|
||||
|
||||
Let's look at an example of serializing a class that represents an RGB color value:
|
||||
|
||||
class Color:
|
||||
"""
|
||||
A color represented in the RGB colorspace.
|
||||
"""
|
||||
def __init__(self, red, green, blue):
|
||||
assert(red >= 0 and green >= 0 and blue >= 0)
|
||||
assert(red < 256 and green < 256 and blue < 256)
|
||||
self.red, self.green, self.blue = red, green, blue
|
||||
|
||||
class ColorField(serializers.Field):
|
||||
"""
|
||||
Color objects are serialized into 'rgb(#, #, #)' notation.
|
||||
"""
|
||||
def to_representation(self, value):
|
||||
return "rgb(%d, %d, %d)" % (value.red, value.green, value.blue)
|
||||
|
||||
def to_internal_value(self, data):
|
||||
data = data.strip('rgb(').rstrip(')')
|
||||
red, green, blue = [int(col) for col in data.split(',')]
|
||||
return Color(red, green, blue)
|
||||
|
||||
By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override `.get_attribute()` and/or `.get_value()`.
|
||||
|
||||
As an example, let's create a field that can be used to represent the class name of the object being serialized:
|
||||
|
||||
class ClassNameField(serializers.Field):
|
||||
def get_attribute(self, instance):
|
||||
# We pass the object instance onto `to_representation`,
|
||||
# not just the field attribute.
|
||||
return instance
|
||||
|
||||
def to_representation(self, value):
|
||||
"""
|
||||
Serialize the value's class name.
|
||||
"""
|
||||
return value.__class__.__name__
|
||||
|
||||
### Raising validation errors
|
||||
|
||||
Our `ColorField` class above currently does not perform any data validation.
|
||||
To indicate invalid data, we should raise a `serializers.ValidationError`, like so:
|
||||
|
||||
def to_internal_value(self, data):
|
||||
if not isinstance(data, str):
|
||||
msg = 'Incorrect type. Expected a string, but got %s'
|
||||
raise ValidationError(msg % type(data).__name__)
|
||||
|
||||
if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data):
|
||||
raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')
|
||||
|
||||
data = data.strip('rgb(').rstrip(')')
|
||||
red, green, blue = [int(col) for col in data.split(',')]
|
||||
|
||||
if any([col > 255 or col < 0 for col in (red, green, blue)]):
|
||||
raise ValidationError('Value out of range. Must be between 0 and 255.')
|
||||
|
||||
return Color(red, green, blue)
|
||||
|
||||
The `.fail()` method is a shortcut for raising `ValidationError` that takes a message string from the `error_messages` dictionary. For example:
|
||||
|
||||
default_error_messages = {
|
||||
'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',
|
||||
'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',
|
||||
'out_of_range': 'Value out of range. Must be between 0 and 255.'
|
||||
}
|
||||
|
||||
def to_internal_value(self, data):
|
||||
if not isinstance(data, str):
|
||||
self.fail('incorrect_type', input_type=type(data).__name__)
|
||||
|
||||
if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data):
|
||||
self.fail('incorrect_format')
|
||||
|
||||
data = data.strip('rgb(').rstrip(')')
|
||||
red, green, blue = [int(col) for col in data.split(',')]
|
||||
|
||||
if any([col > 255 or col < 0 for col in (red, green, blue)]):
|
||||
self.fail('out_of_range')
|
||||
|
||||
return Color(red, green, blue)
|
||||
|
||||
This style keeps your error messages cleaner and more separated from your code, and should be preferred.
|
||||
|
||||
### Using `source='*'`
|
||||
|
||||
Here we'll take an example of a _flat_ `DataPoint` model with `x_coordinate` and `y_coordinate` attributes.
|
||||
|
||||
class DataPoint(models.Model):
|
||||
label = models.CharField(max_length=50)
|
||||
x_coordinate = models.SmallIntegerField()
|
||||
y_coordinate = models.SmallIntegerField()
|
||||
|
||||
Using a custom field and `source='*'` we can provide a nested representation of
|
||||
the coordinate pair:
|
||||
|
||||
class CoordinateField(serializers.Field):
|
||||
|
||||
def to_representation(self, value):
|
||||
ret = {
|
||||
"x": value.x_coordinate,
|
||||
"y": value.y_coordinate
|
||||
}
|
||||
return ret
|
||||
|
||||
def to_internal_value(self, data):
|
||||
ret = {
|
||||
"x_coordinate": data["x"],
|
||||
"y_coordinate": data["y"],
|
||||
}
|
||||
return ret
|
||||
|
||||
|
||||
class DataPointSerializer(serializers.ModelSerializer):
|
||||
coordinates = CoordinateField(source='*')
|
||||
|
||||
class Meta:
|
||||
model = DataPoint
|
||||
fields = ['label', 'coordinates']
|
||||
|
||||
Note that this example doesn't handle validation. Partly for that reason, in a
|
||||
real project, the coordinate nesting might be better handled with a nested serializer
|
||||
using `source='*'`, with two `IntegerField` instances, each with their own `source`
|
||||
pointing to the relevant field.
|
||||
|
||||
The key points from the example, though, are:
|
||||
|
||||
* `to_representation` is passed the entire `DataPoint` object and must map from that
|
||||
to the desired output.
|
||||
|
||||
>>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2)
|
||||
>>> out_serializer = DataPointSerializer(instance)
|
||||
>>> out_serializer.data
|
||||
ReturnDict([('label', 'Example'), ('coordinates', {'x': 1, 'y': 2})])
|
||||
|
||||
* Unless our field is to be read-only, `to_internal_value` must map back to a dict
|
||||
suitable for updating our target object. With `source='*'`, the return from
|
||||
`to_internal_value` will update the root validated data dictionary, rather than a single key.
|
||||
|
||||
>>> data = {
|
||||
... "label": "Second Example",
|
||||
... "coordinates": {
|
||||
... "x": 3,
|
||||
... "y": 4,
|
||||
... }
|
||||
... }
|
||||
>>> in_serializer = DataPointSerializer(data=data)
|
||||
>>> in_serializer.is_valid()
|
||||
True
|
||||
>>> in_serializer.validated_data
|
||||
OrderedDict([('label', 'Second Example'),
|
||||
('y_coordinate', 4),
|
||||
('x_coordinate', 3)])
|
||||
|
||||
For completeness lets do the same thing again but with the nested serializer
|
||||
approach suggested above:
|
||||
|
||||
class NestedCoordinateSerializer(serializers.Serializer):
|
||||
x = serializers.IntegerField(source='x_coordinate')
|
||||
y = serializers.IntegerField(source='y_coordinate')
|
||||
|
||||
|
||||
class DataPointSerializer(serializers.ModelSerializer):
|
||||
coordinates = NestedCoordinateSerializer(source='*')
|
||||
|
||||
class Meta:
|
||||
model = DataPoint
|
||||
fields = ['label', 'coordinates']
|
||||
|
||||
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 behavior as the custom field
|
||||
approach.
|
||||
|
||||
Serializing:
|
||||
|
||||
>>> out_serializer = DataPointSerializer(instance)
|
||||
>>> out_serializer.data
|
||||
ReturnDict([('label', 'testing'),
|
||||
('coordinates', OrderedDict([('x', 1), ('y', 2)]))])
|
||||
|
||||
Deserializing:
|
||||
|
||||
>>> in_serializer = DataPointSerializer(data=data)
|
||||
>>> in_serializer.is_valid()
|
||||
True
|
||||
>>> in_serializer.validated_data
|
||||
OrderedDict([('label', 'still testing'),
|
||||
('x_coordinate', 3),
|
||||
('y_coordinate', 4)])
|
||||
|
||||
But we also get the built-in validation for free:
|
||||
|
||||
>>> invalid_data = {
|
||||
... "label": "still testing",
|
||||
... "coordinates": {
|
||||
... "x": 'a',
|
||||
... "y": 'b',
|
||||
... }
|
||||
... }
|
||||
>>> invalid_serializer = DataPointSerializer(data=invalid_data)
|
||||
>>> invalid_serializer.is_valid()
|
||||
False
|
||||
>>> invalid_serializer.errors
|
||||
ReturnDict([('coordinates',
|
||||
{'x': ['A valid integer is required.'],
|
||||
'y': ['A valid integer is required.']})])
|
||||
|
||||
For this reason, the nested serializer approach would be the first to try. You
|
||||
would use the custom field approach when the nested serializer becomes infeasible
|
||||
or overly complex.
|
||||
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages are also available.
|
||||
|
||||
## DRF Compound Fields
|
||||
|
||||
The [drf-compound-fields][drf-compound-fields] package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the `many=True` option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.
|
||||
|
||||
## DRF Extra Fields
|
||||
|
||||
The [drf-extra-fields][drf-extra-fields] package provides extra serializer fields for REST framework, including `Base64ImageField` and `PointField` classes.
|
||||
|
||||
## djangorestframework-recursive
|
||||
|
||||
the [djangorestframework-recursive][djangorestframework-recursive] package provides a `RecursiveField` for serializing and deserializing recursive structures
|
||||
|
||||
## 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.
|
||||
|
||||
## django-rest-framework-hstore
|
||||
|
||||
The [django-rest-framework-hstore][django-rest-framework-hstore] package provides an `HStoreField` to support [django-hstore][django-hstore] `DictionaryField` model field.
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/ref/forms/api/#django.forms.Form.cleaned_data
|
||||
[html-and-forms]: ../topics/html-and-forms.md
|
||||
[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
|
||||
[strftime]: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
|
||||
[iso8601]: https://www.w3.org/TR/NOTE-datetime
|
||||
[drf-compound-fields]: https://drf-compound-fields.readthedocs.io
|
||||
[drf-extra-fields]: https://github.com/Hipo/drf-extra-fields
|
||||
[djangorestframework-recursive]: https://github.com/heywbj/django-rest-framework-recursive
|
||||
[django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis
|
||||
[django-rest-framework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore
|
||||
[django-hstore]: https://github.com/djangonauts/django-hstore
|
||||
[python-decimal-rounding-modes]: https://docs.python.org/3/library/decimal.html#rounding-modes
|
||||
[django-current-timezone]: https://docs.djangoproject.com/en/stable/topics/i18n/timezones/#default-time-zone-and-current-time-zone
|
||||
[django-docs-select-related]: https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related
|
||||
[cite]: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data
|
||||
[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
|
||||
|
|
|
@ -1,17 +1,14 @@
|
|||
---
|
||||
source:
|
||||
- filters.py
|
||||
---
|
||||
<a class="github" href="filters.py"></a>
|
||||
|
||||
# Filtering
|
||||
|
||||
> The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.
|
||||
> The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.
|
||||
>
|
||||
> — [Django documentation][cite]
|
||||
|
||||
The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.
|
||||
|
||||
The simplest way to filter the queryset of any view that subclasses `GenericAPIView` is to override the `.get_queryset()` method.
|
||||
The simplest way to filter the queryset of any view that subclasses `MultipleObjectAPIView` is to override the `.get_queryset()` method.
|
||||
|
||||
Overriding this method allows you to customize the queryset returned by the view in a number of different ways.
|
||||
|
||||
|
@ -23,13 +20,10 @@ You can do so by filtering based on the value of `request.user`.
|
|||
|
||||
For example:
|
||||
|
||||
from myapp.models import Purchase
|
||||
from myapp.serializers import PurchaseSerializer
|
||||
from rest_framework import generics
|
||||
|
||||
class PurchaseList(generics.ListAPIView):
|
||||
class PurchaseList(generics.ListAPIView)
|
||||
model = Purchase
|
||||
serializer_class = PurchaseSerializer
|
||||
|
||||
|
||||
def get_queryset(self):
|
||||
"""
|
||||
This view should return a list of all the purchases
|
||||
|
@ -41,17 +35,18 @@ For example:
|
|||
|
||||
## Filtering against the URL
|
||||
|
||||
Another style of filtering might involve restricting the queryset based on some part of the URL.
|
||||
Another style of filtering might involve restricting the queryset based on some part of the URL.
|
||||
|
||||
For example if your URL config contained an entry like this:
|
||||
|
||||
re_path('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
|
||||
url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
|
||||
|
||||
You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
|
||||
|
||||
class PurchaseList(generics.ListAPIView):
|
||||
class PurchaseList(generics.ListAPIView)
|
||||
model = Purchase
|
||||
serializer_class = PurchaseSerializer
|
||||
|
||||
|
||||
def get_queryset(self):
|
||||
"""
|
||||
This view should return a list of all the purchases for
|
||||
|
@ -60,22 +55,23 @@ You could then write a view that returned a purchase queryset filtered by the us
|
|||
username = self.kwargs['username']
|
||||
return Purchase.objects.filter(purchaser__username=username)
|
||||
|
||||
## Filtering against query parameters
|
||||
## Filtering against query parameters
|
||||
|
||||
A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.
|
||||
|
||||
We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL:
|
||||
|
||||
class PurchaseList(generics.ListAPIView):
|
||||
class PurchaseList(generics.ListAPIView)
|
||||
model = Purchase
|
||||
serializer_class = PurchaseSerializer
|
||||
|
||||
|
||||
def get_queryset(self):
|
||||
"""
|
||||
Optionally restricts the returned purchases to a given user,
|
||||
by filtering against a `username` query parameter in the URL.
|
||||
"""
|
||||
queryset = Purchase.objects.all()
|
||||
username = self.request.query_params.get('username')
|
||||
username = self.request.QUERY_PARAMS.get('username', None)
|
||||
if username is not None:
|
||||
queryset = queryset.filter(purchaser__username=username)
|
||||
return queryset
|
||||
|
@ -84,43 +80,68 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
|
|||
|
||||
# Generic Filtering
|
||||
|
||||
As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.
|
||||
As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex filters that can be specified by the client using query parameters.
|
||||
|
||||
Generic filters can also present themselves as HTML controls in the browsable API and admin API.
|
||||
REST framework supports pluggable backends to implement filtering, and provides an implementation which uses the [django-filter] package.
|
||||
|
||||

|
||||
To use REST framework's filtering backend, first install `django-filter`.
|
||||
|
||||
## Setting filter backends
|
||||
pip install django-filter
|
||||
|
||||
The default filter backends may be set globally, using the `DEFAULT_FILTER_BACKENDS` setting. For example.
|
||||
You must also set the filter backend to `DjangoFilterBackend` in your settings:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
|
||||
'FILTER_BACKEND': 'rest_framework.filters.DjangoFilterBackend'
|
||||
}
|
||||
|
||||
You can also set the filter backends on a per-view, or per-viewset basis,
|
||||
using the `GenericAPIView` class-based views.
|
||||
|
||||
import django_filters.rest_framework
|
||||
from django.contrib.auth.models import User
|
||||
from myapp.serializers import UserSerializer
|
||||
from rest_framework import generics
|
||||
## Specifying filter fields
|
||||
|
||||
class UserListView(generics.ListAPIView):
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
|
||||
If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, listing the set of fields you wish to filter against.
|
||||
|
||||
## Filtering and object lookups
|
||||
class ProductList(generics.ListAPIView):
|
||||
model = Product
|
||||
serializer_class = ProductSerializer
|
||||
filter_fields = ('category', 'in_stock')
|
||||
|
||||
Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.
|
||||
This will automatically create a `FilterSet` class for the given fields, and will allow you to make requests such as:
|
||||
|
||||
For instance, given the previous example, and a product with an id of `4675`, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance:
|
||||
http://example.com/api/products?category=clothing&in_stock=True
|
||||
|
||||
http://example.com/api/products/4675/?category=clothing&max_price=10.00
|
||||
## Specifying a FilterSet
|
||||
|
||||
For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view. For example:
|
||||
|
||||
class ProductFilter(django_filters.FilterSet):
|
||||
min_price = django_filters.NumberFilter(lookup_type='gte')
|
||||
max_price = django_filters.NumberFilter(lookup_type='lte')
|
||||
class Meta:
|
||||
model = Product
|
||||
fields = ['category', 'in_stock', 'min_price', 'max_price']
|
||||
|
||||
class ProductList(generics.ListAPIView):
|
||||
model = Product
|
||||
serializer_class = ProductSerializer
|
||||
filter_class = ProductFilter
|
||||
|
||||
Which will allow you to make requests such as:
|
||||
|
||||
http://example.com/api/products?category=clothing&max_price=10.00
|
||||
|
||||
For more details on using filter sets see the [django-filter documentation][django-filter-docs].
|
||||
|
||||
---
|
||||
|
||||
**Hints & Tips**
|
||||
|
||||
* By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'FILTER_BACKEND'` setting.
|
||||
* When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].)
|
||||
* `django-filter` supports filtering across relationships, using Django's double-underscore syntax.
|
||||
|
||||
---
|
||||
|
||||
## Overriding the initial queryset
|
||||
|
||||
|
||||
Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this:
|
||||
|
||||
class PurchasedProductsList(generics.ListAPIView):
|
||||
|
@ -130,184 +151,11 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering
|
|||
"""
|
||||
model = Product
|
||||
serializer_class = ProductSerializer
|
||||
filterset_class = ProductFilter
|
||||
|
||||
filter_class = ProductFilter
|
||||
|
||||
def get_queryset(self):
|
||||
user = self.request.user
|
||||
return user.purchase_set.all()
|
||||
|
||||
---
|
||||
|
||||
# API Guide
|
||||
|
||||
## DjangoFilterBackend
|
||||
|
||||
The [`django-filter`][django-filter-docs] library includes a `DjangoFilterBackend` class which
|
||||
supports highly customizable field filtering for REST framework.
|
||||
|
||||
To use `DjangoFilterBackend`, first install `django-filter`.
|
||||
|
||||
pip install django-filter
|
||||
|
||||
Then add `'django_filters'` to Django's `INSTALLED_APPS`:
|
||||
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'django_filters',
|
||||
...
|
||||
]
|
||||
|
||||
You should now either add the filter backend to your settings:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
|
||||
}
|
||||
|
||||
Or add the filter backend to an individual View or ViewSet.
|
||||
|
||||
from django_filters.rest_framework import DjangoFilterBackend
|
||||
|
||||
class UserListView(generics.ListAPIView):
|
||||
...
|
||||
filter_backends = [DjangoFilterBackend]
|
||||
|
||||
If all you need is simple equality-based filtering, you can set a `filterset_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against.
|
||||
|
||||
class ProductList(generics.ListAPIView):
|
||||
queryset = Product.objects.all()
|
||||
serializer_class = ProductSerializer
|
||||
filter_backends = [DjangoFilterBackend]
|
||||
filterset_fields = ['category', 'in_stock']
|
||||
|
||||
This will automatically create a `FilterSet` class for the given fields, and will allow you to make requests such as:
|
||||
|
||||
http://example.com/api/products?category=clothing&in_stock=True
|
||||
|
||||
For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view.
|
||||
You can read more about `FilterSet`s in the [django-filter documentation][django-filter-docs].
|
||||
It's also recommended that you read the section on [DRF integration][django-filter-drf-docs].
|
||||
|
||||
|
||||
## SearchFilter
|
||||
|
||||
The `SearchFilter` class supports simple single query parameter based searching, and is based on the [Django admin's search functionality][search-django-admin].
|
||||
|
||||
When in use, the browsable API will include a `SearchFilter` control:
|
||||
|
||||

|
||||
|
||||
The `SearchFilter` class will only be applied if the view has a `search_fields` attribute set. The `search_fields` attribute should be a list of names of text type fields on the model, such as `CharField` or `TextField`.
|
||||
|
||||
from rest_framework import filters
|
||||
|
||||
class UserListView(generics.ListAPIView):
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
filter_backends = [filters.SearchFilter]
|
||||
search_fields = ['username', 'email']
|
||||
|
||||
This will allow the client to filter the items in the list by making queries such as:
|
||||
|
||||
http://example.com/api/users?search=russell
|
||||
|
||||
You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:
|
||||
|
||||
search_fields = ['username', 'email', 'profile__profession']
|
||||
|
||||
For [JSONField][JSONField] and [HStoreField][HStoreField] fields you can filter based on nested values within the data structure using the same double-underscore notation:
|
||||
|
||||
search_fields = ['data__breed', 'data__owner__other_pets__0__name']
|
||||
|
||||
By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. Searches may contain _quoted phrases_ with spaces, each phrase is considered as a single search term.
|
||||
|
||||
|
||||
The search behavior may be specified by prefixing field names in `search_fields` with one of the following characters (which is equivalent to adding `__<lookup>` to the field):
|
||||
|
||||
| Prefix | Lookup | |
|
||||
| ------ | --------------| ------------------ |
|
||||
| `^` | `istartswith` | Starts-with search.|
|
||||
| `=` | `iexact` | Exact matches. |
|
||||
| `$` | `iregex` | Regex search. |
|
||||
| `@` | `search` | Full-text search (Currently only supported Django's [PostgreSQL backend][postgres-search]). |
|
||||
| None | `icontains` | Contains search (Default). |
|
||||
|
||||
For example:
|
||||
|
||||
search_fields = ['=username', '=email']
|
||||
|
||||
By default, the search parameter is named `'search'`, but this may be overridden with the `SEARCH_PARAM` setting.
|
||||
|
||||
To dynamically change search fields based on request content, it's possible to subclass the `SearchFilter` and override the `get_search_fields()` function. For example, the following subclass will only search on `title` if the query parameter `title_only` is in the request:
|
||||
|
||||
from rest_framework import filters
|
||||
|
||||
class CustomSearchFilter(filters.SearchFilter):
|
||||
def get_search_fields(self, view, request):
|
||||
if request.query_params.get('title_only'):
|
||||
return ['title']
|
||||
return super().get_search_fields(view, request)
|
||||
|
||||
For more details, see the [Django documentation][search-django-admin].
|
||||
|
||||
---
|
||||
|
||||
## OrderingFilter
|
||||
|
||||
The `OrderingFilter` class supports simple query parameter controlled ordering of results.
|
||||
|
||||

|
||||
|
||||
By default, the query parameter is named `'ordering'`, but this may be overridden with the `ORDERING_PARAM` setting.
|
||||
|
||||
For example, to order users by username:
|
||||
|
||||
http://example.com/api/users?ordering=username
|
||||
|
||||
The client may also specify reverse orderings by prefixing the field name with '-', like so:
|
||||
|
||||
http://example.com/api/users?ordering=-username
|
||||
|
||||
Multiple orderings may also be specified:
|
||||
|
||||
http://example.com/api/users?ordering=account,username
|
||||
|
||||
### Specifying which fields may be ordered against
|
||||
|
||||
It's recommended that you explicitly specify which fields the API should allow in the ordering filter. You can do this by setting an `ordering_fields` attribute on the view, like so:
|
||||
|
||||
class UserListView(generics.ListAPIView):
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
filter_backends = [filters.OrderingFilter]
|
||||
ordering_fields = ['username', 'email']
|
||||
|
||||
This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data.
|
||||
|
||||
If you *don't* specify an `ordering_fields` attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the `serializer_class` attribute.
|
||||
|
||||
If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on *any* model field or queryset aggregate, by using the special value `'__all__'`.
|
||||
|
||||
class BookingsListView(generics.ListAPIView):
|
||||
queryset = Booking.objects.all()
|
||||
serializer_class = BookingSerializer
|
||||
filter_backends = [filters.OrderingFilter]
|
||||
ordering_fields = '__all__'
|
||||
|
||||
### Specifying a default ordering
|
||||
|
||||
If an `ordering` attribute is set on the view, this will be used as the default ordering.
|
||||
|
||||
Typically you'd instead control this by setting `order_by` on the initial queryset, but using the `ordering` parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results.
|
||||
|
||||
class UserListView(generics.ListAPIView):
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
filter_backends = [filters.OrderingFilter]
|
||||
ordering_fields = ['username', 'email']
|
||||
ordering = ['username']
|
||||
|
||||
The `ordering` attribute may be either a string or a list/tuple of strings.
|
||||
|
||||
---
|
||||
|
||||
# Custom generic filtering
|
||||
|
@ -316,57 +164,15 @@ You can also provide your own generic filtering backend, or write an installable
|
|||
|
||||
To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset.
|
||||
|
||||
As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user.
|
||||
To install the filter backend, set the `'FILTER_BACKEND'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class.
|
||||
|
||||
## Example
|
||||
For example:
|
||||
|
||||
For example, you might need to restrict users to only being able to see objects they created.
|
||||
REST_FRAMEWORK = {
|
||||
'FILTER_BACKEND': 'custom_filters.CustomFilterBackend'
|
||||
}
|
||||
|
||||
class IsOwnerFilterBackend(filters.BaseFilterBackend):
|
||||
"""
|
||||
Filter that only allows users to see their own objects.
|
||||
"""
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
return queryset.filter(owner=request.user)
|
||||
|
||||
We could achieve the same behavior by overriding `get_queryset()` on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.
|
||||
|
||||
## Customizing the interface
|
||||
|
||||
Generic filters may also present an interface in the browsable API. To do so you should implement a `to_html()` method which returns a rendered HTML representation of the filter. This method should have the following signature:
|
||||
|
||||
`to_html(self, request, queryset, view)`
|
||||
|
||||
The method should return a rendered HTML string.
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages provide additional filter implementations.
|
||||
|
||||
## Django REST framework filters package
|
||||
|
||||
The [django-rest-framework-filters package][django-rest-framework-filters] works together with the `DjangoFilterBackend` class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.
|
||||
|
||||
## Django REST framework full word search filter
|
||||
|
||||
The [djangorestframework-word-filter][django-rest-framework-word-search-filter] developed as alternative to `filters.SearchFilter` which will search full word in text, or exact match.
|
||||
|
||||
## Django URL Filter
|
||||
|
||||
[django-url-filter][django-url-filter] provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django `QuerySet`s.
|
||||
|
||||
## drf-url-filters
|
||||
|
||||
[drf-url-filter][drf-url-filter] is a simple Django app to apply filters on drf `ModelViewSet`'s `Queryset` in a clean, simple and configurable way. It also supports validations on incoming query params and their values. A beautiful python package `Voluptuous` is being used for validations on the incoming query parameters. The best part about voluptuous is you can define your own validations as per your query params requirements.
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/topics/db/queries/#retrieving-specific-objects-with-filters
|
||||
[django-filter-docs]: https://django-filter.readthedocs.io/en/latest/index.html
|
||||
[django-filter-drf-docs]: https://django-filter.readthedocs.io/en/latest/guide/rest_framework.html
|
||||
[search-django-admin]: https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields
|
||||
[django-rest-framework-filters]: https://github.com/philipn/django-rest-framework-filters
|
||||
[django-rest-framework-word-search-filter]: https://github.com/trollknurr/django-rest-framework-word-search-filter
|
||||
[django-url-filter]: https://github.com/miki725/django-url-filter
|
||||
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
|
||||
[HStoreField]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/fields/#hstorefield
|
||||
[JSONField]: https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.JSONField
|
||||
[postgres-search]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/search/
|
||||
[cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters
|
||||
[django-filter]: https://github.com/alex/django-filter
|
||||
[django-filter-docs]: https://django-filter.readthedocs.org/en/latest/index.html
|
||||
[nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py
|
|
@ -1,7 +1,4 @@
|
|||
---
|
||||
source:
|
||||
- urlpatterns.py
|
||||
---
|
||||
<a class="github" href="urlpatterns.py"></a>
|
||||
|
||||
# Format suffixes
|
||||
|
||||
|
@ -10,7 +7,7 @@ used all the time.
|
|||
>
|
||||
> — Roy Fielding, [REST discuss mailing list][cite]
|
||||
|
||||
A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation.
|
||||
A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation.
|
||||
|
||||
Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf.
|
||||
|
||||
|
@ -23,74 +20,42 @@ 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:
|
||||
|
||||
from rest_framework.urlpatterns import format_suffix_patterns
|
||||
from blog import views
|
||||
|
||||
urlpatterns = [
|
||||
path('', views.apt_root),
|
||||
path('comments/', views.comment_list),
|
||||
path('comments/<int:pk>/', views.comment_detail)
|
||||
]
|
||||
|
||||
|
||||
urlpatterns = patterns('blog.views',
|
||||
url(r'^/$', 'api_root'),
|
||||
url(r'^comment/$', 'comment_root'),
|
||||
url(r'^comment/(?P<pk>[0-9]+)/$', 'comment_instance')
|
||||
)
|
||||
|
||||
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
|
||||
|
||||
When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example:
|
||||
When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example.
|
||||
|
||||
@api_view(['GET', 'POST'])
|
||||
def comment_list(request, format=None):
|
||||
@api_view(('GET',))
|
||||
def api_root(request, format=None):
|
||||
# do stuff...
|
||||
|
||||
Or with class-based views:
|
||||
|
||||
class CommentList(APIView):
|
||||
def get(self, request, format=None):
|
||||
# do stuff...
|
||||
|
||||
def post(self, request, format=None):
|
||||
# do stuff...
|
||||
|
||||
The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` setting.
|
||||
|
||||
Also note that `format_suffix_patterns` does not support descending into `include` URL patterns.
|
||||
|
||||
### Using with `i18n_patterns`
|
||||
|
||||
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:
|
||||
|
||||
urlpatterns = [
|
||||
…
|
||||
]
|
||||
|
||||
urlpatterns = i18n_patterns(
|
||||
format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
|
||||
)
|
||||
|
||||
---
|
||||
|
||||
## Query parameter formats
|
||||
|
||||
An alternative to the format suffixes is to include the requested format in a query parameter. REST framework provides this option by default, and it is used in the browsable API to switch between differing available representations.
|
||||
|
||||
To select a representation using its short format, use the `format` query parameter. For example: `http://example.com/organizations/?format=csv`.
|
||||
|
||||
The name of this query parameter can be modified using the `URL_FORMAT_OVERRIDE` setting. Set the value to `None` to disable this behavior.
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Accept headers vs. format suffixes
|
||||
|
||||
There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead.
|
||||
There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead.
|
||||
|
||||
It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators:
|
||||
It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators:
|
||||
|
||||
“That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, [REST discuss mailing list][cite2]
|
||||
“That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, [REST discuss mailing list][cite2]
|
||||
|
||||
The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern.
|
||||
|
||||
[cite]: http://tech.groups.yahoo.com/group/rest-discuss/message/5857
|
||||
[cite2]: https://groups.yahoo.com/neo/groups/rest-discuss/conversations/topics/14844
|
||||
[cite2]: http://tech.groups.yahoo.com/group/rest-discuss/message/14844
|
|
@ -1,8 +1,5 @@
|
|||
---
|
||||
source:
|
||||
- mixins.py
|
||||
- generics.py
|
||||
---
|
||||
<a class="github" href="mixins.py"></a>
|
||||
<a class="github" href="generics.py"></a>
|
||||
|
||||
# Generic views
|
||||
|
||||
|
@ -10,7 +7,7 @@ source:
|
|||
>
|
||||
> — [Django Documentation][cite]
|
||||
|
||||
One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
|
||||
One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
|
||||
|
||||
The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
|
||||
|
||||
|
@ -20,234 +17,43 @@ If the generic views don't suit the needs of your API, you can drop down to usin
|
|||
|
||||
Typically when using the generic views, you'll override the view, and set several class attributes.
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from myapp.serializers import UserSerializer
|
||||
from rest_framework import generics
|
||||
from rest_framework.permissions import IsAdminUser
|
||||
|
||||
class UserList(generics.ListCreateAPIView):
|
||||
queryset = User.objects.all()
|
||||
model = User
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = [IsAdminUser]
|
||||
permission_classes = (IsAdminUser,)
|
||||
paginate_by = 100
|
||||
|
||||
For more complex cases you might also want to override various methods on the view class. For example.
|
||||
|
||||
class UserList(generics.ListCreateAPIView):
|
||||
queryset = User.objects.all()
|
||||
model = User
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = [IsAdminUser]
|
||||
permission_classes = (IsAdminUser,)
|
||||
|
||||
def list(self, request):
|
||||
# Note the use of `get_queryset()` instead of `self.queryset`
|
||||
queryset = self.get_queryset()
|
||||
serializer = UserSerializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
def get_paginate_by(self, queryset):
|
||||
"""
|
||||
Use smaller pagination for HTML representations.
|
||||
"""
|
||||
page_size_param = self.request.QUERY_PARAMS.get('page_size')
|
||||
if page_size_param:
|
||||
return int(page_size_param)
|
||||
return 100
|
||||
|
||||
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something like the following entry:
|
||||
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something the following entry.
|
||||
|
||||
path('users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
|
||||
url(r'^/users/', ListCreateAPIView.as_view(model=User) name='user-list')
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## GenericAPIView
|
||||
|
||||
This class extends REST framework's `APIView` class, adding commonly required behavior for standard list and detail views.
|
||||
|
||||
Each of the concrete generic views provided is built by combining `GenericAPIView`, with one or more mixin classes.
|
||||
|
||||
### Attributes
|
||||
|
||||
**Basic settings**:
|
||||
|
||||
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 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**:
|
||||
|
||||
The following attributes are used to control pagination when used with list views.
|
||||
|
||||
* `pagination_class` - The pagination class that should be used when paginating list results. Defaults to the same value as the `DEFAULT_PAGINATION_CLASS` setting, which is `'rest_framework.pagination.PageNumberPagination'`. Setting `pagination_class=None` will disable pagination on this view.
|
||||
|
||||
**Filtering**:
|
||||
|
||||
* `filter_backends` - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the `DEFAULT_FILTER_BACKENDS` setting.
|
||||
|
||||
### Methods
|
||||
|
||||
**Base methods**:
|
||||
|
||||
#### `get_queryset(self)`
|
||||
|
||||
Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the `queryset` attribute.
|
||||
|
||||
This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests.
|
||||
|
||||
May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.
|
||||
|
||||
For example:
|
||||
|
||||
def get_queryset(self):
|
||||
user = self.request.user
|
||||
return user.accounts.all()
|
||||
|
||||
---
|
||||
|
||||
**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].
|
||||
|
||||
---
|
||||
|
||||
#### `get_object(self)`
|
||||
|
||||
Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.
|
||||
|
||||
May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.
|
||||
|
||||
For example:
|
||||
|
||||
def get_object(self):
|
||||
queryset = self.get_queryset()
|
||||
filter = {}
|
||||
for field in self.multiple_lookup_fields:
|
||||
filter[field] = self.kwargs[field]
|
||||
|
||||
obj = get_object_or_404(queryset, **filter)
|
||||
self.check_object_permissions(self.request, obj)
|
||||
return obj
|
||||
|
||||
Note that if your API doesn't include any object level permissions, you may optionally exclude the `self.check_object_permissions`, and simply return the object from the `get_object_or_404` lookup.
|
||||
|
||||
#### `filter_queryset(self, queryset)`
|
||||
|
||||
Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
|
||||
|
||||
For example:
|
||||
|
||||
def filter_queryset(self, queryset):
|
||||
filter_backends = [CategoryFilter]
|
||||
|
||||
if 'geo_route' in self.request.query_params:
|
||||
filter_backends = [GeoRouteFilter, CategoryFilter]
|
||||
elif 'geo_point' in self.request.query_params:
|
||||
filter_backends = [GeoPointFilter, CategoryFilter]
|
||||
|
||||
for backend in list(filter_backends):
|
||||
queryset = backend().filter_queryset(self.request, queryset, view=self)
|
||||
|
||||
return queryset
|
||||
|
||||
#### `get_serializer_class(self)`
|
||||
|
||||
Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute.
|
||||
|
||||
May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.
|
||||
|
||||
For example:
|
||||
|
||||
def get_serializer_class(self):
|
||||
if self.request.user.is_staff:
|
||||
return FullAccountSerializer
|
||||
return BasicAccountSerializer
|
||||
|
||||
**Save and deletion hooks**:
|
||||
|
||||
The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
|
||||
|
||||
* `perform_create(self, serializer)` - Called by `CreateModelMixin` when saving a new object instance.
|
||||
* `perform_update(self, serializer)` - Called by `UpdateModelMixin` when saving an existing object instance.
|
||||
* `perform_destroy(self, instance)` - Called by `DestroyModelMixin` when deleting an object instance.
|
||||
|
||||
These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.
|
||||
|
||||
def perform_create(self, serializer):
|
||||
serializer.save(user=self.request.user)
|
||||
|
||||
These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.
|
||||
|
||||
def perform_update(self, serializer):
|
||||
instance = serializer.save()
|
||||
send_email_confirmation(user=self.request.user, modified=instance)
|
||||
|
||||
You can also use these hooks to provide additional validation, by raising a `ValidationError()`. This can be useful if you need some validation logic to apply at the point of database save. For example:
|
||||
|
||||
def perform_create(self, serializer):
|
||||
queryset = SignupRequest.objects.filter(user=self.request.user)
|
||||
if queryset.exists():
|
||||
raise ValidationError('You have already signed up')
|
||||
serializer.save(user=self.request.user)
|
||||
|
||||
**Other methods**:
|
||||
|
||||
You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`.
|
||||
|
||||
* `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys.
|
||||
* `get_serializer(self, instance=None, data=None, many=False, partial=False)` - Returns a serializer instance.
|
||||
* `get_paginated_response(self, data)` - Returns a paginated style `Response` object.
|
||||
* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view.
|
||||
* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
|
||||
|
||||
---
|
||||
|
||||
# Mixins
|
||||
|
||||
The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as `.get()` and `.post()`, directly. This allows for more flexible composition of behavior.
|
||||
|
||||
The mixin classes can be imported from `rest_framework.mixins`.
|
||||
|
||||
## ListModelMixin
|
||||
|
||||
Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
|
||||
|
||||
If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.
|
||||
|
||||
## CreateModelMixin
|
||||
|
||||
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
|
||||
|
||||
If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value.
|
||||
|
||||
If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
|
||||
|
||||
## RetrieveModelMixin
|
||||
|
||||
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`.
|
||||
|
||||
## UpdateModelMixin
|
||||
|
||||
Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
|
||||
|
||||
Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests.
|
||||
|
||||
If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response.
|
||||
|
||||
If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
|
||||
|
||||
## DestroyModelMixin
|
||||
|
||||
Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance.
|
||||
|
||||
If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`.
|
||||
|
||||
---
|
||||
|
||||
# Concrete View Classes
|
||||
|
||||
The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.
|
||||
|
||||
The view classes can be imported from `rest_framework.generics`.
|
||||
|
||||
## CreateAPIView
|
||||
|
||||
Used for **create-only** endpoints.
|
||||
|
||||
Provides a `post` method handler.
|
||||
Provides `post` method handlers.
|
||||
|
||||
Extends: [GenericAPIView], [CreateModelMixin]
|
||||
|
||||
|
@ -257,7 +63,7 @@ Used for **read-only** endpoints to represent a **collection of model instances*
|
|||
|
||||
Provides a `get` method handler.
|
||||
|
||||
Extends: [GenericAPIView], [ListModelMixin]
|
||||
Extends: [MultipleObjectAPIView], [ListModelMixin]
|
||||
|
||||
## RetrieveAPIView
|
||||
|
||||
|
@ -265,7 +71,7 @@ Used for **read-only** endpoints to represent a **single model instance**.
|
|||
|
||||
Provides a `get` method handler.
|
||||
|
||||
Extends: [GenericAPIView], [RetrieveModelMixin]
|
||||
Extends: [SingleObjectAPIView], [RetrieveModelMixin]
|
||||
|
||||
## DestroyAPIView
|
||||
|
||||
|
@ -273,7 +79,7 @@ Used for **delete-only** endpoints for a **single model instance**.
|
|||
|
||||
Provides a `delete` method handler.
|
||||
|
||||
Extends: [GenericAPIView], [DestroyModelMixin]
|
||||
Extends: [SingleObjectAPIView], [DestroyModelMixin]
|
||||
|
||||
## UpdateAPIView
|
||||
|
||||
|
@ -281,7 +87,7 @@ Used for **update-only** endpoints for a **single model instance**.
|
|||
|
||||
Provides `put` and `patch` method handlers.
|
||||
|
||||
Extends: [GenericAPIView], [UpdateModelMixin]
|
||||
Extends: [SingleObjectAPIView], [UpdateModelMixin]
|
||||
|
||||
## ListCreateAPIView
|
||||
|
||||
|
@ -289,7 +95,7 @@ Used for **read-write** endpoints to represent a **collection of model instances
|
|||
|
||||
Provides `get` and `post` method handlers.
|
||||
|
||||
Extends: [GenericAPIView], [ListModelMixin], [CreateModelMixin]
|
||||
Extends: [MultipleObjectAPIView], [ListModelMixin], [CreateModelMixin]
|
||||
|
||||
## RetrieveUpdateAPIView
|
||||
|
||||
|
@ -297,7 +103,7 @@ Used for **read or update** endpoints to represent a **single model instance**.
|
|||
|
||||
Provides `get`, `put` and `patch` method handlers.
|
||||
|
||||
Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin]
|
||||
Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin]
|
||||
|
||||
## RetrieveDestroyAPIView
|
||||
|
||||
|
@ -305,7 +111,7 @@ Used for **read or delete** endpoints to represent a **single model instance**.
|
|||
|
||||
Provides `get` and `delete` method handlers.
|
||||
|
||||
Extends: [GenericAPIView], [RetrieveModelMixin], [DestroyModelMixin]
|
||||
Extends: [SingleObjectAPIView], [RetrieveModelMixin], [DestroyModelMixin]
|
||||
|
||||
## RetrieveUpdateDestroyAPIView
|
||||
|
||||
|
@ -313,86 +119,115 @@ Used for **read-write-delete** endpoints to represent a **single model instance*
|
|||
|
||||
Provides `get`, `put`, `patch` and `delete` method handlers.
|
||||
|
||||
Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin]
|
||||
Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin]
|
||||
|
||||
---
|
||||
|
||||
# Customizing the generic views
|
||||
# Base views
|
||||
|
||||
Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.
|
||||
Each of the generic views provided is built by combining one of the base views below, with one or more mixin classes.
|
||||
|
||||
## Creating custom mixins
|
||||
## GenericAPIView
|
||||
|
||||
For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:
|
||||
Extends REST framework's `APIView` class, adding support for serialization of model instances and model querysets.
|
||||
|
||||
class MultipleFieldLookupMixin:
|
||||
"""
|
||||
Apply this mixin to any view or viewset to get multiple field filtering
|
||||
based on a `lookup_fields` attribute, instead of the default single field filtering.
|
||||
"""
|
||||
def get_object(self):
|
||||
queryset = self.get_queryset() # Get the base queryset
|
||||
queryset = self.filter_queryset(queryset) # Apply any filter backends
|
||||
filter = {}
|
||||
for field in self.lookup_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)
|
||||
return obj
|
||||
**Attributes**:
|
||||
|
||||
You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.
|
||||
* `model` - The model that should be used for this view. Used as a fallback for determining the serializer if `serializer_class` is not set, and as a fallback for determining the queryset if `queryset` is not set. Otherwise not required.
|
||||
* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. If unset, this defaults to creating a serializer class using `self.model`, with the `DEFAULT_MODEL_SERIALIZER_CLASS` setting as the base serializer class.
|
||||
|
||||
class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
lookup_fields = ['account', 'username']
|
||||
## MultipleObjectAPIView
|
||||
|
||||
Using custom mixins is a good option if you have custom behavior that needs to be used.
|
||||
Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [MultipleObjectMixin].
|
||||
|
||||
## Creating custom base classes
|
||||
**See also:** ccbv.co.uk documentation for [MultipleObjectMixin][multiple-object-mixin-classy].
|
||||
|
||||
If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:
|
||||
**Attributes**:
|
||||
|
||||
class BaseRetrieveView(MultipleFieldLookupMixin,
|
||||
generics.RetrieveAPIView):
|
||||
pass
|
||||
* `queryset` - The queryset that should be used for returning objects from this view. If unset, defaults to the default queryset manager for `self.model`.
|
||||
* `paginate_by` - The size of pages to use with paginated data. If set to `None` then pagination is turned off. If unset this uses the same value as the `PAGINATE_BY` setting, which defaults to `None`.
|
||||
* `paginate_by_param` - The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`.
|
||||
|
||||
class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
|
||||
generics.RetrieveUpdateDestroyAPIView):
|
||||
pass
|
||||
## SingleObjectAPIView
|
||||
|
||||
Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.
|
||||
Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [SingleObjectMixin].
|
||||
|
||||
**See also:** ccbv.co.uk documentation for [SingleObjectMixin][single-object-mixin-classy].
|
||||
|
||||
**Attributes**:
|
||||
|
||||
* `queryset` - The queryset that should be used when retrieving an object from this view. If unset, defaults to the default queryset manager for `self.model`.
|
||||
* `pk_kwarg` - The URL kwarg that should be used to look up objects by primary key. Defaults to `'pk'`. [Can only be set to non-default on Django 1.4+]
|
||||
* `slug_url_kwarg` - The URL kwarg that should be used to look up objects by a slug. Defaults to `'slug'`. [Can only be set to non-default on Django 1.4+]
|
||||
* `slug_field` - The field on the model that should be used to look up objects by a slug. If used, this should typically be set to a field with `unique=True`. Defaults to `'slug'`.
|
||||
|
||||
---
|
||||
|
||||
# PUT as create
|
||||
# Mixins
|
||||
|
||||
Prior to version 3.0 the REST framework mixins treated `PUT` as either an update or a create operation, depending on if the object already existed or not.
|
||||
The mixin classes provide the actions that are used to provide the basic view behaviour. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behaviour.
|
||||
|
||||
Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses.
|
||||
## ListModelMixin
|
||||
|
||||
Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.
|
||||
Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
|
||||
|
||||
If you need to generic PUT-as-create behavior you may want to include something like [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views.
|
||||
If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.
|
||||
|
||||
---
|
||||
If the queryset is empty this returns a `200 OK` reponse, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`.
|
||||
|
||||
# Third party packages
|
||||
Should be mixed in with [MultipleObjectAPIView].
|
||||
|
||||
The following third party packages provide additional generic view implementations.
|
||||
## CreateModelMixin
|
||||
|
||||
## Django Rest Multiple Models
|
||||
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
|
||||
|
||||
[Django Rest Multiple Models][django-rest-multiple-models] provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
|
||||
If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value.
|
||||
|
||||
If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
|
||||
|
||||
Should be mixed in with any [GenericAPIView].
|
||||
|
||||
## RetrieveModelMixin
|
||||
|
||||
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
|
||||
|
||||
If an object can be retrieve 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`.
|
||||
|
||||
Should be mixed in with [SingleObjectAPIView].
|
||||
|
||||
## UpdateModelMixin
|
||||
|
||||
Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
|
||||
|
||||
If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response.
|
||||
|
||||
If an object is created, for example when making a `DELETE` request followed by a `PUT` request to the same URL, this returns a `201 Created` response, with a serialized representation of the object as the body of the response.
|
||||
|
||||
If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
|
||||
|
||||
A boolean `partial` keyword argument may be supplied to the `.update()` method. If `partial` is set to `True`, all fields for the update will be optional. This allows support for HTTP `PATCH` requests.
|
||||
|
||||
Should be mixed in with [SingleObjectAPIView].
|
||||
|
||||
## DestroyModelMixin
|
||||
|
||||
Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance.
|
||||
|
||||
If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`.
|
||||
|
||||
Should be mixed in with [SingleObjectAPIView].
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views
|
||||
[MultipleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-multiple-object/
|
||||
[SingleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-single-object/
|
||||
[multiple-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.list/MultipleObjectMixin/
|
||||
[single-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.detail/SingleObjectMixin/
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/ref/class-based-views/#base-vs-generic-views
|
||||
[GenericAPIView]: #genericapiview
|
||||
[SingleObjectAPIView]: #singleobjectapiview
|
||||
[MultipleObjectAPIView]: #multipleobjectapiview
|
||||
[ListModelMixin]: #listmodelmixin
|
||||
[CreateModelMixin]: #createmodelmixin
|
||||
[RetrieveModelMixin]: #retrievemodelmixin
|
||||
[UpdateModelMixin]: #updatemodelmixin
|
||||
[DestroyModelMixin]: #destroymodelmixin
|
||||
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
|
||||
[django-docs-select-related]: https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related
|
||||
|
|
|
@ -1,124 +0,0 @@
|
|||
---
|
||||
source:
|
||||
- metadata.py
|
||||
---
|
||||
|
||||
# Metadata
|
||||
|
||||
> [The `OPTIONS`] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.
|
||||
>
|
||||
> — [RFC7231, Section 4.3.7.][cite]
|
||||
|
||||
REST framework includes a configurable mechanism for determining how your API should respond to `OPTIONS` requests. This allows you to return API schema or other resource information.
|
||||
|
||||
There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP `OPTIONS` requests, so we provide an ad-hoc style that returns some useful information.
|
||||
|
||||
Here's an example response that demonstrates the information that is returned by default.
|
||||
|
||||
HTTP 200 OK
|
||||
Allow: GET, POST, HEAD, OPTIONS
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "To Do List",
|
||||
"description": "List existing 'To Do' items, or create a new item.",
|
||||
"renders": [
|
||||
"application/json",
|
||||
"text/html"
|
||||
],
|
||||
"parses": [
|
||||
"application/json",
|
||||
"application/x-www-form-urlencoded",
|
||||
"multipart/form-data"
|
||||
],
|
||||
"actions": {
|
||||
"POST": {
|
||||
"note": {
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"read_only": false,
|
||||
"label": "title",
|
||||
"max_length": 100
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
## Setting the metadata scheme
|
||||
|
||||
You can set the metadata class globally using the `'DEFAULT_METADATA_CLASS'` settings key:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata'
|
||||
}
|
||||
|
||||
Or you can set the metadata class individually for a view:
|
||||
|
||||
class APIRoot(APIView):
|
||||
metadata_class = APIRootMetadata
|
||||
|
||||
def get(self, request, format=None):
|
||||
return Response({
|
||||
...
|
||||
})
|
||||
|
||||
The REST framework package only includes a single metadata class implementation, named `SimpleMetadata`. If you want to use an alternative style you'll need to implement a custom metadata class.
|
||||
|
||||
## Creating schema endpoints
|
||||
|
||||
If you have specific requirements for creating schema endpoints that are accessed with regular `GET` requests, you might consider re-using the metadata API for doing so.
|
||||
|
||||
For example, the following additional route could be used on a viewset to provide a linkable schema endpoint.
|
||||
|
||||
@action(methods=['GET'], detail=False)
|
||||
def api_schema(self, request):
|
||||
meta = self.metadata_class()
|
||||
data = meta.determine_metadata(request, self)
|
||||
return Response(data)
|
||||
|
||||
There are a couple of reasons that you might choose to take this approach, including that `OPTIONS` responses [are not cacheable][no-options].
|
||||
|
||||
---
|
||||
|
||||
# Custom metadata classes
|
||||
|
||||
If you want to provide a custom metadata class you should override `BaseMetadata` and implement the `determine_metadata(self, request, view)` method.
|
||||
|
||||
Useful things that you might want to do could include returning schema information, using a format such as [JSON schema][json-schema], or returning debug information to admin users.
|
||||
|
||||
## Example
|
||||
|
||||
The following class could be used to limit the information that is returned to `OPTIONS` requests.
|
||||
|
||||
class MinimalMetadata(BaseMetadata):
|
||||
"""
|
||||
Don't include field and other information for `OPTIONS` requests.
|
||||
Just return the name and description.
|
||||
"""
|
||||
def determine_metadata(self, request, view):
|
||||
return {
|
||||
'name': view.get_view_name(),
|
||||
'description': view.get_view_description()
|
||||
}
|
||||
|
||||
Then configure your settings to use this custom class:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_METADATA_CLASS': 'myproject.apps.core.MinimalMetadata'
|
||||
}
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages provide additional metadata implementations.
|
||||
|
||||
## DRF-schema-adapter
|
||||
|
||||
[drf-schema-adapter][drf-schema-adapter] is a set of tools that makes it easier to provide schema information to frontend frameworks and libraries. It provides a metadata mixin as well as 2 metadata classes and several adapters suitable to generate [json-schema][json-schema] as well as schema information readable by various libraries.
|
||||
|
||||
You can also write your own adapter to work with your specific frontend.
|
||||
If you wish to do so, it also provides an exporter that can export those schema information to json files.
|
||||
|
||||
[cite]: https://tools.ietf.org/html/rfc7231#section-4.3.7
|
||||
[no-options]: https://www.mnot.net/blog/2012/10/29/NO_OPTIONS
|
||||
[json-schema]: https://json-schema.org/
|
||||
[drf-schema-adapter]: https://github.com/drf-forms/drf-schema-adapter
|
|
@ -1,7 +1,4 @@
|
|||
---
|
||||
source:
|
||||
- pagination.py
|
||||
---
|
||||
<a class="github" href="pagination.py"></a>
|
||||
|
||||
# Pagination
|
||||
|
||||
|
@ -9,308 +6,135 @@ source:
|
|||
>
|
||||
> — [Django documentation][cite]
|
||||
|
||||
REST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data.
|
||||
REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types.
|
||||
|
||||
The pagination API can support either:
|
||||
## Paginating basic data
|
||||
|
||||
* Pagination links that are provided as part of the content of the response.
|
||||
* Pagination links that are included in response headers, such as `Content-Range` or `Link`.
|
||||
Let's start by taking a look at an example from the Django documentation.
|
||||
|
||||
The built-in styles currently all use links included as part of the content of the response. This style is more accessible when using the browsable API.
|
||||
from django.core.paginator import Paginator
|
||||
objects = ['john', 'paul', 'george', 'ringo']
|
||||
paginator = Paginator(objects, 2)
|
||||
page = paginator.page(1)
|
||||
page.object_list
|
||||
# ['john', 'paul']
|
||||
|
||||
Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular `APIView`, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the `mixins.ListModelMixin` and `generics.GenericAPIView` classes for an example.
|
||||
At this point we've got a page object. If we wanted to return this page object as a JSON response, we'd need to provide the client with context such as next and previous links, so that it would be able to page through the remaining results.
|
||||
|
||||
Pagination can be turned off by setting the pagination class to `None`.
|
||||
from rest_framework.pagination import PaginationSerializer
|
||||
serializer = PaginationSerializer(instance=page)
|
||||
serializer.data
|
||||
# {'count': 4, 'next': '?page=2', 'previous': None, 'results': [u'john', u'paul']}
|
||||
|
||||
## Setting the pagination style
|
||||
The `context` argument of the `PaginationSerializer` class may optionally include the request. If the request is included in the context then the next and previous links returned by the serializer will use absolute URLs instead of relative URLs.
|
||||
|
||||
The pagination style may be set globally, using the `DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` setting keys. For example, to use the built-in limit/offset pagination, you would do something like this:
|
||||
request = RequestFactory().get('/foobar')
|
||||
serializer = PaginationSerializer(instance=page, context={'request': request})
|
||||
serializer.data
|
||||
# {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']}
|
||||
|
||||
We could now return that data in a `Response` object, and it would be rendered into the correct media type.
|
||||
|
||||
## Paginating QuerySets
|
||||
|
||||
Our first example worked because we were using primative objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself with.
|
||||
|
||||
We can do this using the `object_serializer_class` attribute on the inner `Meta` class of the pagination serializer. For example.
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer):
|
||||
"""
|
||||
Serializes user querysets.
|
||||
"""
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ('username', 'email')
|
||||
|
||||
class PaginatedUserSerializer(pagination.PaginationSerializer):
|
||||
"""
|
||||
Serializes page objects of user querysets.
|
||||
"""
|
||||
class Meta:
|
||||
object_serializer_class = UserSerializer
|
||||
|
||||
We could now use our pagination serializer in a view like this.
|
||||
|
||||
@api_view('GET')
|
||||
def user_list(request):
|
||||
queryset = User.objects.all()
|
||||
paginator = Paginator(queryset, 20)
|
||||
|
||||
page = request.QUERY_PARAMS.get('page')
|
||||
try:
|
||||
users = paginator.page(page)
|
||||
except PageNotAnInteger:
|
||||
# If page is not an integer, deliver first page.
|
||||
users = paginator.page(1)
|
||||
except EmptyPage:
|
||||
# If page is out of range (e.g. 9999),
|
||||
# deliver last page of results.
|
||||
users = paginator.page(paginator.num_pages)
|
||||
|
||||
serializer_context = {'request': request}
|
||||
serializer = PaginatedUserSerializer(users,
|
||||
context=serializer_context)
|
||||
return Response(serializer.data)
|
||||
|
||||
## Pagination in the generic views
|
||||
|
||||
The generic class based views `ListAPIView` and `ListCreateAPIView` provide pagination of the returned querysets by default. You can customise this behaviour by altering the pagination style, by modifying the default number of results, by allowing clients to override the page size using a query parameter, or by turning pagination off completely.
|
||||
|
||||
The default pagination style may be set globally, using the `DEFAULT_PAGINATION_SERIALIZER_CLASS`, `PAGINATE_BY` and `PAGINATE_BY_PARAM` settings. For example.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
|
||||
'PAGE_SIZE': 100
|
||||
'PAGINATE_BY': 10,
|
||||
'PAGINATE_BY_PARAM': 'page_size'
|
||||
}
|
||||
|
||||
Note that you need to set both the pagination class, and the page size that should be used. Both `DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` are `None` by default.
|
||||
You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view.
|
||||
|
||||
You can also set the pagination class on an individual view by using the `pagination_class` attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis.
|
||||
class PaginatedListView(ListAPIView):
|
||||
model = ExampleModel
|
||||
paginate_by = 10
|
||||
paginate_by_param = 'page_size'
|
||||
|
||||
## Modifying the pagination style
|
||||
|
||||
If you want to modify particular aspects of the pagination style, you'll want to override one of the pagination classes, and set the attributes that you want to change.
|
||||
|
||||
class LargeResultsSetPagination(PageNumberPagination):
|
||||
page_size = 1000
|
||||
page_size_query_param = 'page_size'
|
||||
max_page_size = 10000
|
||||
|
||||
class StandardResultsSetPagination(PageNumberPagination):
|
||||
page_size = 100
|
||||
page_size_query_param = 'page_size'
|
||||
max_page_size = 1000
|
||||
|
||||
You can then apply your new style to a view using the `pagination_class` attribute:
|
||||
|
||||
class BillingRecordsView(generics.ListAPIView):
|
||||
queryset = Billing.objects.all()
|
||||
serializer_class = BillingRecordsSerializer
|
||||
pagination_class = LargeResultsSetPagination
|
||||
|
||||
Or apply the style globally, using the `DEFAULT_PAGINATION_CLASS` settings key. For example:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination'
|
||||
}
|
||||
For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods.
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
# Custom pagination serializers
|
||||
|
||||
## PageNumberPagination
|
||||
To create a custom pagination serializer class you should override `pagination.BasePaginationSerializer` and set the fields that you want the serializer to return.
|
||||
|
||||
This pagination style accepts a single number page number in the request query parameters.
|
||||
|
||||
**Request**:
|
||||
|
||||
GET https://api.example.org/accounts/?page=4
|
||||
|
||||
**Response**:
|
||||
|
||||
HTTP 200 OK
|
||||
{
|
||||
"count": 1023,
|
||||
"next": "https://api.example.org/accounts/?page=5",
|
||||
"previous": "https://api.example.org/accounts/?page=3",
|
||||
"results": [
|
||||
…
|
||||
]
|
||||
}
|
||||
|
||||
#### Setup
|
||||
|
||||
To enable the `PageNumberPagination` style globally, use the following configuration, and set the `PAGE_SIZE` as desired:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
|
||||
'PAGE_SIZE': 100
|
||||
}
|
||||
|
||||
On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `PageNumberPagination` on a per-view basis.
|
||||
|
||||
#### Configuration
|
||||
|
||||
The `PageNumberPagination` class includes a number of attributes that may be overridden to modify the pagination style.
|
||||
|
||||
To set these attributes you should override the `PageNumberPagination` class, and then enable your custom pagination class as above.
|
||||
|
||||
* `django_paginator_class` - The Django Paginator class to use. Default is `django.core.paginator.Paginator`, which should be fine for most use cases.
|
||||
* `page_size` - A numeric value indicating the page size. If set, this overrides the `PAGE_SIZE` setting. Defaults to the same value as the `PAGE_SIZE` settings key.
|
||||
* `page_query_param` - A string value indicating the name of the query parameter to use for the pagination control.
|
||||
* `page_size_query_param` - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to `None`, indicating that the client may not control the requested page size.
|
||||
* `max_page_size` - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if `page_size_query_param` is also set.
|
||||
* `last_page_strings` - A list or tuple of string values indicating values that may be used with the `page_query_param` to request the final page in the set. Defaults to `('last',)`
|
||||
* `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`.
|
||||
|
||||
---
|
||||
|
||||
## LimitOffsetPagination
|
||||
|
||||
This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an
|
||||
"offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the `page_size` in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items.
|
||||
|
||||
**Request**:
|
||||
|
||||
GET https://api.example.org/accounts/?limit=100&offset=400
|
||||
|
||||
**Response**:
|
||||
|
||||
HTTP 200 OK
|
||||
{
|
||||
"count": 1023,
|
||||
"next": "https://api.example.org/accounts/?limit=100&offset=500",
|
||||
"previous": "https://api.example.org/accounts/?limit=100&offset=300",
|
||||
"results": [
|
||||
…
|
||||
]
|
||||
}
|
||||
|
||||
#### Setup
|
||||
|
||||
To enable the `LimitOffsetPagination` style globally, use the following configuration:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'
|
||||
}
|
||||
|
||||
Optionally, you may also set a `PAGE_SIZE` key. If the `PAGE_SIZE` parameter is also used then the `limit` query parameter will be optional, and may be omitted by the client.
|
||||
|
||||
On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `LimitOffsetPagination` on a per-view basis.
|
||||
|
||||
#### Configuration
|
||||
|
||||
The `LimitOffsetPagination` class includes a number of attributes that may be overridden to modify the pagination style.
|
||||
|
||||
To set these attributes you should override the `LimitOffsetPagination` class, and then enable your custom pagination class as above.
|
||||
|
||||
* `default_limit` - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the `PAGE_SIZE` settings key.
|
||||
* `limit_query_param` - A string value indicating the name of the "limit" query parameter. Defaults to `'limit'`.
|
||||
* `offset_query_param` - A string value indicating the name of the "offset" query parameter. Defaults to `'offset'`.
|
||||
* `max_limit` - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to `None`.
|
||||
* `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`.
|
||||
|
||||
---
|
||||
|
||||
## CursorPagination
|
||||
|
||||
The cursor-based pagination presents an opaque "cursor" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions.
|
||||
|
||||
Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against.
|
||||
|
||||
Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits:
|
||||
|
||||
* Provides a consistent pagination view. When used properly `CursorPagination` ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process.
|
||||
* Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases.
|
||||
|
||||
#### Details and limitations
|
||||
|
||||
Proper use of cursor based pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by `"-created"`. This assumes that **there must be a 'created' timestamp field** on the model instances, and will present a "timeline" style paginated view, with the most recently added items first.
|
||||
|
||||
You can modify the ordering by overriding the `'ordering'` attribute on the pagination class, or by using the `OrderingFilter` filter class together with `CursorPagination`. When used with `OrderingFilter` you should strongly consider restricting the fields that the user may order by.
|
||||
|
||||
Proper usage of cursor pagination should have an ordering field that satisfies the following:
|
||||
|
||||
* Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation.
|
||||
* Should be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart "position plus offset" style that allows it to properly support not-strictly-unique values as the ordering.
|
||||
* Should be a non-nullable value that can be coerced to a string.
|
||||
* Should not be a float. Precision errors easily lead to incorrect results.
|
||||
Hint: use decimals instead.
|
||||
(If you already have a float field and must paginate on that, an
|
||||
[example `CursorPagination` subclass that uses decimals to limit precision is available here][float_cursor_pagination_example].)
|
||||
* The field should have a database index.
|
||||
|
||||
Using an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination.
|
||||
|
||||
For more technical details on the implementation we use for cursor pagination, the ["Building cursors for the Disqus API"][disqus-cursor-api] blog post gives a good overview of the basic approach.
|
||||
|
||||
#### Setup
|
||||
|
||||
To enable the `CursorPagination` style globally, use the following configuration, modifying the `PAGE_SIZE` as desired:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',
|
||||
'PAGE_SIZE': 100
|
||||
}
|
||||
|
||||
On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `CursorPagination` on a per-view basis.
|
||||
|
||||
#### Configuration
|
||||
|
||||
The `CursorPagination` class includes a number of attributes that may be overridden to modify the pagination style.
|
||||
|
||||
To set these attributes you should override the `CursorPagination` class, and then enable your custom pagination class as above.
|
||||
|
||||
* `page_size` = A numeric value indicating the page size. If set, this overrides the `PAGE_SIZE` setting. Defaults to the same value as the `PAGE_SIZE` settings key.
|
||||
* `cursor_query_param` = A string value indicating the name of the "cursor" query parameter. Defaults to `'cursor'`.
|
||||
* `ordering` = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: `ordering = 'slug'`. Defaults to `-created`. This value may also be overridden by using `OrderingFilter` on the view.
|
||||
* `template` = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/previous_and_next.html"`.
|
||||
|
||||
---
|
||||
|
||||
# Custom pagination styles
|
||||
|
||||
To create a custom pagination serializer class, you should inherit the subclass `pagination.BasePagination`, override the `paginate_queryset(self, queryset, request, view=None)`, and `get_paginated_response(self, data)` methods:
|
||||
|
||||
* The `paginate_queryset` method is passed to the initial queryset and should return an iterable object. That object contains only the data in the requested page.
|
||||
* The `get_paginated_response` method is passed to the serialized page data and should return a `Response` instance.
|
||||
|
||||
Note that the `paginate_queryset` method may set state on the pagination instance, that may later be used by the `get_paginated_response` method.
|
||||
You can also override the name used for the object list field, by setting the `results_field` attribute, which defaults to `'results'`.
|
||||
|
||||
## 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:
|
||||
For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this.
|
||||
|
||||
class CustomPagination(pagination.PageNumberPagination):
|
||||
def get_paginated_response(self, data):
|
||||
return Response({
|
||||
'links': {
|
||||
'next': self.get_next_link(),
|
||||
'previous': self.get_previous_link()
|
||||
},
|
||||
'count': self.page.paginator.count,
|
||||
'results': data
|
||||
})
|
||||
class LinksSerializer(serializers.Serializer):
|
||||
next = pagination.NextURLField(source='*')
|
||||
prev = pagination.PreviousURLField(source='*')
|
||||
|
||||
We'd then need to set up the custom class in our configuration:
|
||||
class CustomPaginationSerializer(pagination.BasePaginationSerializer):
|
||||
links = LinksSerializer(source='*') # Takes the page object as the source
|
||||
total_results = serializers.Field(source='paginator.count')
|
||||
|
||||
results_field = 'objects'
|
||||
|
||||
## Using your custom pagination serializer
|
||||
|
||||
To have your custom pagination serializer be used by default, use the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination',
|
||||
'PAGE_SIZE': 100
|
||||
'DEFAULT_PAGINATION_SERIALIZER_CLASS':
|
||||
'example_app.pagination.CustomPaginationSerializer',
|
||||
}
|
||||
|
||||
Note that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an `OrderedDict` when constructing the body of paginated responses, but this is optional.
|
||||
Alternatively, to set your custom pagination serializer on a per-view basis, use the `pagination_serializer_class` attribute on a generic class based view:
|
||||
|
||||
## Using your custom pagination class
|
||||
class PaginatedListView(ListAPIView):
|
||||
model = ExampleModel
|
||||
pagination_serializer_class = CustomPaginationSerializer
|
||||
paginate_by = 10
|
||||
|
||||
To have your custom pagination class be used by default, use the `DEFAULT_PAGINATION_CLASS` setting:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination',
|
||||
'PAGE_SIZE': 100
|
||||
}
|
||||
|
||||
API responses for list endpoints will now include a `Link` header, instead of including the pagination links as part of the body of the response, for example:
|
||||
|
||||
![Link Header][link-header]
|
||||
|
||||
*A custom pagination style, using the 'Link' header*
|
||||
|
||||
---
|
||||
|
||||
# HTML pagination controls
|
||||
|
||||
By default using the pagination classes will cause HTML pagination controls to be displayed in the browsable API. There are two built-in display styles. The `PageNumberPagination` and `LimitOffsetPagination` classes display a list of page numbers with previous and next controls. The `CursorPagination` class displays a simpler style that only displays a previous and next control.
|
||||
|
||||
## Customizing the controls
|
||||
|
||||
You can override the templates that render the HTML pagination controls. The two built-in styles are:
|
||||
|
||||
* `rest_framework/pagination/numbers.html`
|
||||
* `rest_framework/pagination/previous_and_next.html`
|
||||
|
||||
Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes.
|
||||
|
||||
Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting `template = None` as an attribute on the class. You'll then need to configure your `DEFAULT_PAGINATION_CLASS` settings key to use your custom class as the default pagination style.
|
||||
|
||||
#### Low-level API
|
||||
|
||||
The low-level API for determining if a pagination class should display the controls or not is exposed as a `display_page_controls` attribute on the pagination instance. Custom pagination classes should be set to `True` in the `paginate_queryset` method if they require the HTML pagination controls to be displayed.
|
||||
|
||||
The `.to_html()` and `.get_html_context()` methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered.
|
||||
|
||||
---
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages are also available.
|
||||
|
||||
## DRF-extensions
|
||||
|
||||
The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` mixin class][paginate-by-max-mixin] that allows your API clients to specify `?page_size=max` to obtain the maximum allowed page size.
|
||||
|
||||
## drf-proxy-pagination
|
||||
|
||||
The [`drf-proxy-pagination` package][drf-proxy-pagination] includes a `ProxyPagination` class which allows to choose pagination class with a query parameter.
|
||||
|
||||
## link-header-pagination
|
||||
|
||||
The [`django-rest-framework-link-header-pagination` package][drf-link-header-pagination] includes a `LinkHeaderPagination` class which provides pagination via an HTTP `Link` header as described in [GitHub REST API documentation][github-traversing-with-pagination].
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/topics/pagination/
|
||||
[link-header]: ../img/link-header-pagination.png
|
||||
[drf-extensions]: https://chibisov.github.io/drf-extensions/docs/
|
||||
[paginate-by-max-mixin]: https://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin
|
||||
[drf-proxy-pagination]: https://github.com/tuffnatty/drf-proxy-pagination
|
||||
[drf-link-header-pagination]: https://github.com/tbeadle/django-rest-framework-link-header-pagination
|
||||
[disqus-cursor-api]: https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api
|
||||
[float_cursor_pagination_example]: https://gist.github.com/keturn/8bc88525a183fd41c73ffb729b8865be#file-fpcursorpagination-py
|
||||
[github-traversing-with-pagination]: https://docs.github.com/en/rest/guides/traversing-with-pagination
|
||||
[cite]: https://docs.djangoproject.com/en/dev/topics/pagination/
|
||||
|
|
|
@ -1,7 +1,4 @@
|
|||
---
|
||||
source:
|
||||
- parsers.py
|
||||
---
|
||||
<a class="github" href="parsers.py"></a>
|
||||
|
||||
# Parsers
|
||||
|
||||
|
@ -11,61 +8,42 @@ sending more complex data than simple forms
|
|||
>
|
||||
> — Malcom Tredinnick, [Django developers group][cite]
|
||||
|
||||
REST framework includes a number of built-in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.
|
||||
REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.
|
||||
|
||||
## 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.
|
||||
|
||||
---
|
||||
|
||||
**Note**: When developing client applications always remember to make sure you're setting the `Content-Type` header when sending data in an HTTP request.
|
||||
|
||||
If you don't set the content type, most clients will default to using `'application/x-www-form-urlencoded'`, which may not be what you wanted.
|
||||
|
||||
As an example, if you are sending `json` encoded data using jQuery with the [.ajax() method][jquery-ajax], you should make sure to include the `contentType: 'application/json'` setting.
|
||||
|
||||
---
|
||||
The set of valid parsers for a view is always defined as a list of classes. When either `request.DATA` or `request.FILES` 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.
|
||||
|
||||
## Setting the parsers
|
||||
|
||||
The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow only requests with `JSON` content, instead of the default of JSON or form data.
|
||||
The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow requests with `YAML` content.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PARSER_CLASSES': [
|
||||
'rest_framework.parsers.JSONParser',
|
||||
]
|
||||
'DEFAULT_PARSER_CLASSES': (
|
||||
'rest_framework.parsers.YAMLParser',
|
||||
)
|
||||
}
|
||||
|
||||
You can also set the parsers used for an individual view, or viewset,
|
||||
using the `APIView` class-based views.
|
||||
|
||||
from rest_framework.parsers import JSONParser
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
You can also set the renderers used for an individual view, using the `APIView` class based views.
|
||||
|
||||
class ExampleView(APIView):
|
||||
"""
|
||||
A view that can accept POST requests with JSON content.
|
||||
A view that can accept POST requests with YAML content.
|
||||
"""
|
||||
parser_classes = [JSONParser]
|
||||
parser_classes = (YAMLParser,)
|
||||
|
||||
def post(self, request, format=None):
|
||||
return Response({'received data': request.data})
|
||||
return Response({'received data': request.DATA})
|
||||
|
||||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.decorators import parser_classes
|
||||
from rest_framework.parsers import JSONParser
|
||||
|
||||
@api_view(['POST'])
|
||||
@parser_classes([JSONParser])
|
||||
@parser_classes((YAMLParser,))
|
||||
def example_view(request, format=None):
|
||||
"""
|
||||
A view that can accept POST requests with JSON content.
|
||||
A view that can accept POST requests with YAML content.
|
||||
"""
|
||||
return Response({'received data': request.data})
|
||||
return Response({'received data': request.DATA})
|
||||
|
||||
---
|
||||
|
||||
|
@ -73,13 +51,29 @@ Or, if you're using the `@api_view` decorator with function based views.
|
|||
|
||||
## JSONParser
|
||||
|
||||
Parses `JSON` request content. `request.data` will be populated with a dictionary of data.
|
||||
Parses `JSON` request content.
|
||||
|
||||
**.media_type**: `application/json`
|
||||
|
||||
## YAMLParser
|
||||
|
||||
Parses `YAML` request content.
|
||||
|
||||
**.media_type**: `application/yaml`
|
||||
|
||||
## XMLParser
|
||||
|
||||
Parses REST framework's default style of `XML` request content.
|
||||
|
||||
Note that the `XML` markup language is typically used as the base language for more strictly defined domain-specific languages, such as `RSS`, `Atom`, and `XHTML`.
|
||||
|
||||
If you are considering using `XML` for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type.
|
||||
|
||||
**.media_type**: `application/xml`
|
||||
|
||||
## FormParser
|
||||
|
||||
Parses HTML form content. `request.data` will be populated with a `QueryDict` of data.
|
||||
Parses HTML form content. `request.DATA` will be populated with a `QueryDict` of data, `request.FILES` will be populated with an empty `QueryDict` of data.
|
||||
|
||||
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
|
||||
|
||||
|
@ -87,54 +81,19 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
|
|||
|
||||
## MultiPartParser
|
||||
|
||||
Parses multipart HTML form content, which supports file uploads. `request.data` and `request.FILES` will be populated with a `QueryDict` and `MultiValueDict` respectively.
|
||||
Parses multipart HTML form content, which supports file uploads. Both `request.DATA` and `request.FILES` will be populated with a `QueryDict`.
|
||||
|
||||
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
|
||||
|
||||
**.media_type**: `multipart/form-data`
|
||||
|
||||
## FileUploadParser
|
||||
|
||||
Parses raw file upload content. The `request.data` property will be a dictionary with a single key `'file'` containing the uploaded file.
|
||||
|
||||
If the view used with `FileUploadParser` is called with a `filename` URL keyword argument, then that argument will be used as the filename.
|
||||
|
||||
If it is called without a `filename` URL keyword argument, then the client must set the filename in the `Content-Disposition` HTTP header. For example `Content-Disposition: attachment; filename=upload.jpg`.
|
||||
|
||||
**.media_type**: `*/*`
|
||||
|
||||
##### Notes:
|
||||
|
||||
* The `FileUploadParser` is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the `MultiPartParser` instead.
|
||||
* Since this parser's `media_type` matches any content type, `FileUploadParser` should generally be the only parser set on an API view.
|
||||
* `FileUploadParser` respects Django's standard `FILE_UPLOAD_HANDLERS` setting, and the `request.upload_handlers` attribute. See the [Django documentation][upload-handlers] for more details.
|
||||
|
||||
##### Basic usage example:
|
||||
|
||||
# views.py
|
||||
class FileUploadView(views.APIView):
|
||||
parser_classes = [FileUploadParser]
|
||||
|
||||
def put(self, request, filename, format=None):
|
||||
file_obj = request.data['file']
|
||||
# ...
|
||||
# do some stuff with uploaded file
|
||||
# ...
|
||||
return Response(status=204)
|
||||
|
||||
# urls.py
|
||||
urlpatterns = [
|
||||
# ...
|
||||
re_path(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
|
||||
]
|
||||
|
||||
---
|
||||
|
||||
# Custom parsers
|
||||
|
||||
To implement a custom parser, you should override `BaseParser`, set the `.media_type` property, and implement the `.parse(self, stream, media_type, parser_context)` method.
|
||||
|
||||
The method should return the data that will be used to populate the `request.data` property.
|
||||
The method should return the data that will be used to populate the `request.DATA` property.
|
||||
|
||||
The arguments passed to `.parse()` are:
|
||||
|
||||
|
@ -156,84 +115,48 @@ By default this will include the following keys: `view`, `request`, `args`, `kwa
|
|||
|
||||
## Example
|
||||
|
||||
The following is an example plaintext parser that will populate the `request.data` property with a string representing the body of the request.
|
||||
The following is an example plaintext parser that will populate the `request.DATA` property with a string representing the body of the request.
|
||||
|
||||
class PlainTextParser(BaseParser):
|
||||
"""
|
||||
Plain text parser.
|
||||
"""
|
||||
|
||||
media_type = 'text/plain'
|
||||
|
||||
def parse(self, stream, media_type=None, parser_context=None):
|
||||
"""
|
||||
Plain text parser.
|
||||
Simply return a string representing the body of the request.
|
||||
"""
|
||||
media_type = 'text/plain'
|
||||
return stream.read()
|
||||
|
||||
## Uploading file content
|
||||
|
||||
If your custom parser needs to support file uploads, you may return a `DataAndFiles` object from the `.parse()` method. `DataAndFiles` should be instantiated with two arguments. The first argument will be used to populate the `request.DATA` property, and the second argument will be used to populate the `request.FILES` property.
|
||||
|
||||
For example:
|
||||
|
||||
class SimpleFileUploadParser(BaseParser):
|
||||
"""
|
||||
A naive raw file upload parser.
|
||||
"""
|
||||
media_type = '*/*' # Accept anything
|
||||
|
||||
def parse(self, stream, media_type=None, parser_context=None):
|
||||
"""
|
||||
Simply return a string representing the body of the request.
|
||||
"""
|
||||
return stream.read()
|
||||
content = stream.read()
|
||||
name = 'example.dat'
|
||||
content_type = 'application/octet-stream'
|
||||
size = len(content)
|
||||
charset = 'utf-8'
|
||||
|
||||
---
|
||||
# Write a temporary file based on the request content
|
||||
temp = tempfile.NamedTemporaryFile(delete=False)
|
||||
temp.write(content)
|
||||
uploaded = UploadedFile(temp, name, content_type, size, charset)
|
||||
|
||||
# Third party packages
|
||||
# Return the uploaded file
|
||||
data = {}
|
||||
files = {name: uploaded}
|
||||
return DataAndFiles(data, files)
|
||||
|
||||
The following third party packages are also available.
|
||||
|
||||
## YAML
|
||||
|
||||
[REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
|
||||
|
||||
#### Installation & configuration
|
||||
|
||||
Install using pip.
|
||||
|
||||
$ pip install djangorestframework-yaml
|
||||
|
||||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PARSER_CLASSES': [
|
||||
'rest_framework_yaml.parsers.YAMLParser',
|
||||
],
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework_yaml.renderers.YAMLRenderer',
|
||||
],
|
||||
}
|
||||
|
||||
## XML
|
||||
|
||||
[REST Framework XML][rest-framework-xml] provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
|
||||
|
||||
#### Installation & configuration
|
||||
|
||||
Install using pip.
|
||||
|
||||
$ pip install djangorestframework-xml
|
||||
|
||||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PARSER_CLASSES': [
|
||||
'rest_framework_xml.parsers.XMLParser',
|
||||
],
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework_xml.renderers.XMLRenderer',
|
||||
],
|
||||
}
|
||||
|
||||
## MessagePack
|
||||
|
||||
[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.
|
||||
|
||||
## CamelCase JSON
|
||||
|
||||
[djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy].
|
||||
|
||||
[jquery-ajax]: https://api.jquery.com/jQuery.ajax/
|
||||
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
|
||||
[upload-handlers]: https://docs.djangoproject.com/en/stable/topics/http/file-uploads/#upload-handlers
|
||||
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
|
||||
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
|
||||
[yaml]: http://www.yaml.org/
|
||||
[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
|
||||
[juanriaza]: https://github.com/juanriaza
|
||||
[vbabiy]: https://github.com/vbabiy
|
||||
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
|
||||
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
|
||||
|
|
|
@ -1,11 +1,8 @@
|
|||
---
|
||||
source:
|
||||
- permissions.py
|
||||
---
|
||||
<a class="github" href="permissions.py"></a>
|
||||
|
||||
# Permissions
|
||||
|
||||
> Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.
|
||||
> Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.
|
||||
>
|
||||
> — [Apple Developer Documentation][cite]
|
||||
|
||||
|
@ -13,90 +10,39 @@ Together with [authentication] and [throttling], permissions determine whether a
|
|||
|
||||
Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the `request.user` and `request.auth` properties to determine if the incoming request should be permitted.
|
||||
|
||||
Permissions are used to grant or deny access for different classes of users to different parts of the API.
|
||||
|
||||
The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the `IsAuthenticated` class in REST framework.
|
||||
|
||||
A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the `IsAuthenticatedOrReadOnly` class in REST framework.
|
||||
|
||||
## How permissions are determined
|
||||
|
||||
Permissions in REST framework are always defined as a list of permission classes.
|
||||
Permissions in REST framework are always defined as a list of permission classes.
|
||||
|
||||
Before running the main body of the view each permission in the list is checked.
|
||||
If any permission check fails, an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run.
|
||||
|
||||
When the permission checks fail, either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
|
||||
|
||||
* The request was successfully authenticated, but permission was denied. *— An HTTP 403 Forbidden response will be returned.*
|
||||
* The request was not successfully authenticated, and the highest priority authentication class *does not* use `WWW-Authenticate` headers. *— An HTTP 403 Forbidden response will be returned.*
|
||||
* The request was not successfully authenticated, and the highest priority authentication class *does* use `WWW-Authenticate` headers. *— An HTTP 401 Unauthorized response, with an appropriate `WWW-Authenticate` header will be returned.*
|
||||
If any permission check fails an `exceptions.PermissionDenied` exception will be raised, and the main body of the view will not run.
|
||||
|
||||
## Object level permissions
|
||||
|
||||
REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance.
|
||||
|
||||
Object level permissions are run by REST framework's generic views when `.get_object()` is called.
|
||||
As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object.
|
||||
|
||||
If you're writing your own views and want to enforce object level permissions,
|
||||
or if you override the `get_object` method on a generic view, then you'll need to explicitly call the `.check_object_permissions(request, obj)` method on the view at the point at which you've retrieved the object.
|
||||
|
||||
This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or simply return if the view has the appropriate permissions.
|
||||
|
||||
For example:
|
||||
|
||||
def get_object(self):
|
||||
obj = get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"])
|
||||
self.check_object_permissions(self.request, obj)
|
||||
return obj
|
||||
|
||||
---
|
||||
|
||||
**Note**: With the exception of `DjangoObjectPermissions`, the provided
|
||||
permission classes in `rest_framework.permissions` **do not** implement the
|
||||
methods necessary to check object permissions.
|
||||
|
||||
If you wish to use the provided permission classes in order to check object
|
||||
permissions, **you must** subclass them and implement the
|
||||
`has_object_permission()` method described in the [_Custom
|
||||
permissions_](#custom-permissions) section (below).
|
||||
|
||||
---
|
||||
|
||||
#### Limitations of object level permissions
|
||||
|
||||
For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.
|
||||
|
||||
Often when you're using object level permissions you'll also want to [filter the queryset][filtering] appropriately, to ensure that users only have visibility onto instances that they are permitted to view.
|
||||
|
||||
Because the `get_object()` method is not called, object level permissions from the `has_object_permission()` method **are not applied** when creating objects. In order to restrict object creation you need to implement the permission check either in your Serializer class or override the `perform_create()` method of your ViewSet class.
|
||||
Object level permissions are run by REST framework's generic views when `.get_object()` is called. As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object.
|
||||
|
||||
## Setting the permission policy
|
||||
|
||||
The default permission policy may be set globally, using the `DEFAULT_PERMISSION_CLASSES` setting. For example.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PERMISSION_CLASSES': [
|
||||
'DEFAULT_PERMISSION_CLASSES': (
|
||||
'rest_framework.permissions.IsAuthenticated',
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
If not specified, this setting defaults to allowing unrestricted access:
|
||||
|
||||
'DEFAULT_PERMISSION_CLASSES': [
|
||||
'DEFAULT_PERMISSION_CLASSES': (
|
||||
'rest_framework.permissions.AllowAny',
|
||||
]
|
||||
)
|
||||
|
||||
You can also set the authentication policy on a per-view, or per-viewset basis,
|
||||
using the `APIView` class-based views.
|
||||
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
|
||||
|
||||
class ExampleView(APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
permission_classes = (IsAuthenticated,)
|
||||
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
|
@ -106,41 +52,14 @@ using the `APIView` class-based views.
|
|||
|
||||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
|
||||
from rest_framework.decorators import api_view, permission_classes
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
|
||||
@api_view(['GET'])
|
||||
@permission_classes([IsAuthenticated])
|
||||
@api_view('GET')
|
||||
@permission_classes((IsAuthenticated, ))
|
||||
def example_view(request, format=None):
|
||||
content = {
|
||||
'status': 'request was permitted'
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
__Note:__ when you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in the __settings.py__ file.
|
||||
|
||||
Provided they inherit from `rest_framework.permissions.BasePermission`, permissions can be composed using standard Python bitwise operators. For example, `IsAuthenticatedOrReadOnly` could be written:
|
||||
|
||||
from rest_framework.permissions import BasePermission, IsAuthenticated, SAFE_METHODS
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
class ReadOnly(BasePermission):
|
||||
def has_permission(self, request, view):
|
||||
return request.method in SAFE_METHODS
|
||||
|
||||
class ExampleView(APIView):
|
||||
permission_classes = [IsAuthenticated|ReadOnly]
|
||||
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
'status': 'request was permitted'
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
__Note:__ it supports & (and), | (or) and ~ (not).
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
@ -161,201 +80,39 @@ This permission is suitable if you want your API to only be accessible to regist
|
|||
|
||||
The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff` is `True` in which case permission will be allowed.
|
||||
|
||||
This permission is suitable if you want your API to only be accessible to a subset of trusted administrators.
|
||||
This permission is suitable is you want your API to only be accessible to a subset of trusted administrators.
|
||||
|
||||
## IsAuthenticatedOrReadOnly
|
||||
|
||||
The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthenticated users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`.
|
||||
The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`.
|
||||
|
||||
This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.
|
||||
|
||||
## 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. The appropriate model is determined by checking `get_queryset().model` or `queryset.model`.
|
||||
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. When applied to a view that has a `.model` property, authorization will only be granted if the user has the relevant model permissions assigned.
|
||||
|
||||
* `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 behavior 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 behaviour 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.
|
||||
|
||||
## DjangoModelPermissionsOrAnonReadOnly
|
||||
|
||||
Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API.
|
||||
|
||||
## DjangoObjectPermissions
|
||||
|
||||
This permission class ties into Django's standard [object permissions framework][objectpermissions] that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as [django-guardian][guardian].
|
||||
|
||||
As with `DjangoModelPermissions`, 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 per-object permissions* and *relevant model permissions* assigned.
|
||||
|
||||
* `POST` requests require the user to have the `add` permission on the model instance.
|
||||
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model instance.
|
||||
* `DELETE` requests require the user to have the `delete` permission on the model instance.
|
||||
|
||||
Note that `DjangoObjectPermissions` **does not** require the `django-guardian` package, and should support other object-level backends equally well.
|
||||
|
||||
As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoObjectPermissions` and setting the `.perms_map` property. Refer to the source code for details.
|
||||
|
||||
---
|
||||
|
||||
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian` package][django-rest-framework-guardian]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.
|
||||
The `DjangoModelPermissions` class also supports object-level permissions. Third-party authorization backends such as [django-guardian][guardian] that provide object-level permissions should work just fine with `DjangoModelPermissions` without any custom configuration required.
|
||||
|
||||
---
|
||||
|
||||
# Custom permissions
|
||||
|
||||
To implement a custom permission, override `BasePermission` and implement either, or both, of the following methods:
|
||||
To implement a custom permission, override `BasePermission` and implement the `.has_permission(self, request, view, obj=None)` method.
|
||||
|
||||
* `.has_permission(self, request, view)`
|
||||
* `.has_object_permission(self, request, view, obj)`
|
||||
|
||||
The methods should return `True` if the request should be granted access, and `False` otherwise.
|
||||
|
||||
If you need to test if a request is a read operation or a write operation, you should check the request method against the constant `SAFE_METHODS`, which is a tuple containing `'GET'`, `'OPTIONS'` and `'HEAD'`. For example:
|
||||
|
||||
if request.method in permissions.SAFE_METHODS:
|
||||
# Check permissions for read-only request
|
||||
else:
|
||||
# Check permissions for write request
|
||||
|
||||
---
|
||||
|
||||
**Note**: The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default. (Function-based views will need to check object permissions explicitly, raising `PermissionDenied` on failure.)
|
||||
|
||||
---
|
||||
|
||||
Custom permissions will raise a `PermissionDenied` exception if the test fails. To change the error message associated with the exception, implement a `message` attribute directly on your custom permission. Otherwise the `default_detail` attribute from `PermissionDenied` will be used. Similarly, to change the code identifier associated with the exception, implement a `code` attribute directly on your custom permission - otherwise the `default_code` attribute from `PermissionDenied` will be used.
|
||||
|
||||
from rest_framework import permissions
|
||||
|
||||
class CustomerAccessPermission(permissions.BasePermission):
|
||||
message = 'Adding customers not allowed.'
|
||||
|
||||
def has_permission(self, request, view):
|
||||
...
|
||||
|
||||
## Examples
|
||||
|
||||
The following is an example of a permission class that checks the incoming request's IP address against a blocklist, and denies the request if the IP has been blocked.
|
||||
|
||||
from rest_framework import permissions
|
||||
|
||||
class BlocklistPermission(permissions.BasePermission):
|
||||
"""
|
||||
Global permission check for blocked IPs.
|
||||
"""
|
||||
|
||||
def has_permission(self, request, view):
|
||||
ip_addr = request.META['REMOTE_ADDR']
|
||||
blocked = Blocklist.objects.filter(ip_addr=ip_addr).exists()
|
||||
return not blocked
|
||||
|
||||
As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example:
|
||||
|
||||
class IsOwnerOrReadOnly(permissions.BasePermission):
|
||||
"""
|
||||
Object-level permission to only allow owners of an object to edit it.
|
||||
Assumes the model instance has an `owner` attribute.
|
||||
"""
|
||||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
# Read permissions are allowed to any request,
|
||||
# so we'll always allow GET, HEAD or OPTIONS requests.
|
||||
if request.method in permissions.SAFE_METHODS:
|
||||
return True
|
||||
|
||||
# Instance must have an attribute named `owner`.
|
||||
return obj.owner == request.user
|
||||
|
||||
Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling `self.check_object_permissions(request, obj)` from the view once you have the object instance. This call will raise an appropriate `APIException` if any object-level permission checks fail, and will otherwise simply return.
|
||||
|
||||
Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the [filtering documentation][filtering] for more details.
|
||||
|
||||
# Overview of access restriction methods
|
||||
|
||||
REST framework offers three different methods to customize access restrictions on a case-by-case basis. These apply in different scenarios and have different effects and limitations.
|
||||
|
||||
* `queryset`/`get_queryset()`: Limits the general visibility of existing objects from the database. The queryset limits which objects will be listed and which objects can be modified or deleted. The `get_queryset()` method can apply different querysets based on the current action.
|
||||
* `permission_classes`/`get_permissions()`: General permission checks based on the current action, request and targeted object. Object level permissions can only be applied to retrieve, modify and deletion actions. Permission checks for list and create will be applied to the entire object type. (In case of list: subject to restrictions in the queryset.)
|
||||
* `serializer_class`/`get_serializer()`: Instance level restrictions that apply to all objects on input and output. The serializer may have access to the request context. The `get_serializer()` method can apply different serializers based on the current action.
|
||||
|
||||
The following table lists the access restriction methods and the level of control they offer over which actions.
|
||||
|
||||
| | `queryset` | `permission_classes` | `serializer_class` |
|
||||
|------------------------------------|------------|----------------------|--------------------|
|
||||
| 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 |
|
||||
| Action: partial_update | global | object-level | object-level |
|
||||
| Action: destroy | global | object-level | no |
|
||||
| Can reference action in decision | no** | yes | no** |
|
||||
| Can reference request in decision | no** | yes | yes |
|
||||
|
||||
\* A Serializer class should not raise PermissionDenied in a list action, or the entire list would not be returned. <br>
|
||||
\** The `get_*()` methods have access to the current view and can return different Serializer or QuerySet instances based on the request or action.
|
||||
|
||||
---
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages are also available.
|
||||
|
||||
## DRF - Access Policy
|
||||
|
||||
The [Django REST - Access Policy][drf-access-policy] package provides a way to define complex access rules in declarative policy classes that are attached to view sets or function-based views. The policies are defined in JSON in a format similar to AWS' Identity & Access Management policies.
|
||||
|
||||
## Composed Permissions
|
||||
|
||||
The [Composed Permissions][composed-permissions] package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.
|
||||
|
||||
## REST Condition
|
||||
|
||||
The [REST Condition][rest-condition] package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators.
|
||||
|
||||
## DRY Rest Permissions
|
||||
|
||||
The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrieve per user.
|
||||
|
||||
## Django Rest Framework Roles
|
||||
|
||||
The [Django Rest Framework Roles][django-rest-framework-roles] package makes it easier to parameterize your API over multiple types of users.
|
||||
|
||||
## Rest Framework Roles
|
||||
|
||||
The [Rest Framework Roles][rest-framework-roles] makes it super easy to protect views based on roles. Most importantly allows you to decouple accessibility logic from models and views in a clean human-readable way.
|
||||
|
||||
## Django REST Framework API Key
|
||||
|
||||
The [Django REST Framework API Key][djangorestframework-api-key] package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. _machines_) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.
|
||||
|
||||
## Django Rest Framework Role Filters
|
||||
|
||||
The [Django Rest Framework Role Filters][django-rest-framework-role-filters] package provides simple filtering over multiple types of roles.
|
||||
|
||||
## Django Rest Framework PSQ
|
||||
|
||||
The [Django Rest Framework PSQ][drf-psq] package is an extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.
|
||||
The method should return `True` if the request should be granted access, and `False` otherwise.
|
||||
|
||||
|
||||
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
|
||||
[authentication]: authentication.md
|
||||
[throttling]: throttling.md
|
||||
[filtering]: filtering.md
|
||||
[contribauth]: https://docs.djangoproject.com/en/stable/topics/auth/customizing/#custom-permissions
|
||||
[objectpermissions]: https://docs.djangoproject.com/en/stable/topics/auth/customizing/#handling-object-permissions
|
||||
[contribauth]: https://docs.djangoproject.com/en/1.0/topics/auth/#permissions
|
||||
[guardian]: https://github.com/lukaszb/django-guardian
|
||||
[filtering]: filtering.md
|
||||
[composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions
|
||||
[rest-condition]: https://github.com/caxap/rest_condition
|
||||
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
|
||||
[django-rest-framework-roles]: https://github.com/computer-lab/django-rest-framework-roles
|
||||
[rest-framework-roles]: https://github.com/Pithikos/rest-framework-roles
|
||||
[djangorestframework-api-key]: https://florimondmanca.github.io/djangorestframework-api-key/
|
||||
[django-rest-framework-role-filters]: https://github.com/allisson/django-rest-framework-role-filters
|
||||
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
|
||||
[drf-access-policy]: https://github.com/rsinger86/drf-access-policy
|
||||
[drf-psq]: https://github.com/drf-psq/drf-psq
|
||||
|
|
|
@ -1,556 +1,62 @@
|
|||
---
|
||||
source:
|
||||
- relations.py
|
||||
---
|
||||
<a class="github" href="relations.py"></a>
|
||||
|
||||
# Serializer relations
|
||||
|
||||
> Data structures, not algorithms, are central to programming.
|
||||
> Bad programmers worry about the code.
|
||||
> Good programmers worry about data structures and their relationships.
|
||||
>
|
||||
> — [Rob Pike][cite]
|
||||
> — [Linus Torvalds][cite]
|
||||
|
||||
|
||||
Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
|
||||
|
||||
---
|
||||
|
||||
**Note:** The relational fields are declared in `relations.py`, but by convention you should import them from the `serializers` module, using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
|
||||
**Note:** The relational fields are declared in `relations.py`, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
## RelatedField
|
||||
|
||||
**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.
|
||||
This field can be applied to any of the following:
|
||||
|
||||
For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched:
|
||||
* A `ForeignKey` field.
|
||||
* A `OneToOneField` field.
|
||||
* A reverse OneToOne relationship
|
||||
* Any other "to-one" relationship.
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = serializers.SlugRelatedField(
|
||||
many=True,
|
||||
read_only=True,
|
||||
slug_field='title'
|
||||
)
|
||||
By default `RelatedField` will represent the target of the field using it's `__unicode__` method.
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
You can customize this behavior by subclassing `ManyRelatedField`, and overriding the `.to_native(self, value)` method.
|
||||
|
||||
# For each album object, tracks should be fetched from database
|
||||
qs = Album.objects.all()
|
||||
print(AlbumSerializer(qs, many=True).data)
|
||||
## ManyRelatedField
|
||||
|
||||
If `AlbumSerializer` is used to serialize a fairly large queryset with `many=True` then it could be a serious performance problem. Optimizing the queryset passed to `AlbumSerializer` with:
|
||||
This field can be applied to any of the following:
|
||||
|
||||
* A `ManyToManyField` field.
|
||||
* A reverse ManyToMany relationship.
|
||||
* A reverse ForeignKey relationship
|
||||
* Any other "to-many" relationship.
|
||||
|
||||
qs = Album.objects.prefetch_related('tracks')
|
||||
# No additional database hits required
|
||||
print(AlbumSerializer(qs, many=True).data)
|
||||
By default `ManyRelatedField` will represent the targets of the field using their `__unicode__` method.
|
||||
|
||||
would solve the issue.
|
||||
|
||||
---
|
||||
|
||||
#### Inspecting relationships.
|
||||
|
||||
When using the `ModelSerializer` class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style.
|
||||
|
||||
To do so, open the Django shell, using `python manage.py shell`, then import the serializer class, instantiate it, and print the object representation…
|
||||
|
||||
>>> from myapp.serializers import AccountSerializer
|
||||
>>> serializer = AccountSerializer()
|
||||
>>> print(repr(serializer))
|
||||
AccountSerializer():
|
||||
id = IntegerField(label='ID', read_only=True)
|
||||
name = CharField(allow_blank=True, max_length=100, required=False)
|
||||
owner = PrimaryKeyRelatedField(queryset=User.objects.all())
|
||||
|
||||
# API Reference
|
||||
|
||||
In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album.
|
||||
|
||||
class Album(models.Model):
|
||||
album_name = models.CharField(max_length=100)
|
||||
artist = models.CharField(max_length=100)
|
||||
|
||||
class Track(models.Model):
|
||||
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
|
||||
order = models.IntegerField()
|
||||
title = models.CharField(max_length=100)
|
||||
duration = models.IntegerField()
|
||||
|
||||
class Meta:
|
||||
unique_together = ['album', 'order']
|
||||
ordering = ['order']
|
||||
|
||||
def __str__(self):
|
||||
return '%d: %s' % (self.order, self.title)
|
||||
|
||||
## StringRelatedField
|
||||
|
||||
`StringRelatedField` may be used to represent the target of the relationship using its `__str__` method.
|
||||
|
||||
For example, the following serializer:
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = serializers.StringRelatedField(many=True)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
Would serialize to the following representation:
|
||||
|
||||
{
|
||||
'album_name': 'Things We Lost In The Fire',
|
||||
'artist': 'Low',
|
||||
'tracks': [
|
||||
'1: Sunflower',
|
||||
'2: Whitetail',
|
||||
'3: Dinosaur Act',
|
||||
...
|
||||
]
|
||||
}
|
||||
|
||||
This field is read only.
|
||||
|
||||
**Arguments**:
|
||||
|
||||
* `many` - If applied to a to-many relationship, you should set this argument to `True`.
|
||||
|
||||
## PrimaryKeyRelatedField
|
||||
|
||||
`PrimaryKeyRelatedField` may be used to represent the target of the relationship using its primary key.
|
||||
|
||||
For example, the following serializer:
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
Would serialize to a representation like this:
|
||||
|
||||
{
|
||||
'album_name': 'Undun',
|
||||
'artist': 'The Roots',
|
||||
'tracks': [
|
||||
89,
|
||||
90,
|
||||
91,
|
||||
...
|
||||
]
|
||||
}
|
||||
|
||||
By default this field is read-write, although you can change this behavior using the `read_only` flag.
|
||||
|
||||
**Arguments**:
|
||||
|
||||
* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`.
|
||||
* `many` - If applied to a to-many relationship, you should set this argument to `True`.
|
||||
* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
|
||||
* `pk_field` - Set to a field to control serialization/deserialization of the primary key's value. For example, `pk_field=UUIDField(format='hex')` would serialize a UUID primary key into its compact hex representation.
|
||||
|
||||
|
||||
## HyperlinkedRelatedField
|
||||
|
||||
`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink.
|
||||
|
||||
For example, the following serializer:
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = serializers.HyperlinkedRelatedField(
|
||||
many=True,
|
||||
read_only=True,
|
||||
view_name='track-detail'
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
Would serialize to a representation like this:
|
||||
|
||||
{
|
||||
'album_name': 'Graceland',
|
||||
'artist': 'Paul Simon',
|
||||
'tracks': [
|
||||
'http://www.example.com/api/tracks/45/',
|
||||
'http://www.example.com/api/tracks/46/',
|
||||
'http://www.example.com/api/tracks/47/',
|
||||
...
|
||||
]
|
||||
}
|
||||
|
||||
By default this field is read-write, although you can change this behavior using the `read_only` flag.
|
||||
|
||||
---
|
||||
|
||||
**Note**: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the `lookup_field` and `lookup_url_kwarg` arguments.
|
||||
|
||||
This is suitable for URLs that contain a single primary key or slug argument as part of the URL.
|
||||
|
||||
If you require more complex hyperlinked representation you'll need to customize the field, as described in the [custom hyperlinked fields](#custom-hyperlinked-fields) section, below.
|
||||
|
||||
---
|
||||
|
||||
**Arguments**:
|
||||
|
||||
* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `<modelname>-detail`. **required**.
|
||||
* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`.
|
||||
* `many` - If applied to a to-many relationship, you should set this argument to `True`.
|
||||
* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
|
||||
* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
|
||||
* `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as `lookup_field`.
|
||||
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
|
||||
|
||||
## SlugRelatedField
|
||||
|
||||
`SlugRelatedField` may be used to represent the target of the relationship using a field on the target.
|
||||
|
||||
For example, the following serializer:
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = serializers.SlugRelatedField(
|
||||
many=True,
|
||||
read_only=True,
|
||||
slug_field='title'
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
Would serialize to a representation like this:
|
||||
|
||||
{
|
||||
'album_name': 'Dear John',
|
||||
'artist': 'Loney Dear',
|
||||
'tracks': [
|
||||
'Airport Surroundings',
|
||||
'Everything Turns to You',
|
||||
'I Was Only Going Out',
|
||||
...
|
||||
]
|
||||
}
|
||||
|
||||
By default this field is read-write, although you can change this behavior using the `read_only` flag.
|
||||
|
||||
When using `SlugRelatedField` as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with `unique=True`.
|
||||
|
||||
**Arguments**:
|
||||
|
||||
* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. **required**
|
||||
* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`.
|
||||
* `many` - If applied to a to-many relationship, you should set this argument to `True`.
|
||||
* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
|
||||
|
||||
## 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:
|
||||
|
||||
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
|
||||
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'track_listing']
|
||||
|
||||
Would serialize to a representation like this:
|
||||
|
||||
{
|
||||
'album_name': 'The Eraser',
|
||||
'artist': 'Thom Yorke',
|
||||
'track_listing': 'http://www.example.com/api/track_list/12/',
|
||||
}
|
||||
|
||||
This field is always read-only.
|
||||
|
||||
**Arguments**:
|
||||
|
||||
* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `<model_name>-detail`. **required**.
|
||||
* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
|
||||
* `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as `lookup_field`.
|
||||
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
|
||||
|
||||
---
|
||||
|
||||
# Nested relationships
|
||||
|
||||
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.
|
||||
|
||||
If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field.
|
||||
|
||||
## Example
|
||||
|
||||
For example, the following serializer:
|
||||
|
||||
class TrackSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Track
|
||||
fields = ['order', 'title', 'duration']
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = TrackSerializer(many=True, read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
Would serialize to a nested representation like this:
|
||||
|
||||
>>> album = Album.objects.create(album_name="The Grey Album", artist='Danger Mouse')
|
||||
>>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)
|
||||
<Track: Track object>
|
||||
>>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)
|
||||
<Track: Track object>
|
||||
>>> Track.objects.create(album=album, order=3, title='Encore', duration=159)
|
||||
<Track: Track object>
|
||||
>>> serializer = AlbumSerializer(instance=album)
|
||||
>>> serializer.data
|
||||
{
|
||||
'album_name': 'The Grey Album',
|
||||
'artist': 'Danger Mouse',
|
||||
'tracks': [
|
||||
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
|
||||
{'order': 2, 'title': 'What More Can I Say', 'duration': 264},
|
||||
{'order': 3, 'title': 'Encore', 'duration': 159},
|
||||
...
|
||||
],
|
||||
}
|
||||
|
||||
## Writable nested serializers
|
||||
|
||||
By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create `create()` and/or `update()` methods in order to explicitly specify how the child relationships should be saved:
|
||||
|
||||
class TrackSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Track
|
||||
fields = ['order', 'title', 'duration']
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = TrackSerializer(many=True)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
def create(self, validated_data):
|
||||
tracks_data = validated_data.pop('tracks')
|
||||
album = Album.objects.create(**validated_data)
|
||||
for track_data in tracks_data:
|
||||
Track.objects.create(album=album, **track_data)
|
||||
return album
|
||||
|
||||
>>> data = {
|
||||
'album_name': 'The Grey Album',
|
||||
'artist': 'Danger Mouse',
|
||||
'tracks': [
|
||||
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
|
||||
{'order': 2, 'title': 'What More Can I Say', 'duration': 264},
|
||||
{'order': 3, 'title': 'Encore', 'duration': 159},
|
||||
],
|
||||
}
|
||||
>>> serializer = AlbumSerializer(data=data)
|
||||
>>> serializer.is_valid()
|
||||
True
|
||||
>>> serializer.save()
|
||||
<Album: Album object>
|
||||
|
||||
---
|
||||
|
||||
# Custom relational fields
|
||||
|
||||
In rare cases where none of the existing relational styles fit the representation you need,
|
||||
you can implement a completely custom relational field, that describes exactly how the
|
||||
output representation should be generated from the model instance.
|
||||
|
||||
To implement a custom relational field, you should override `RelatedField`, and implement the `.to_representation(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. The `value` argument will typically be a model instance.
|
||||
|
||||
If you want to implement a read-write relational field, you must also implement the [`.to_internal_value(self, data)` method][to_internal_value].
|
||||
|
||||
To provide a dynamic queryset based on the `context`, you can also override `.get_queryset(self)` instead of specifying `.queryset` on the class or when initializing the field.
|
||||
|
||||
## Example
|
||||
|
||||
For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration:
|
||||
|
||||
import time
|
||||
|
||||
class TrackListingField(serializers.RelatedField):
|
||||
def to_representation(self, value):
|
||||
duration = time.strftime('%M:%S', time.gmtime(value.duration))
|
||||
return 'Track %d: %s (%s)' % (value.order, value.name, duration)
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = TrackListingField(many=True)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
This custom field would then serialize to the following representation:
|
||||
|
||||
{
|
||||
'album_name': 'Sometimes I Wish We Were an Eagle',
|
||||
'artist': 'Bill Callahan',
|
||||
'tracks': [
|
||||
'Track 1: Jim Cain (04:39)',
|
||||
'Track 2: Eid Ma Clack Shaw (04:19)',
|
||||
'Track 3: The Wind and the Dove (04:34)',
|
||||
...
|
||||
]
|
||||
}
|
||||
|
||||
---
|
||||
|
||||
# Custom hyperlinked fields
|
||||
|
||||
In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field.
|
||||
|
||||
You can achieve this by overriding `HyperlinkedRelatedField`. There are two methods that may be overridden:
|
||||
|
||||
**get_url(self, obj, view_name, request, format)**
|
||||
|
||||
The `get_url` method is used to map the object instance to its URL representation.
|
||||
|
||||
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
|
||||
attributes are not configured to correctly match the URL conf.
|
||||
|
||||
**get_object(self, view_name, view_args, view_kwargs)**
|
||||
|
||||
If you want to support a writable hyperlinked field then you'll also want to override `get_object`, in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method.
|
||||
|
||||
The return value of this method should the object that corresponds to the matched URL conf arguments.
|
||||
|
||||
May raise an `ObjectDoesNotExist` exception.
|
||||
|
||||
## Example
|
||||
|
||||
Say we have a URL for a customer object that takes two keyword arguments, like so:
|
||||
|
||||
/api/<organization_slug>/customers/<customer_pk>/
|
||||
|
||||
This cannot be represented with the default implementation, which accepts only a single lookup field.
|
||||
|
||||
In this case we'd need to override `HyperlinkedRelatedField` to get the behavior we want:
|
||||
|
||||
from rest_framework import serializers
|
||||
from rest_framework.reverse import reverse
|
||||
|
||||
class CustomerHyperlink(serializers.HyperlinkedRelatedField):
|
||||
# We define these as class attributes, so we don't need to pass them as arguments.
|
||||
view_name = 'customer-detail'
|
||||
queryset = Customer.objects.all()
|
||||
|
||||
def get_url(self, obj, view_name, request, format):
|
||||
url_kwargs = {
|
||||
'organization_slug': obj.organization.slug,
|
||||
'customer_pk': obj.pk
|
||||
}
|
||||
return reverse(view_name, kwargs=url_kwargs, request=request, format=format)
|
||||
|
||||
def get_object(self, view_name, view_args, view_kwargs):
|
||||
lookup_kwargs = {
|
||||
'organization__slug': view_kwargs['organization_slug'],
|
||||
'pk': view_kwargs['customer_pk']
|
||||
}
|
||||
return self.get_queryset().get(**lookup_kwargs)
|
||||
|
||||
Note that if you wanted to use this style together with the generic views then you'd also need to override `.get_object` on the view in order to get the correct lookup behavior.
|
||||
|
||||
Generally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation.
|
||||
|
||||
---
|
||||
|
||||
# Further notes
|
||||
|
||||
## The `queryset` argument
|
||||
|
||||
The `queryset` argument is only ever required for *writable* relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance.
|
||||
|
||||
In version 2.x a serializer class could *sometimes* automatically determine the `queryset` argument *if* a `ModelSerializer` class was being used.
|
||||
|
||||
This behavior is now replaced with *always* using an explicit `queryset` argument for writable relational fields.
|
||||
|
||||
Doing so reduces the amount of hidden 'magic' that `ModelSerializer` provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the `ModelSerializer` shortcut, or using fully explicit `Serializer` classes.
|
||||
|
||||
## Customizing the HTML display
|
||||
|
||||
The built-in `__str__` method of the model will be used to generate string representations of the objects used to populate the `choices` property. These choices are used to populate select HTML inputs in the browsable API.
|
||||
|
||||
To provide customized representations for such inputs, override `display_value()` of a `RelatedField` subclass. This method will receive a model object, and should return a string suitable for representing it. For example:
|
||||
|
||||
class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
|
||||
def display_value(self, instance):
|
||||
return 'Track: %s' % (instance.title)
|
||||
|
||||
## Select field cutoffs
|
||||
|
||||
When rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with "More than 1000 items…" will be displayed.
|
||||
|
||||
This behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed.
|
||||
|
||||
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…"`
|
||||
|
||||
You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`.
|
||||
|
||||
In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the `style` keyword argument. For example:
|
||||
|
||||
assigned_to = serializers.SlugRelatedField(
|
||||
queryset=User.objects.all(),
|
||||
slug_field='username',
|
||||
style={'base_template': 'input.html'}
|
||||
)
|
||||
|
||||
## Reverse relations
|
||||
|
||||
Note that reverse relationships are not automatically included by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you must explicitly add it to the fields list. For example:
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
fields = ['tracks', ...]
|
||||
|
||||
You'll normally want to ensure that you've set an appropriate `related_name` argument on the relationship, that you can use as the field name. For example:
|
||||
|
||||
class Track(models.Model):
|
||||
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
|
||||
...
|
||||
|
||||
If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the `fields` argument. For example:
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
fields = ['track_set', ...]
|
||||
|
||||
See the Django documentation on [reverse relationships][reverse-relationships] for more details.
|
||||
|
||||
## Generic relationships
|
||||
|
||||
If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to serialize the targets of the relationship.
|
||||
|
||||
For example, given the following model for a tag, which has a generic relationship with other arbitrary models:
|
||||
For example, given the following models:
|
||||
|
||||
class TaggedItem(models.Model):
|
||||
"""
|
||||
Tags arbitrary model instances using a generic relation.
|
||||
|
||||
See: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/
|
||||
|
||||
See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
|
||||
"""
|
||||
tag_name = models.SlugField()
|
||||
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
|
||||
tag = models.SlugField()
|
||||
content_type = models.ForeignKey(ContentType)
|
||||
object_id = models.PositiveIntegerField()
|
||||
tagged_object = GenericForeignKey('content_type', 'object_id')
|
||||
|
||||
def __str__(self):
|
||||
return self.tag_name
|
||||
|
||||
And the following two models, which may have associated tags:
|
||||
|
||||
content_object = GenericForeignKey('content_type', 'object_id')
|
||||
|
||||
def __unicode__(self):
|
||||
return self.tag
|
||||
|
||||
|
||||
class Bookmark(models.Model):
|
||||
"""
|
||||
A bookmark consists of a URL, and 0 or more descriptive tags.
|
||||
|
@ -558,86 +64,76 @@ And the following two models, which may have associated tags:
|
|||
url = models.URLField()
|
||||
tags = GenericRelation(TaggedItem)
|
||||
|
||||
And a model serializer defined like this:
|
||||
|
||||
class Note(models.Model):
|
||||
"""
|
||||
A note consists of some text, and 0 or more descriptive tags.
|
||||
"""
|
||||
text = models.CharField(max_length=1000)
|
||||
tags = GenericRelation(TaggedItem)
|
||||
class BookmarkSerializer(serializers.ModelSerializer):
|
||||
tags = serializers.ManyRelatedField(source='tags')
|
||||
|
||||
We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized:
|
||||
class Meta:
|
||||
model = Bookmark
|
||||
exclude = ('id',)
|
||||
|
||||
class TaggedObjectRelatedField(serializers.RelatedField):
|
||||
"""
|
||||
A custom field to use for the `tagged_object` generic relationship.
|
||||
"""
|
||||
Then an example output format for a Bookmark instance would be:
|
||||
|
||||
def to_representation(self, value):
|
||||
"""
|
||||
Serialize tagged objects to a simple textual representation.
|
||||
"""
|
||||
if isinstance(value, Bookmark):
|
||||
return 'Bookmark: ' + value.url
|
||||
elif isinstance(value, Note):
|
||||
return 'Note: ' + value.text
|
||||
raise Exception('Unexpected type of tagged object')
|
||||
{
|
||||
'tags': [u'django', u'python'],
|
||||
'url': u'https://www.djangoproject.com/'
|
||||
}
|
||||
|
||||
If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_representation()` method:
|
||||
## PrimaryKeyRelatedField
|
||||
## ManyPrimaryKeyRelatedField
|
||||
|
||||
def to_representation(self, value):
|
||||
"""
|
||||
Serialize bookmark instances using a bookmark serializer,
|
||||
and note instances using a note serializer.
|
||||
"""
|
||||
if isinstance(value, Bookmark):
|
||||
serializer = BookmarkSerializer(value)
|
||||
elif isinstance(value, Note):
|
||||
serializer = NoteSerializer(value)
|
||||
else:
|
||||
raise Exception('Unexpected type of tagged object')
|
||||
`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key.
|
||||
|
||||
return serializer.data
|
||||
By default these fields are read-write, although you can change this behavior using the `read_only` flag.
|
||||
|
||||
Note that reverse generic keys, expressed using the `GenericRelation` field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.
|
||||
**Arguments**:
|
||||
|
||||
For more information see [the Django documentation on generic relations][generic-relations].
|
||||
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
|
||||
* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships.
|
||||
|
||||
## ManyToManyFields with a Through Model
|
||||
## SlugRelatedField
|
||||
## ManySlugRelatedField
|
||||
|
||||
By default, relational fields that target a ``ManyToManyField`` with a
|
||||
``through`` model specified are set to read-only.
|
||||
`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug.
|
||||
|
||||
If you explicitly specify a relational field pointing to a
|
||||
``ManyToManyField`` with a through model, be sure to set ``read_only``
|
||||
to ``True``.
|
||||
By default these fields read-write, although you can change this behavior using the `read_only` flag.
|
||||
|
||||
If you wish to represent [extra fields on a through model][django-intermediary-manytomany] then you may serialize the through model as [a nested object][dealing-with-nested-objects].
|
||||
**Arguments**:
|
||||
|
||||
---
|
||||
* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`.
|
||||
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
|
||||
* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships.
|
||||
|
||||
# Third Party Packages
|
||||
## HyperlinkedRelatedField
|
||||
## ManyHyperlinkedRelatedField
|
||||
|
||||
The following third party packages are also available.
|
||||
`HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField` will represent the target of the relationship using a hyperlink.
|
||||
|
||||
## DRF Nested Routers
|
||||
By default, `HyperlinkedRelatedField` is read-write, although you can change this behavior using the `read_only` flag.
|
||||
|
||||
The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources.
|
||||
**Arguments**:
|
||||
|
||||
## Rest Framework Generic Relations
|
||||
* `view_name` - The view name that should be used as the target of the relationship. **required**.
|
||||
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
|
||||
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
|
||||
* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
|
||||
* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
|
||||
* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
|
||||
* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships.
|
||||
|
||||
The [rest-framework-generic-relations][drf-nested-relations] library provides read/write serialization for generic foreign keys.
|
||||
## HyperLinkedIdentityField
|
||||
|
||||
The [rest-framework-gm2m-relations][drf-gm2m-relations] library provides read/write serialization for [django-gm2m][django-gm2m-field].
|
||||
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer.
|
||||
|
||||
[cite]: http://users.ece.utexas.edu/~adnan/pike.html
|
||||
[reverse-relationships]: https://docs.djangoproject.com/en/stable/topics/db/queries/#following-relationships-backward
|
||||
[routers]: https://www.django-rest-framework.org/api-guide/routers#defaultrouter
|
||||
[generic-relations]: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/#id1
|
||||
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
|
||||
[drf-nested-relations]: https://github.com/Ian-Foote/rest-framework-generic-relations
|
||||
[drf-gm2m-relations]: https://github.com/mojtabaakbari221b/rest-framework-gm2m-relations
|
||||
[django-gm2m-field]: https://github.com/tkhyn/django-gm2m
|
||||
[django-intermediary-manytomany]: https://docs.djangoproject.com/en/stable/topics/db/models/#intermediary-manytomany
|
||||
[dealing-with-nested-objects]: https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
|
||||
[to_internal_value]: https://www.django-rest-framework.org/api-guide/serializers/#to_internal_valueself-data
|
||||
This field is always read-only.
|
||||
|
||||
**Arguments**:
|
||||
|
||||
* `view_name` - The view name that should be used as the target of the relationship. **required**.
|
||||
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
|
||||
* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
|
||||
* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
|
||||
* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
|
||||
|
||||
[cite]: http://lwn.net/Articles/193245/
|
||||
|
|
|
@ -1,7 +1,4 @@
|
|||
---
|
||||
source:
|
||||
- renderers.py
|
||||
---
|
||||
<a class="github" href="renderers.py"></a>
|
||||
|
||||
# Renderers
|
||||
|
||||
|
@ -17,32 +14,26 @@ The set of valid renderers for a view is always defined as a list of classes. W
|
|||
|
||||
The basic process of content negotiation involves examining the request's `Accept` header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL `http://example.com/api/users_count.json` might be an endpoint that always returns JSON data.
|
||||
|
||||
For more information see the documentation on [content negotiation][conneg].
|
||||
For more information see the documentation on [content negotation][conneg].
|
||||
|
||||
## Setting the renderers
|
||||
|
||||
The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would use `JSON` as the main media type and also include the self describing API.
|
||||
The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would use `YAML` as the main media type and also include the self describing API.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'DEFAULT_RENDERER_CLASSES': (
|
||||
'rest_framework.renderers.YAMLRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
You can also set the renderers used for an individual view, or viewset,
|
||||
using the `APIView` class-based views.
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework.renderers import JSONRenderer
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
You can also set the renderers used for an individual view, using the `APIView` class based views.
|
||||
|
||||
class UserCountView(APIView):
|
||||
"""
|
||||
A view that returns the count of active users in JSON.
|
||||
A view that returns the count of active users, in JSON or JSONp.
|
||||
"""
|
||||
renderer_classes = [JSONRenderer]
|
||||
renderer_classes = (JSONRenderer, JSONPRenderer)
|
||||
|
||||
def get(self, request, format=None):
|
||||
user_count = User.objects.filter(active=True).count()
|
||||
|
@ -52,10 +43,10 @@ using the `APIView` class-based views.
|
|||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
|
||||
@api_view(['GET'])
|
||||
@renderer_classes([JSONRenderer])
|
||||
@renderer_classes((JSONRenderer, JSONPRenderer))
|
||||
def user_count_view(request, format=None):
|
||||
"""
|
||||
A view that returns the count of active users in JSON.
|
||||
A view that returns the count of active users, in JSON or JSONp.
|
||||
"""
|
||||
user_count = User.objects.filter(active=True).count()
|
||||
content = {'user_count': user_count}
|
||||
|
@ -65,7 +56,7 @@ Or, if you're using the `@api_view` decorator with function based views.
|
|||
|
||||
It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an `Accept: */*` header, or not including an `Accept` header at all, then REST framework will select the first renderer in the list to use for the response.
|
||||
|
||||
For example if your API serves JSON responses and the HTML browsable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header.
|
||||
For example if your API serves JSON responses and the HTML browseable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header.
|
||||
|
||||
If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making `TemplateHTMLRenderer` your default renderer, in order to play nicely with older browsers that send [broken accept headers][browser-accept-headers].
|
||||
|
||||
|
@ -75,26 +66,45 @@ If your API includes views that can serve both regular webpages and API response
|
|||
|
||||
## JSONRenderer
|
||||
|
||||
Renders the request data into `JSON`, using utf-8 encoding.
|
||||
|
||||
Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace:
|
||||
|
||||
{"unicode black star":"★","value":999}
|
||||
Renders the request data into `JSON`.
|
||||
|
||||
The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`.
|
||||
|
||||
{
|
||||
"unicode black star": "★",
|
||||
"value": 999
|
||||
}
|
||||
|
||||
The default JSON encoding style can be altered using the `UNICODE_JSON` and `COMPACT_JSON` settings keys.
|
||||
|
||||
**.media_type**: `application/json`
|
||||
|
||||
**.format**: `'json'`
|
||||
**.format**: `'.json'`
|
||||
|
||||
**.charset**: `None`
|
||||
## JSONPRenderer
|
||||
|
||||
Renders the request data into `JSONP`. The `JSONP` media type provides a mechanism of allowing cross-domain AJAX requests, by wrapping a `JSON` response in a javascript callback.
|
||||
|
||||
The javascript callback function must be set by the client including a `callback` URL query parameter. For example `http://example.com/api/users?callback=jsonpCallback`. If the callback function is not explicitly set by the client it will default to `'callback'`.
|
||||
|
||||
**Note**: If you require cross-domain AJAX requests, you may also want to consider using [CORS] as an alternative to `JSONP`.
|
||||
|
||||
**.media_type**: `application/javascript`
|
||||
|
||||
**.format**: `'.jsonp'`
|
||||
|
||||
## YAMLRenderer
|
||||
|
||||
Renders the request data into `YAML`.
|
||||
|
||||
**.media_type**: `application/yaml`
|
||||
|
||||
**.format**: `'.yaml'`
|
||||
|
||||
## XMLRenderer
|
||||
|
||||
Renders REST framework's default style of `XML` response content.
|
||||
|
||||
Note that the `XML` markup language is used typically used as the base language for more strictly defined domain-specific languages, such as `RSS`, `Atom`, and `XHTML`.
|
||||
|
||||
If you are considering using `XML` for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type.
|
||||
|
||||
**.media_type**: `application/xml`
|
||||
|
||||
**.format**: `'.xml'`
|
||||
|
||||
## TemplateHTMLRenderer
|
||||
|
||||
|
@ -103,46 +113,32 @@ Unlike other renderers, the data passed to the `Response` does not need to be se
|
|||
|
||||
The TemplateHTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context.
|
||||
|
||||
---
|
||||
|
||||
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the `TemplateHTMLRenderer` to render it. For example:
|
||||
|
||||
```
|
||||
response.data = {'results': response.data}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
The template name is determined by (in order of preference):
|
||||
|
||||
1. An explicit `template_name` argument passed to the response.
|
||||
1. An explicit `.template_name` attribute set on the response.
|
||||
2. An explicit `.template_name` attribute set on this class.
|
||||
3. The return result of calling `view.get_template_names()`.
|
||||
|
||||
An example of a view that uses `TemplateHTMLRenderer`:
|
||||
|
||||
class UserDetail(generics.RetrieveAPIView):
|
||||
class UserInstance(generics.RetrieveUserAPIView):
|
||||
"""
|
||||
A view that returns a templated HTML representation of a given user.
|
||||
A view that returns a templated HTML representations of a given user.
|
||||
"""
|
||||
queryset = User.objects.all()
|
||||
renderer_classes = [TemplateHTMLRenderer]
|
||||
model = Users
|
||||
renderer_classes = (TemplateHTMLRenderer,)
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
def get(self, request, *args, **kwargs)
|
||||
self.object = self.get_object()
|
||||
return Response({'user': self.object}, template_name='user_detail.html')
|
||||
|
||||
|
||||
You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
|
||||
|
||||
If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers.
|
||||
|
||||
See the [_HTML & Forms_ Topic Page][html-and-forms] for further examples of `TemplateHTMLRenderer` usage.
|
||||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'html'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
**.format**: `'.html'`
|
||||
|
||||
See also: `StaticHTMLRenderer`
|
||||
|
||||
|
@ -150,116 +146,35 @@ See also: `StaticHTMLRenderer`
|
|||
|
||||
A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.
|
||||
|
||||
An example of a view that uses `StaticHTMLRenderer`:
|
||||
An example of a view that uses `TemplateHTMLRenderer`:
|
||||
|
||||
@api_view(['GET'])
|
||||
@renderer_classes([StaticHTMLRenderer])
|
||||
def simple_html_view(request):
|
||||
@api_view(('GET',))
|
||||
@renderer_classes((StaticHTMLRenderer,))
|
||||
def simple_html_view(request):
|
||||
data = '<html><body><h1>Hello, world</h1></body></html>'
|
||||
return Response(data)
|
||||
|
||||
You can use `StaticHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
|
||||
You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
|
||||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'html'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
**.format**: `'.html'`
|
||||
|
||||
See also: `TemplateHTMLRenderer`
|
||||
|
||||
## BrowsableAPIRenderer
|
||||
|
||||
Renders data into HTML for the Browsable API:
|
||||
|
||||

|
||||
|
||||
This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.
|
||||
Renders data into HTML for the Browseable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.
|
||||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'api'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
|
||||
**.template**: `'rest_framework/api.html'`
|
||||
|
||||
#### Customizing BrowsableAPIRenderer
|
||||
|
||||
By default the response content will be rendered with the highest priority renderer apart from `BrowsableAPIRenderer`. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the `get_default_renderer()` method. For example:
|
||||
|
||||
class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
|
||||
def get_default_renderer(self, view):
|
||||
return JSONRenderer()
|
||||
|
||||
## AdminRenderer
|
||||
|
||||
Renders data into HTML for an admin-like display:
|
||||
|
||||

|
||||
|
||||
This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data.
|
||||
|
||||
Note that views that have nested or list serializers for their input won't work well with the `AdminRenderer`, as the HTML forms are unable to properly support them.
|
||||
|
||||
**Note**: The `AdminRenderer` is only able to include links to detail pages when a properly configured `URL_FIELD_NAME` (`url` by default) attribute is present in the data. For `HyperlinkedModelSerializer` this will be the case, but for `ModelSerializer` or plain `Serializer` classes you'll need to make sure to include the field explicitly. For example here we use models `get_absolute_url` method:
|
||||
|
||||
class AccountSerializer(serializers.ModelSerializer):
|
||||
url = serializers.CharField(source='get_absolute_url', read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Account
|
||||
|
||||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'admin'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
|
||||
**.template**: `'rest_framework/admin.html'`
|
||||
|
||||
## HTMLFormRenderer
|
||||
|
||||
Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing `<form>` tags, a hidden CSRF input or any submit buttons.
|
||||
|
||||
This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the `render_form` template tag.
|
||||
|
||||
{% load rest_framework %}
|
||||
|
||||
<form action="/submit-report/" method="post">
|
||||
{% csrf_token %}
|
||||
{% render_form serializer %}
|
||||
<input type="submit" value="Save" />
|
||||
</form>
|
||||
|
||||
For more information see the [HTML & Forms][html-and-forms] documentation.
|
||||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'form'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
|
||||
**.template**: `'rest_framework/horizontal/form.html'`
|
||||
|
||||
## MultiPartRenderer
|
||||
|
||||
This renderer is used for rendering HTML multipart form data. **It is not suitable as a response renderer**, but is instead used for creating test requests, using REST framework's [test client and test request factory][testing].
|
||||
|
||||
**.media_type**: `multipart/form-data; boundary=BoUnDaRyStRiNg`
|
||||
|
||||
**.format**: `'multipart'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
**.format**: `'.api'`
|
||||
|
||||
---
|
||||
|
||||
# Custom renderers
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
The arguments passed to the `.render()` method are:
|
||||
|
||||
|
@ -267,15 +182,15 @@ The arguments passed to the `.render()` method are:
|
|||
|
||||
The request data, as set by the `Response()` instantiation.
|
||||
|
||||
### `accepted_media_type=None`
|
||||
### `media_type=None`
|
||||
|
||||
Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.
|
||||
Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.
|
||||
|
||||
Depending on the client's `Accept:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"application/json; nested=true"`.
|
||||
|
||||
### `renderer_context=None`
|
||||
|
||||
Optional. If provided, this is a dictionary of contextual information provided by the view.
|
||||
Optional. If provided, this is a dictionary of contextual information provided by the view.
|
||||
|
||||
By default this will include the following keys: `view`, `request`, `response`, `args`, `kwargs`.
|
||||
|
||||
|
@ -283,43 +198,18 @@ By default this will include the following keys: `view`, `request`, `response`,
|
|||
|
||||
The following is an example plaintext renderer that will return a response with the `data` parameter as the content of the response.
|
||||
|
||||
from django.utils.encoding import smart_str
|
||||
from django.utils.encoding import smart_unicode
|
||||
from rest_framework import renderers
|
||||
|
||||
|
||||
class PlainTextRenderer(renderers.BaseRenderer):
|
||||
class PlainText(renderers.BaseRenderer):
|
||||
media_type = 'text/plain'
|
||||
format = 'txt'
|
||||
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return smart_str(data, encoding=self.charset)
|
||||
|
||||
## Setting the character set
|
||||
|
||||
By default renderer classes are assumed to be using the `UTF-8` encoding. To use a different encoding, set the `charset` attribute on the renderer.
|
||||
|
||||
class PlainTextRenderer(renderers.BaseRenderer):
|
||||
media_type = 'text/plain'
|
||||
format = 'txt'
|
||||
charset = 'iso-8859-1'
|
||||
|
||||
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.
|
||||
|
||||
If the renderer returns a bytestring representing raw binary content, you should set a charset value of `None`, which will ensure the `Content-Type` header of the response will not have a `charset` value set.
|
||||
|
||||
In some cases you may also want to set the `render_style` attribute to `'binary'`. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string.
|
||||
|
||||
class JPEGRenderer(renderers.BaseRenderer):
|
||||
media_type = 'image/jpeg'
|
||||
format = 'jpg'
|
||||
charset = None
|
||||
render_style = 'binary'
|
||||
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return data
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
if isinstance(data, basestring):
|
||||
return data
|
||||
return smart_unicode(data)
|
||||
|
||||
---
|
||||
|
||||
|
@ -330,16 +220,16 @@ You can do some pretty flexible things using REST framework's renderers. Some e
|
|||
* Provide either flat or nested representations from the same endpoint, depending on the requested media type.
|
||||
* Serve both regular HTML webpages, and JSON based API responses from the same endpoints.
|
||||
* 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.
|
||||
* 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 behavior by media type
|
||||
## Varying behaviour 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.
|
||||
|
||||
For example:
|
||||
|
||||
@api_view(['GET'])
|
||||
@renderer_classes([TemplateHTMLRenderer, JSONRenderer])
|
||||
@api_view(('GET',))
|
||||
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
|
||||
def list_users(request):
|
||||
"""
|
||||
A view that can return JSON or HTML representations
|
||||
|
@ -359,15 +249,6 @@ For example:
|
|||
data = serializer.data
|
||||
return Response(data)
|
||||
|
||||
## Underspecifying the media type
|
||||
|
||||
In some cases you might want a renderer to serve a range of media types.
|
||||
In this case you can underspecify the media types it should respond to, by using a `media_type` value such as `image/*`, or `*/*`.
|
||||
|
||||
If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the `content_type` attribute. For example:
|
||||
|
||||
return Response(data, content_type='image/png')
|
||||
|
||||
## Designing your media types
|
||||
|
||||
For the purposes of many Web APIs, simple `JSON` responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and [HATEOAS] you'll need to consider the design and usage of your media types in more detail.
|
||||
|
@ -390,181 +271,13 @@ Exceptions raised and handled by an HTML renderer will attempt to render using o
|
|||
|
||||
Templates will render with a `RequestContext` which includes the `status_code` and `details` keys.
|
||||
|
||||
**Note**: If `DEBUG=True`, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.
|
||||
|
||||
---
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages are also available.
|
||||
|
||||
## YAML
|
||||
|
||||
[REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
|
||||
|
||||
#### Installation & configuration
|
||||
|
||||
Install using pip.
|
||||
|
||||
$ pip install djangorestframework-yaml
|
||||
|
||||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PARSER_CLASSES': [
|
||||
'rest_framework_yaml.parsers.YAMLParser',
|
||||
],
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework_yaml.renderers.YAMLRenderer',
|
||||
],
|
||||
}
|
||||
|
||||
## XML
|
||||
|
||||
[REST Framework XML][rest-framework-xml] provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
|
||||
|
||||
#### Installation & configuration
|
||||
|
||||
Install using pip.
|
||||
|
||||
$ pip install djangorestframework-xml
|
||||
|
||||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PARSER_CLASSES': [
|
||||
'rest_framework_xml.parsers.XMLParser',
|
||||
],
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework_xml.renderers.XMLRenderer',
|
||||
],
|
||||
}
|
||||
|
||||
## JSONP
|
||||
|
||||
[REST framework JSONP][rest-framework-jsonp] provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
|
||||
|
||||
---
|
||||
|
||||
**Warning**: If you require cross-domain AJAX requests, you should generally be using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details.
|
||||
|
||||
The `jsonp` approach is essentially a browser hack, and is [only appropriate for globally readable API endpoints][jsonp-security], where `GET` requests are unauthenticated and do not require any user permissions.
|
||||
|
||||
---
|
||||
|
||||
#### Installation & configuration
|
||||
|
||||
Install using pip.
|
||||
|
||||
$ pip install djangorestframework-jsonp
|
||||
|
||||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework_jsonp.renderers.JSONPRenderer',
|
||||
],
|
||||
}
|
||||
|
||||
## MessagePack
|
||||
|
||||
[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.
|
||||
|
||||
## 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-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-excel
|
||||
|
||||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
...
|
||||
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
'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_excel.mixins import XLSXFileMixin
|
||||
from drf_excel.renderers import XLSXRenderer
|
||||
|
||||
from .models import MyExampleModel
|
||||
from .serializers import MyExampleSerializer
|
||||
|
||||
class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
|
||||
queryset = MyExampleModel.objects.all()
|
||||
serializer_class = MyExampleSerializer
|
||||
renderer_classes = [XLSXRenderer]
|
||||
filename = 'my_export.xlsx'
|
||||
|
||||
## CSV
|
||||
|
||||
Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework.
|
||||
|
||||
## UltraJSON
|
||||
|
||||
[UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Adam Mertz][Amertz08] maintains [drf_ujson2][drf_ujson2], a fork of the now unmaintained [drf-ujson-renderer][drf-ujson-renderer], which implements JSON rendering using the UJSON package.
|
||||
|
||||
## CamelCase JSON
|
||||
|
||||
[djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy].
|
||||
|
||||
## Pandas (CSV, Excel, PNG)
|
||||
|
||||
[Django REST Pandas] provides a serializer and renderers that support additional data processing and output via the [Pandas] DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both `.xls` and `.xlsx`), and a number of [other formats]. It is maintained by [S. Andrew Sheppard][sheppard] as part of the [wq Project][wq].
|
||||
|
||||
## LaTeX
|
||||
|
||||
[Rest Framework Latex] provides a renderer that outputs PDFs using Lualatex. It is maintained by [Pebble (S/F Software)][mypebble].
|
||||
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/ref/template-response/#the-rendering-process
|
||||
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
|
||||
[conneg]: content-negotiation.md
|
||||
[html-and-forms]: ../topics/html-and-forms.md
|
||||
[browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
|
||||
[testing]: testing.md
|
||||
[CORS]: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
|
||||
[HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas
|
||||
[quote]: https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
|
||||
[application/vnd.github+json]: https://developer.github.com/v3/media/
|
||||
[quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
|
||||
[application/vnd.github+json]: http://developer.github.com/v3/media/
|
||||
[application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/
|
||||
[django-error-views]: https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views
|
||||
[rest-framework-jsonp]: https://jpadilla.github.io/django-rest-framework-jsonp/
|
||||
[cors]: https://www.w3.org/TR/cors/
|
||||
[cors-docs]: https://www.django-rest-framework.org/topics/ajax-csrf-cors/
|
||||
[jsonp-security]: https://stackoverflow.com/questions/613962/is-jsonp-safe-to-use
|
||||
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
|
||||
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
|
||||
[messagepack]: https://msgpack.org/
|
||||
[juanriaza]: https://github.com/juanriaza
|
||||
[mjumbewu]: https://github.com/mjumbewu
|
||||
[flipperpa]: https://github.com/flipperpa
|
||||
[wharton]: https://github.com/wharton
|
||||
[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/
|
||||
[yaml]: http://www.yaml.org/
|
||||
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
|
||||
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
|
||||
[ultrajson]: https://github.com/esnme/ultrajson
|
||||
[Amertz08]: https://github.com/Amertz08
|
||||
[drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer
|
||||
[drf_ujson2]: https://github.com/Amertz08/drf_ujson2
|
||||
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
|
||||
[Django REST Pandas]: https://github.com/wq/django-rest-pandas
|
||||
[Pandas]: https://pandas.pydata.org/
|
||||
[other formats]: https://github.com/wq/django-rest-pandas#supported-formats
|
||||
[sheppard]: https://github.com/sheppard
|
||||
[wq]: https://github.com/wq
|
||||
[mypebble]: https://github.com/mypebble
|
||||
[Rest Framework Latex]: https://github.com/mypebble/rest-framework-latex
|
||||
[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
|
|
@ -1,7 +1,4 @@
|
|||
---
|
||||
source:
|
||||
- request.py
|
||||
---
|
||||
<a class="github" href="request.py"></a>
|
||||
|
||||
# Requests
|
||||
|
||||
|
@ -17,21 +14,26 @@ REST framework's `Request` class extends the standard `HttpRequest`, adding supp
|
|||
|
||||
REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data.
|
||||
|
||||
## .data
|
||||
## .DATA
|
||||
|
||||
`request.data` returns the parsed content of the request body. This is similar to the standard `request.POST` and `request.FILES` attributes except that:
|
||||
`request.DATA` returns the parsed content of the request body. This is similar to the standard `request.POST` attribute except that:
|
||||
|
||||
* It includes all parsed content, including *file and non-file* inputs.
|
||||
* It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests.
|
||||
* It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming [JSON data] similarly to how you handle incoming [form data].
|
||||
* It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.
|
||||
|
||||
For more details see the [parsers documentation].
|
||||
|
||||
## .query_params
|
||||
## .FILES
|
||||
|
||||
`request.query_params` is a more correctly named synonym for `request.GET`.
|
||||
`request.FILES` returns any uploaded files that may be present in the content of the request body. This is the same as the standard `HttpRequest` behavior, except that the same flexible request parsing is used for `request.DATA`.
|
||||
|
||||
For clarity inside your code, we recommend using `request.query_params` instead of the Django's standard `request.GET`. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just `GET` requests.
|
||||
For more details see the [parsers documentation].
|
||||
|
||||
## .QUERY_PARAMS
|
||||
|
||||
`request.QUERY_PARAMS` is a more correctly named synonym for `request.GET`.
|
||||
|
||||
For clarity inside your code, we recommend using `request.QUERY_PARAMS` instead of the usual `request.GET`, as *any* HTTP method type may include query parameters.
|
||||
|
||||
## .parsers
|
||||
|
||||
|
@ -41,26 +43,12 @@ You won't typically need to access this property.
|
|||
|
||||
---
|
||||
|
||||
**Note:** If a client sends malformed content, then accessing `request.data` may raise a `ParseError`. By default REST framework's `APIView` class or `@api_view` decorator will catch the error and return a `400 Bad Request` response.
|
||||
**Note:** If a client sends malformed content, then accessing `request.DATA` or `request.FILES` may raise a `ParseError`. By default REST framework's `APIView` class or `@api_view` decorator will catch the error and return a `400 Bad Request` response.
|
||||
|
||||
If a client sends a request with a content-type that cannot be parsed then a `UnsupportedMediaType` exception will be raised, which by default will be caught and return a `415 Unsupported Media Type` response.
|
||||
|
||||
---
|
||||
|
||||
# Content negotiation
|
||||
|
||||
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
|
||||
|
||||
The renderer instance that was selected by the content negotiation stage.
|
||||
|
||||
## .accepted_media_type
|
||||
|
||||
A string representing the media type that was accepted by the content negotiation stage.
|
||||
|
||||
---
|
||||
|
||||
# Authentication
|
||||
|
||||
REST framework provides flexible, per-request authentication, that gives you the ability to:
|
||||
|
@ -93,21 +81,17 @@ You won't typically need to access this property.
|
|||
|
||||
---
|
||||
|
||||
**Note:** You may see a `WrappedAttributeError` raised when calling the `.user` or `.auth` properties. These errors originate from an authenticator as a standard `AttributeError`, however it's necessary that they be re-raised as a different exception type in order to prevent them from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from the authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. The authenticator will need to be fixed.
|
||||
|
||||
---
|
||||
|
||||
# Browser enhancements
|
||||
|
||||
REST framework supports a few browser enhancements such as browser-based `PUT`, `PATCH` and `DELETE` forms.
|
||||
REST framework supports a few browser enhancements such as browser-based `PUT` and `DELETE` forms.
|
||||
|
||||
## .method
|
||||
|
||||
`request.method` returns the **uppercased** string representation of the request's HTTP method.
|
||||
|
||||
Browser-based `PUT`, `PATCH` and `DELETE` forms are transparently supported.
|
||||
Browser-based `PUT` and `DELETE` forms are transparently supported.
|
||||
|
||||
For more information see the [browser enhancements documentation].
|
||||
For more information see the [browser enhancements documentation].
|
||||
|
||||
## .content_type
|
||||
|
||||
|
@ -117,7 +101,7 @@ You won't typically need to directly access the request's content type, as you'l
|
|||
|
||||
If you do need to access the content type of the request you should use the `.content_type` property in preference to using `request.META.get('HTTP_CONTENT_TYPE')`, as it provides transparent support for browser-based non-form content.
|
||||
|
||||
For more information see the [browser enhancements documentation].
|
||||
For more information see the [browser enhancements documentation].
|
||||
|
||||
## .stream
|
||||
|
||||
|
@ -125,18 +109,20 @@ For more information see the [browser enhancements documentation].
|
|||
|
||||
You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior.
|
||||
|
||||
If you do need to access the raw content directly, you should use the `.stream` property in preference to using `request.content`, as it provides transparent support for browser-based non-form content.
|
||||
|
||||
For more information see the [browser enhancements documentation].
|
||||
|
||||
---
|
||||
|
||||
# Standard HttpRequest attributes
|
||||
|
||||
As REST framework's `Request` extends Django's `HttpRequest`, all the other standard attributes and methods are also available. For example the `request.META` and `request.session` dictionaries are available as normal.
|
||||
As REST framework's `Request` extends Django's `HttpRequest`, all the other standard attributes and methods are also available. For example the `request.META` dictionary is available as normal.
|
||||
|
||||
Note that due to implementation reasons the `Request` class does not inherit from `HttpRequest` class, but instead extends the class using composition.
|
||||
|
||||
|
||||
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
|
||||
[parsers documentation]: parsers.md
|
||||
[JSON data]: parsers.md#jsonparser
|
||||
[form data]: parsers.md#formparser
|
||||
[authentication documentation]: authentication.md
|
||||
[browser enhancements documentation]: ../topics/browser-enhancements.md
|
||||
|
|
|
@ -1,19 +1,16 @@
|
|||
---
|
||||
source:
|
||||
- response.py
|
||||
---
|
||||
<a class="github" href="response.py"></a>
|
||||
|
||||
# Responses
|
||||
|
||||
> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.
|
||||
> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.
|
||||
>
|
||||
> — [Django documentation][cite]
|
||||
|
||||
REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request.
|
||||
|
||||
The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` objects are initialised with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.
|
||||
The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` objects are initialised with data, which should consist of native python primatives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.
|
||||
|
||||
There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` or `StreamingHttpResponse` objects from your views if required. Using the `Response` class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats.
|
||||
There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` objects from your views if you want, but it provides a nicer interface for returning Web API responses.
|
||||
|
||||
Unless you want to heavily customize REST framework for some reason, you should always use an `APIView` class or `@api_view` function for views that return `Response` objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view.
|
||||
|
||||
|
@ -23,11 +20,11 @@ Unless you want to heavily customize REST framework for some reason, you should
|
|||
|
||||
## Response()
|
||||
|
||||
**Signature:** `Response(data, status=None, template_name=None, headers=None, content_type=None)`
|
||||
**Signature:** `Response(data, status=None, template_name=None, headers=None)`
|
||||
|
||||
Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.
|
||||
Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any python primatives.
|
||||
|
||||
The renderers used by the `Response` class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the `Response` object.
|
||||
The renderers used by the `Response` class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primative datatypes before creating the `Response` object.
|
||||
|
||||
You can use REST framework's `Serializer` classes to perform this data serialization, or use your own custom serialization.
|
||||
|
||||
|
@ -37,7 +34,6 @@ Arguments:
|
|||
* `status`: A status code for the response. Defaults to 200. See also [status codes][statuscodes].
|
||||
* `template_name`: A template name to use if `HTMLRenderer` is selected.
|
||||
* `headers`: A dictionary of HTTP headers to use in the response.
|
||||
* `content_type`: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly.
|
||||
|
||||
---
|
||||
|
||||
|
@ -45,7 +41,7 @@ Arguments:
|
|||
|
||||
## .data
|
||||
|
||||
The unrendered, serialized data of the response.
|
||||
The unrendered content of a `Request` object.
|
||||
|
||||
## .status_code
|
||||
|
||||
|
@ -57,7 +53,7 @@ The rendered content of the response. The `.render()` method must have been cal
|
|||
|
||||
## .template_name
|
||||
|
||||
The `template_name`, if supplied. Only required if `HTMLRenderer` or some other custom template renderer is the accepted renderer for the response.
|
||||
The `template_name`, if supplied. Only required if `HTMLRenderer` or some other custom template renderer is the accepted renderer for the reponse.
|
||||
|
||||
## .accepted_renderer
|
||||
|
||||
|
@ -93,6 +89,6 @@ The `Response` class extends `SimpleTemplateResponse`, and all the usual attribu
|
|||
As with any other `TemplateResponse`, this method is called to render the serialized data of the response into the final response content. When `.render()` is called, the response content will be set to the result of calling the `.render(data, accepted_media_type, renderer_context)` method on the `accepted_renderer` instance.
|
||||
|
||||
You won't typically need to call `.render()` yourself, as it's handled by Django's standard response cycle.
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/ref/template-response/
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/
|
||||
[statuscodes]: status-codes.md
|
||||
|
|
|
@ -1,7 +1,4 @@
|
|||
---
|
||||
source:
|
||||
- reverse.py
|
||||
---
|
||||
<a class="github" href="reverse.py"></a>
|
||||
|
||||
# Returning URLs
|
||||
|
||||
|
@ -20,39 +17,39 @@ The advantages of doing so are:
|
|||
|
||||
REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.
|
||||
|
||||
There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier.
|
||||
There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink it's output for you, which makes browsing the API much easier.
|
||||
|
||||
## reverse
|
||||
|
||||
**Signature:** `reverse(viewname, *args, **kwargs)`
|
||||
|
||||
Has the same behavior as [`django.urls.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port.
|
||||
Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port.
|
||||
|
||||
You should **include the request as a keyword argument** to the function, for example:
|
||||
|
||||
import datetime
|
||||
from rest_framework.reverse import reverse
|
||||
from rest_framework.views import APIView
|
||||
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 = datetime.datetime.now().year
|
||||
data = {
|
||||
...
|
||||
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
||||
}
|
||||
return Response(data)
|
||||
return Response(data)
|
||||
|
||||
## reverse_lazy
|
||||
|
||||
**Signature:** `reverse_lazy(viewname, *args, **kwargs)`
|
||||
|
||||
Has the same behavior as [`django.urls.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port.
|
||||
Has the same behavior as [`django.core.urlresolvers.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port.
|
||||
|
||||
As with the `reverse` function, you should **include the request as a keyword argument** to the function, for example:
|
||||
|
||||
api_root = reverse_lazy('api-root', request=request)
|
||||
|
||||
[cite]: https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5
|
||||
[reverse]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse
|
||||
[reverse-lazy]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse-lazy
|
||||
[cite]: http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5
|
||||
[reverse]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
|
||||
[reverse-lazy]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
|
||||
|
|
|
@ -1,355 +0,0 @@
|
|||
---
|
||||
source:
|
||||
- routers.py
|
||||
---
|
||||
|
||||
# Routers
|
||||
|
||||
> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.
|
||||
>
|
||||
> — [Ruby on Rails Documentation][cite]
|
||||
|
||||
Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.
|
||||
|
||||
REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.
|
||||
|
||||
## Usage
|
||||
|
||||
Here's an example of a simple URL conf, that uses `SimpleRouter`.
|
||||
|
||||
from rest_framework import routers
|
||||
|
||||
router = routers.SimpleRouter()
|
||||
router.register(r'users', UserViewSet)
|
||||
router.register(r'accounts', AccountViewSet)
|
||||
urlpatterns = router.urls
|
||||
|
||||
There are two mandatory arguments to the `register()` method:
|
||||
|
||||
* `prefix` - The URL prefix to use for this set of routes.
|
||||
* `viewset` - The viewset class.
|
||||
|
||||
Optionally, you may also specify an additional argument:
|
||||
|
||||
* `basename` - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the `queryset` attribute of the viewset, if it has one. Note that if the viewset does not include a `queryset` attribute then you must set `basename` when registering the viewset.
|
||||
|
||||
The example above would generate the following URL patterns:
|
||||
|
||||
* URL pattern: `^users/$` Name: `'user-list'`
|
||||
* URL pattern: `^users/{pk}/$` Name: `'user-detail'`
|
||||
* URL pattern: `^accounts/$` Name: `'account-list'`
|
||||
* URL pattern: `^accounts/{pk}/$` Name: `'account-detail'`
|
||||
|
||||
---
|
||||
|
||||
**Note**: The `basename` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part.
|
||||
|
||||
Typically you won't *need* to specify the `basename` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this:
|
||||
|
||||
'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
|
||||
|
||||
This means you'll need to explicitly set the `basename` argument when registering the viewset, as it could not be automatically determined from the model name.
|
||||
|
||||
---
|
||||
|
||||
### Using `include` with routers
|
||||
|
||||
The `.urls` attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs.
|
||||
|
||||
For example, you can append `router.urls` to a list of existing views...
|
||||
|
||||
router = routers.SimpleRouter()
|
||||
router.register(r'users', UserViewSet)
|
||||
router.register(r'accounts', AccountViewSet)
|
||||
|
||||
urlpatterns = [
|
||||
path('forgot-password/', ForgotPasswordFormView.as_view()),
|
||||
]
|
||||
|
||||
urlpatterns += router.urls
|
||||
|
||||
Alternatively you can use Django's `include` function, like so...
|
||||
|
||||
urlpatterns = [
|
||||
path('forgot-password', ForgotPasswordFormView.as_view()),
|
||||
path('', include(router.urls)),
|
||||
]
|
||||
|
||||
You may use `include` with an application namespace:
|
||||
|
||||
urlpatterns = [
|
||||
path('forgot-password/', ForgotPasswordFormView.as_view()),
|
||||
path('api/', include((router.urls, 'app_name'))),
|
||||
]
|
||||
|
||||
Or both an application and instance namespace:
|
||||
|
||||
urlpatterns = [
|
||||
path('forgot-password/', ForgotPasswordFormView.as_view()),
|
||||
path('api/', include((router.urls, 'app_name'), namespace='instance_name')),
|
||||
]
|
||||
|
||||
See Django's [URL namespaces docs][url-namespace-docs] and the [`include` API reference][include-api-reference] for more details.
|
||||
|
||||
---
|
||||
|
||||
**Note**: If using namespacing with hyperlinked serializers you'll also need to ensure that any `view_name` parameters
|
||||
on the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as
|
||||
`view_name='app_name:user-detail'` for serializer fields hyperlinked to the user detail view.
|
||||
|
||||
The automatic `view_name` generation uses a pattern like `%(model_name)-detail`. Unless your models names actually clash
|
||||
you may be better off **not** namespacing your Django REST Framework views when using hyperlinked serializers.
|
||||
|
||||
---
|
||||
|
||||
### Routing for extra actions
|
||||
|
||||
A viewset may [mark extra actions for routing][route-decorators] by decorating a method with the `@action` decorator. These extra actions will be included in the generated routes. For example, given the `set_password` method on the `UserViewSet` class:
|
||||
|
||||
from myapp.permissions import IsAdminOrIsSelf
|
||||
from rest_framework.decorators import action
|
||||
|
||||
class UserViewSet(ModelViewSet):
|
||||
...
|
||||
|
||||
@action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])
|
||||
def set_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
The following route would be generated:
|
||||
|
||||
* URL pattern: `^users/{pk}/set_password/$`
|
||||
* URL name: `'user-set-password'`
|
||||
|
||||
By default, the URL pattern is based on the method name, and the URL name is the combination of the `ViewSet.basename` and the hyphenated method name.
|
||||
If you don't want to use the defaults for either of these values, you can instead provide the `url_path` and `url_name` arguments to the `@action` decorator.
|
||||
|
||||
For example, if you want to change the URL for our custom action to `^users/{pk}/change-password/$`, you could write:
|
||||
|
||||
from myapp.permissions import IsAdminOrIsSelf
|
||||
from rest_framework.decorators import action
|
||||
|
||||
class UserViewSet(ModelViewSet):
|
||||
...
|
||||
|
||||
@action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf],
|
||||
url_path='change-password', url_name='change_password')
|
||||
def set_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
The above example would now generate the following URL pattern:
|
||||
|
||||
* URL path: `^users/{pk}/change-password/$`
|
||||
* URL name: `'user-change_password'`
|
||||
|
||||
### Using Django `path()` with routers
|
||||
|
||||
By default, the URLs created by routers use regular expressions. This behavior can be modified by setting the `use_regex_path` argument to `False` when instantiating the router, in this case [path converters][path-converters-topic-reference] are used. For example:
|
||||
|
||||
router = SimpleRouter(use_regex_path=False)
|
||||
|
||||
The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset or `lookup_value_converter` if using path converters. For example, you can limit the lookup to valid UUIDs:
|
||||
|
||||
class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
|
||||
lookup_field = 'my_model_id'
|
||||
lookup_value_regex = '[0-9a-f]{32}'
|
||||
|
||||
class MyPathModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
|
||||
lookup_field = 'my_model_uuid'
|
||||
lookup_value_converter = 'uuid'
|
||||
|
||||
Note that path converters will be used on all URLs registered in the router, including viewset actions.
|
||||
|
||||
# API Guide
|
||||
|
||||
## SimpleRouter
|
||||
|
||||
This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@action` decorator.
|
||||
|
||||
<table border=1>
|
||||
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
|
||||
<tr><td rowspan=2>{prefix}/</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
|
||||
<tr><td>POST</td><td>create</td></tr>
|
||||
<tr><td>{prefix}/{url_path}/</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=False)` decorated method</td><td>{basename}-{url_name}</td></tr>
|
||||
<tr><td rowspan=4>{prefix}/{lookup}/</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
|
||||
<tr><td>PUT</td><td>update</td></tr>
|
||||
<tr><td>PATCH</td><td>partial_update</td></tr>
|
||||
<tr><td>DELETE</td><td>destroy</td></tr>
|
||||
<tr><td>{prefix}/{lookup}/{url_path}/</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=True)` decorated method</td><td>{basename}-{url_name}</td></tr>
|
||||
</table>
|
||||
|
||||
By default, the URLs created by `SimpleRouter` are appended with a trailing slash.
|
||||
This behavior can be modified by setting the `trailing_slash` argument to `False` when instantiating the router. For example:
|
||||
|
||||
router = SimpleRouter(trailing_slash=False)
|
||||
|
||||
Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.
|
||||
|
||||
## DefaultRouter
|
||||
|
||||
This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes.
|
||||
|
||||
<table border=1>
|
||||
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
|
||||
<tr><td>[.format]</td><td>GET</td><td>automatically generated root view</td><td>api-root</td></tr></tr>
|
||||
<tr><td rowspan=2>{prefix}/[.format]</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
|
||||
<tr><td>POST</td><td>create</td></tr>
|
||||
<tr><td>{prefix}/{url_path}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=False)` decorated method</td><td>{basename}-{url_name}</td></tr>
|
||||
<tr><td rowspan=4>{prefix}/{lookup}/[.format]</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
|
||||
<tr><td>PUT</td><td>update</td></tr>
|
||||
<tr><td>PATCH</td><td>partial_update</td></tr>
|
||||
<tr><td>DELETE</td><td>destroy</td></tr>
|
||||
<tr><td>{prefix}/{lookup}/{url_path}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=True)` decorated method</td><td>{basename}-{url_name}</td></tr>
|
||||
</table>
|
||||
|
||||
As with `SimpleRouter` the trailing slashes on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router.
|
||||
|
||||
router = DefaultRouter(trailing_slash=False)
|
||||
|
||||
# Custom Routers
|
||||
|
||||
Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.
|
||||
|
||||
The simplest way to implement a custom router is to subclass one of the existing router classes. The `.routes` attribute is used to template the URL patterns that will be mapped to each viewset. The `.routes` attribute is a list of `Route` named tuples.
|
||||
|
||||
The arguments to the `Route` named tuple are:
|
||||
|
||||
**url**: A string representing the URL to be routed. May include the following format strings:
|
||||
|
||||
* `{prefix}` - The URL prefix to use for this set of routes.
|
||||
* `{lookup}` - The lookup field used to match against a single instance.
|
||||
* `{trailing_slash}` - Either a '/' or an empty string, depending on the `trailing_slash` argument.
|
||||
|
||||
**mapping**: A mapping of HTTP method names to the view methods
|
||||
|
||||
**name**: The name of the URL as used in `reverse` calls. May include the following format string:
|
||||
|
||||
* `{basename}` - The base to use for the URL names that are created.
|
||||
|
||||
**initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the `detail`, `basename`, and `suffix` arguments are reserved for viewset introspection and are also used by the browsable API to generate the view name and breadcrumb links.
|
||||
|
||||
## Customizing dynamic routes
|
||||
|
||||
You can also customize how the `@action` decorator is routed. Include the `DynamicRoute` named tuple in the `.routes` list, setting the `detail` argument as appropriate for the list-based and detail-based routes. In addition to `detail`, the arguments to `DynamicRoute` are:
|
||||
|
||||
**url**: A string representing the URL to be routed. May include the same format strings as `Route`, and additionally accepts the `{url_path}` format string.
|
||||
|
||||
**name**: The name of the URL as used in `reverse` calls. May include the following format strings:
|
||||
|
||||
* `{basename}` - The base to use for the URL names that are created.
|
||||
* `{url_name}` - The `url_name` provided to the `@action`.
|
||||
|
||||
**initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view.
|
||||
|
||||
## Example
|
||||
|
||||
The following example will only route to the `list` and `retrieve` actions, and does not use the trailing slash convention.
|
||||
|
||||
from rest_framework.routers import Route, DynamicRoute, SimpleRouter
|
||||
|
||||
class CustomReadOnlyRouter(SimpleRouter):
|
||||
"""
|
||||
A router for read-only APIs, which doesn't use trailing slashes.
|
||||
"""
|
||||
routes = [
|
||||
Route(
|
||||
url=r'^{prefix}$',
|
||||
mapping={'get': 'list'},
|
||||
name='{basename}-list',
|
||||
detail=False,
|
||||
initkwargs={'suffix': 'List'}
|
||||
),
|
||||
Route(
|
||||
url=r'^{prefix}/{lookup}$',
|
||||
mapping={'get': 'retrieve'},
|
||||
name='{basename}-detail',
|
||||
detail=True,
|
||||
initkwargs={'suffix': 'Detail'}
|
||||
),
|
||||
DynamicRoute(
|
||||
url=r'^{prefix}/{lookup}/{url_path}$',
|
||||
name='{basename}-{url_name}',
|
||||
detail=True,
|
||||
initkwargs={}
|
||||
)
|
||||
]
|
||||
|
||||
Let's take a look at the routes our `CustomReadOnlyRouter` would generate for a simple viewset.
|
||||
|
||||
`views.py`:
|
||||
|
||||
class UserViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
"""
|
||||
A viewset that provides the standard actions
|
||||
"""
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
lookup_field = 'username'
|
||||
|
||||
@action(detail=True)
|
||||
def group_names(self, request, pk=None):
|
||||
"""
|
||||
Returns a list of all the group names that the given
|
||||
user belongs to.
|
||||
"""
|
||||
user = self.get_object()
|
||||
groups = user.groups.all()
|
||||
return Response([group.name for group in groups])
|
||||
|
||||
`urls.py`:
|
||||
|
||||
router = CustomReadOnlyRouter()
|
||||
router.register('users', UserViewSet)
|
||||
urlpatterns = router.urls
|
||||
|
||||
The following mappings would be generated...
|
||||
|
||||
<table border=1>
|
||||
<tr><th>URL</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
|
||||
<tr><td>/users</td><td>GET</td><td>list</td><td>user-list</td></tr>
|
||||
<tr><td>/users/{username}</td><td>GET</td><td>retrieve</td><td>user-detail</td></tr>
|
||||
<tr><td>/users/{username}/group_names</td><td>GET</td><td>group_names</td><td>user-group-names</td></tr>
|
||||
</table>
|
||||
|
||||
For another example of setting the `.routes` attribute, see the source code for the `SimpleRouter` class.
|
||||
|
||||
## Advanced custom routers
|
||||
|
||||
If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute.
|
||||
|
||||
You may also want to override the `get_default_basename(self, viewset)` method, or else always explicitly set the `basename` argument when registering your viewsets with the router.
|
||||
|
||||
# Third Party Packages
|
||||
|
||||
The following third party packages are also available.
|
||||
|
||||
## DRF Nested Routers
|
||||
|
||||
The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources.
|
||||
|
||||
## ModelRouter (wq.db.rest)
|
||||
|
||||
The [wq.db package][wq.db] provides an advanced [ModelRouter][wq.db-router] class (and singleton instance) that extends `DefaultRouter` with a `register_model()` API. Much like Django's `admin.site.register`, the only required argument to `rest.router.register_model` is a model class. Reasonable defaults for a url prefix, serializer, and viewset will be inferred from the model and global configuration.
|
||||
|
||||
from wq.db import rest
|
||||
from myapp.models import MyModel
|
||||
|
||||
rest.router.register_model(MyModel)
|
||||
|
||||
## DRF-extensions
|
||||
|
||||
The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions-routers] for creating [nested viewsets][drf-extensions-nested-viewsets], [collection level controllers][drf-extensions-collection-level-controllers] with [customizable endpoint names][drf-extensions-customizable-endpoint-names].
|
||||
|
||||
[cite]: https://guides.rubyonrails.org/routing.html
|
||||
[route-decorators]: viewsets.md#marking-extra-actions-for-routing
|
||||
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
|
||||
[wq.db]: https://wq.io/wq.db
|
||||
[wq.db-router]: https://wq.io/docs/router
|
||||
[drf-extensions]: https://chibisov.github.io/drf-extensions/docs/
|
||||
[drf-extensions-routers]: https://chibisov.github.io/drf-extensions/docs/#routers
|
||||
[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/stable/topics/http/urls/#url-namespaces
|
||||
[include-api-reference]: https://docs.djangoproject.com/en/stable/ref/urls/#include
|
||||
[path-converters-topic-reference]: https://docs.djangoproject.com/en/stable/topics/http/urls/#path-converters
|
|
@ -1,465 +0,0 @@
|
|||
---
|
||||
source:
|
||||
- schemas
|
||||
---
|
||||
|
||||
# Schema
|
||||
|
||||
> 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]
|
||||
|
||||
---
|
||||
|
||||
**Deprecation notice:**
|
||||
|
||||
REST framework's built-in support for generating OpenAPI schemas is
|
||||
**deprecated** in favor of 3rd party packages that can provide this
|
||||
functionality instead. The built-in support will be moved into a separate
|
||||
package and then subsequently retired over the next releases.
|
||||
|
||||
As a full-fledged replacement, we recommend the [drf-spectacular] package.
|
||||
It has extensive support for generating OpenAPI 3 schemas from
|
||||
REST framework APIs, with both automatic and customisable options available.
|
||||
For further information please refer to
|
||||
[Documenting your API](../topics/documenting-your-api.md#drf-spectacular).
|
||||
|
||||
---
|
||||
|
||||
API schemas are a useful tool that allow for a range of use cases, including
|
||||
generating reference documentation, or driving dynamic client libraries that
|
||||
can interact with your API.
|
||||
|
||||
Django REST Framework provides support for automatic generation of
|
||||
[OpenAPI][openapi] schemas.
|
||||
|
||||
## Overview
|
||||
|
||||
Schema generation has several moving parts. It's worth having an overview:
|
||||
|
||||
* `SchemaGenerator` is a top-level class that is responsible for walking your
|
||||
configured URL patterns, finding `APIView` subclasses, enquiring for their
|
||||
schema representation, and compiling the final schema object.
|
||||
* `AutoSchema` encapsulates all the details necessary for per-view schema
|
||||
introspection. Is attached to each view via the `schema` attribute. You
|
||||
subclass `AutoSchema` in order to customize your schema.
|
||||
* The `generateschema` management command allows you to generate a static schema
|
||||
offline.
|
||||
* Alternatively, you can route `SchemaView` to dynamically generate and serve
|
||||
your schema.
|
||||
* `settings.DEFAULT_SCHEMA_CLASS` allows you to specify an `AutoSchema`
|
||||
subclass to serve as your project's default.
|
||||
|
||||
The following sections explain more.
|
||||
|
||||
## Generating an OpenAPI Schema
|
||||
|
||||
### Install dependencies
|
||||
|
||||
pip install pyyaml uritemplate inflection
|
||||
|
||||
* `pyyaml` is used to generate schema into YAML-based OpenAPI format.
|
||||
* `uritemplate` is used internally to get parameters in path.
|
||||
* `inflection` is used to pluralize operations more appropriately in the list endpoints.
|
||||
|
||||
### Generating a static schema with the `generateschema` management command
|
||||
|
||||
If your schema is static, you can use the `generateschema` management command:
|
||||
|
||||
```bash
|
||||
./manage.py generateschema --file openapi-schema.yml
|
||||
```
|
||||
|
||||
Once you've generated a schema in this way you can annotate it with any
|
||||
additional information that cannot be automatically inferred by the schema
|
||||
generator.
|
||||
|
||||
You might want to check your API schema into version control and update it
|
||||
with each new release, or serve the API schema from your site's static media.
|
||||
|
||||
### Generating a dynamic schema with `SchemaView`
|
||||
|
||||
If you require a dynamic schema, because foreign key choices depend on database
|
||||
values, for example, you can route a `SchemaView` that will generate and serve
|
||||
your schema on demand.
|
||||
|
||||
To route a `SchemaView`, use the `get_schema_view()` helper.
|
||||
|
||||
In `urls.py`:
|
||||
|
||||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
|
||||
urlpatterns = [
|
||||
# ...
|
||||
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
|
||||
# * `title` and `description` parameters are passed to `SchemaGenerator`.
|
||||
# * Provide view name for use with `reverse()`.
|
||||
path(
|
||||
"openapi",
|
||||
get_schema_view(
|
||||
title="Your Project", description="API for all things …", version="1.0.0"
|
||||
),
|
||||
name="openapi-schema",
|
||||
),
|
||||
# ...
|
||||
]
|
||||
```
|
||||
|
||||
#### `get_schema_view()`
|
||||
|
||||
The `get_schema_view()` helper takes the following keyword arguments:
|
||||
|
||||
* `title`: May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Longer descriptive text.
|
||||
* `version`: The version of the API.
|
||||
* `url`: May be used to pass a canonical base URL for the schema.
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/'
|
||||
)
|
||||
|
||||
* `urlconf`: A string representing the import path to the URL conf that you want
|
||||
to generate an API schema for. This defaults to the value of Django's
|
||||
`ROOT_URLCONF` setting.
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
urlconf='myproject.urls'
|
||||
)
|
||||
|
||||
* `patterns`: List of url patterns to limit the schema introspection to. If you
|
||||
only want the `myproject.api` urls to be exposed in the schema:
|
||||
|
||||
schema_url_patterns = [
|
||||
path('api/', include('myproject.api.urls')),
|
||||
]
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
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`.
|
||||
* `authentication_classes`: May be used to specify the list of authentication
|
||||
classes that will apply to the schema endpoint. Defaults to
|
||||
`settings.DEFAULT_AUTHENTICATION_CLASSES`
|
||||
* `permission_classes`: May be used to specify the list of permission classes
|
||||
that will apply to the schema endpoint. Defaults to
|
||||
`settings.DEFAULT_PERMISSION_CLASSES`.
|
||||
* `renderer_classes`: May be used to pass the set of renderer classes that can
|
||||
be used to render the API root endpoint.
|
||||
|
||||
|
||||
## SchemaGenerator
|
||||
|
||||
**Schema-level customization**
|
||||
|
||||
```python
|
||||
from rest_framework.schemas.openapi import SchemaGenerator
|
||||
```
|
||||
|
||||
`SchemaGenerator` is a class that walks a list of routed URL patterns, requests
|
||||
the schema for each view and collates the resulting OpenAPI schema.
|
||||
|
||||
Typically you won't need to instantiate `SchemaGenerator` yourself, but you can
|
||||
do so like so:
|
||||
|
||||
generator = SchemaGenerator(title='Stock Prices API')
|
||||
|
||||
Arguments:
|
||||
|
||||
* `title` **required**: The name of the API.
|
||||
* `description`: Longer descriptive text.
|
||||
* `version`: The version of the API. Defaults to `0.1.0`.
|
||||
* `url`: The root URL of the API schema. This option is not required unless the schema is included under path prefix.
|
||||
* `patterns`: A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.
|
||||
* `urlconf`: A URL conf module name to use when generating the schema. Defaults to `settings.ROOT_URLCONF`.
|
||||
|
||||
In order to customize the top-level schema, subclass
|
||||
`rest_framework.schemas.openapi.SchemaGenerator` and provide your subclass
|
||||
as an argument to the `generateschema` command or `get_schema_view()` helper
|
||||
function.
|
||||
|
||||
### get_schema(self, request=None, public=False)
|
||||
|
||||
Returns a dictionary that represents the OpenAPI schema:
|
||||
|
||||
generator = SchemaGenerator(title='Stock Prices API')
|
||||
schema = generator.get_schema()
|
||||
|
||||
The `request` argument is optional, and may be used if you want to apply
|
||||
per-user permissions to the resulting schema generation.
|
||||
|
||||
This is a good point to override if you want to customize the generated
|
||||
dictionary For example you might wish to add terms of service to the [top-level
|
||||
`info` object][info-object]:
|
||||
|
||||
```
|
||||
class TOSSchemaGenerator(SchemaGenerator):
|
||||
def get_schema(self, *args, **kwargs):
|
||||
schema = super().get_schema(*args, **kwargs)
|
||||
schema["info"]["termsOfService"] = "https://example.com/tos.html"
|
||||
return schema
|
||||
```
|
||||
|
||||
## AutoSchema
|
||||
|
||||
**Per-View Customization**
|
||||
|
||||
```python
|
||||
from rest_framework.schemas.openapi import AutoSchema
|
||||
```
|
||||
|
||||
By default, view introspection is performed by an `AutoSchema` instance
|
||||
accessible via the `schema` attribute on `APIView`.
|
||||
|
||||
auto_schema = some_view.schema
|
||||
|
||||
`AutoSchema` provides the OpenAPI elements needed for each view, request method
|
||||
and path:
|
||||
|
||||
* A list of [OpenAPI components][openapi-components]. In DRF terms these are
|
||||
mappings of serializers that describe request and response bodies.
|
||||
* The appropriate [OpenAPI operation object][openapi-operation] that describes
|
||||
the endpoint, including path and query parameters for pagination, filtering,
|
||||
and so on.
|
||||
|
||||
```python
|
||||
components = auto_schema.get_components(...)
|
||||
operation = auto_schema.get_operation(...)
|
||||
```
|
||||
|
||||
In compiling the schema, `SchemaGenerator` calls `get_components()` and
|
||||
`get_operation()` for each view, allowed method, and path.
|
||||
|
||||
----
|
||||
|
||||
**Note**: The automatic introspection of components, and many operation
|
||||
parameters relies on the relevant attributes and methods of
|
||||
`GenericAPIView`: `get_serializer()`, `pagination_class`, `filter_backends`,
|
||||
etc. For basic `APIView` subclasses, default introspection is essentially limited to
|
||||
the URL kwarg path parameters for this reason.
|
||||
|
||||
----
|
||||
|
||||
`AutoSchema` encapsulates the view introspection needed for schema generation.
|
||||
Because of this all the schema generation logic is kept in a single place,
|
||||
rather than being spread around the already extensive view, serializer and
|
||||
field APIs.
|
||||
|
||||
Keeping with this pattern, try not to let schema logic leak into your own
|
||||
views, serializers, or fields when customizing the schema generation. You might
|
||||
be tempted to do something like this:
|
||||
|
||||
```python
|
||||
class CustomSchema(AutoSchema):
|
||||
"""
|
||||
AutoSchema subclass using schema_extra_info on the view.
|
||||
"""
|
||||
|
||||
...
|
||||
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = CustomSchema()
|
||||
schema_extra_info = ... # some extra info
|
||||
```
|
||||
|
||||
Here, the `AutoSchema` subclass goes looking for `schema_extra_info` on the
|
||||
view. This is _OK_ (it doesn't actually hurt) but it means you'll end up with
|
||||
your schema logic spread out in a number of different places.
|
||||
|
||||
Instead try to subclass `AutoSchema` such that the `extra_info` doesn't leak
|
||||
out into the view:
|
||||
|
||||
```python
|
||||
class BaseSchema(AutoSchema):
|
||||
"""
|
||||
AutoSchema subclass that knows how to use extra_info.
|
||||
"""
|
||||
|
||||
...
|
||||
|
||||
|
||||
class CustomSchema(BaseSchema):
|
||||
extra_info = ... # some extra info
|
||||
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = CustomSchema()
|
||||
```
|
||||
|
||||
This style is slightly more verbose but maintains the encapsulation of the
|
||||
schema related code. It's more _cohesive_ in the _parlance_. It'll keep the
|
||||
rest of your API code more tidy.
|
||||
|
||||
If an option applies to many view classes, rather than creating a specific
|
||||
subclass per-view, you may find it more convenient to allow specifying the
|
||||
option as an `__init__()` kwarg to your base `AutoSchema` subclass:
|
||||
|
||||
```python
|
||||
class CustomSchema(BaseSchema):
|
||||
def __init__(self, **kwargs):
|
||||
# store extra_info for later
|
||||
self.extra_info = kwargs.pop("extra_info")
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = CustomSchema(extra_info=...) # some extra info
|
||||
```
|
||||
|
||||
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
|
||||
the more commonly needed options do.
|
||||
|
||||
### `AutoSchema` methods
|
||||
|
||||
#### `get_components()`
|
||||
|
||||
Generates the OpenAPI components that describe request and response bodies,
|
||||
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
|
||||
`get_components()` to return multiple pairs if your view uses multiple
|
||||
serializers.
|
||||
|
||||
#### `get_component_name()`
|
||||
|
||||
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.
|
||||
|
||||
Most serializers should conform to the standard OpenAPI `object` type, but you may
|
||||
wish to override `map_serializer()` in order to customize this or other
|
||||
serializer-level fields.
|
||||
|
||||
#### `map_field()`
|
||||
|
||||
Maps individual serializer fields to their schema representation. The base implementation
|
||||
will handle the default fields that Django REST Framework provides.
|
||||
|
||||
For `SerializerMethodField` instances, for which the schema is unknown, or custom field subclasses you should override `map_field()` to generate the correct schema:
|
||||
|
||||
```python
|
||||
class CustomSchema(AutoSchema):
|
||||
"""Extension of ``AutoSchema`` to add support for custom field schemas."""
|
||||
|
||||
def map_field(self, field):
|
||||
# Handle SerializerMethodFields or custom fields here...
|
||||
# ...
|
||||
return super().map_field(field)
|
||||
```
|
||||
|
||||
Authors of third-party packages should aim to provide an `AutoSchema` subclass,
|
||||
and a mixin, overriding `map_field()` so that users can easily generate schemas
|
||||
for their custom fields.
|
||||
|
||||
#### `get_tags()`
|
||||
|
||||
OpenAPI groups operations by tags. By default tags taken from the first path
|
||||
segment of the routed URL. For example, a URL like `/users/{id}/` will generate
|
||||
the tag `users`.
|
||||
|
||||
You can pass an `__init__()` kwarg to manually specify tags (see below), or
|
||||
override `get_tags()` to provide custom logic.
|
||||
|
||||
#### `get_operation()`
|
||||
|
||||
Returns the [OpenAPI operation object][openapi-operation] that describes the
|
||||
endpoint, including path and query parameters for pagination, filtering, and so
|
||||
on.
|
||||
|
||||
Together with `get_components()`, this is the main entry point to the view
|
||||
introspection.
|
||||
|
||||
#### `get_operation_id()`
|
||||
|
||||
There must be a unique [operationid](openapi-operationid) for each operation.
|
||||
By default the `operationId` is deduced from the model name, serializer name or
|
||||
view name. The operationId looks like "listItems", "retrieveItem",
|
||||
"updateItem", etc. The `operationId` is camelCase by convention.
|
||||
|
||||
#### `get_operation_id_base()`
|
||||
|
||||
If you have several views with the same model name, you may see duplicate
|
||||
operationIds.
|
||||
|
||||
In order to work around this, you can override `get_operation_id_base()` to
|
||||
provide a different base for name part of the ID.
|
||||
|
||||
#### `get_serializer()`
|
||||
|
||||
If the view has implemented `get_serializer()`, returns the result.
|
||||
|
||||
#### `get_request_serializer()`
|
||||
|
||||
By default returns `get_serializer()` but can be overridden to
|
||||
differentiate between request and response objects.
|
||||
|
||||
#### `get_response_serializer()`
|
||||
|
||||
By default returns `get_serializer()` but can be overridden to
|
||||
differentiate between request and response objects.
|
||||
|
||||
### `AutoSchema.__init__()` kwargs
|
||||
|
||||
`AutoSchema` provides a number of `__init__()` kwargs that can be used for
|
||||
common customizations, if the default generated values are not appropriate.
|
||||
|
||||
The available kwargs are:
|
||||
|
||||
* `tags`: Specify a list of tags.
|
||||
* `component_name`: Specify the component name.
|
||||
* `operation_id_base`: Specify the resource-name part of operation IDs.
|
||||
|
||||
You pass the kwargs when declaring the `AutoSchema` instance on your view:
|
||||
|
||||
```
|
||||
class PetDetailView(generics.RetrieveUpdateDestroyAPIView):
|
||||
schema = AutoSchema(
|
||||
tags=['Pets'],
|
||||
component_name='Pet',
|
||||
operation_id_base='Pet',
|
||||
)
|
||||
...
|
||||
```
|
||||
|
||||
Assuming a `Pet` model and `PetSerializer` serializer, the kwargs in this
|
||||
example are probably not needed. Often, though, you'll need to pass the kwargs
|
||||
if you have multiple view targeting the same model, or have multiple views with
|
||||
identically named serializers.
|
||||
|
||||
If your views have related customizations that are needed frequently, you can
|
||||
create a base `AutoSchema` subclass for your project that takes additional
|
||||
`__init__()` kwargs to save subclassing `AutoSchema` for each view.
|
||||
|
||||
[cite]: https://www.heroku.com/blog/json_schema_for_heroku_platform_api/
|
||||
[openapi]: https://github.com/OAI/OpenAPI-Specification
|
||||
[openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions
|
||||
[openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject
|
||||
[openapi-tags]: https://swagger.io/specification/#tagObject
|
||||
[openapi-operationid]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#fixed-fields-17
|
||||
[openapi-components]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#componentsObject
|
||||
[openapi-reference]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#referenceObject
|
||||
[openapi-generator]: https://github.com/OpenAPITools/openapi-generator
|
||||
[swagger-codegen]: https://github.com/swagger-api/swagger-codegen
|
||||
[info-object]: https://swagger.io/specification/#infoObject
|
||||
[drf-spectacular]: https://drf-spectacular.readthedocs.io/en/latest/readme.html
|
|
@ -1,7 +1,4 @@
|
|||
---
|
||||
source:
|
||||
- settings.py
|
||||
---
|
||||
<a class="github" href="settings.py"></a>
|
||||
|
||||
# Settings
|
||||
|
||||
|
@ -14,12 +11,12 @@ Configuration for REST framework is all namespaced inside a single Django settin
|
|||
For example your project's `settings.py` file might include something like this:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
],
|
||||
'DEFAULT_PARSER_CLASSES': [
|
||||
'rest_framework.parsers.JSONParser',
|
||||
]
|
||||
'DEFAULT_RENDERER_CLASSES': (
|
||||
'rest_framework.renderers.YAMLRenderer',
|
||||
),
|
||||
'DEFAULT_PARSER_CLASSES': (
|
||||
'rest_framework.parsers.YAMLParser',
|
||||
)
|
||||
}
|
||||
|
||||
## Accessing settings
|
||||
|
@ -28,436 +25,145 @@ If you need to access the values of REST framework's API settings in your projec
|
|||
you should use the `api_settings` object. For example.
|
||||
|
||||
from rest_framework.settings import api_settings
|
||||
|
||||
print api_settings.DEFAULT_AUTHENTICATION_CLASSES
|
||||
|
||||
print(api_settings.DEFAULT_AUTHENTICATION_CLASSES)
|
||||
|
||||
The `api_settings` object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal.
|
||||
The `api_settings` object will check for any user-defined settings, and otherwise fallback to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal.
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## API policy settings
|
||||
|
||||
*The following settings control the basic API policies, and are applied to every `APIView` class-based view, or `@api_view` function based view.*
|
||||
|
||||
#### DEFAULT_RENDERER_CLASSES
|
||||
## DEFAULT_RENDERER_CLASSES
|
||||
|
||||
A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a `Response` object.
|
||||
|
||||
Default:
|
||||
|
||||
[
|
||||
(
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
]
|
||||
'rest_framework.renderers.TemplateHTMLRenderer'
|
||||
)
|
||||
|
||||
#### DEFAULT_PARSER_CLASSES
|
||||
## DEFAULT_PARSER_CLASSES
|
||||
|
||||
A list or tuple of parser classes, that determines the default set of parsers used when accessing the `request.data` property.
|
||||
A list or tuple of parser classes, that determines the default set of parsers used when accessing the `request.DATA` property.
|
||||
|
||||
Default:
|
||||
|
||||
[
|
||||
(
|
||||
'rest_framework.parsers.JSONParser',
|
||||
'rest_framework.parsers.FormParser',
|
||||
'rest_framework.parsers.MultiPartParser'
|
||||
]
|
||||
'rest_framework.parsers.FormParser'
|
||||
)
|
||||
|
||||
#### DEFAULT_AUTHENTICATION_CLASSES
|
||||
## DEFAULT_AUTHENTICATION_CLASSES
|
||||
|
||||
A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the `request.user` or `request.auth` properties.
|
||||
|
||||
Default:
|
||||
|
||||
[
|
||||
(
|
||||
'rest_framework.authentication.SessionAuthentication',
|
||||
'rest_framework.authentication.BasicAuthentication'
|
||||
]
|
||||
'rest_framework.authentication.UserBasicAuthentication'
|
||||
)
|
||||
|
||||
#### DEFAULT_PERMISSION_CLASSES
|
||||
## DEFAULT_PERMISSION_CLASSES
|
||||
|
||||
A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list.
|
||||
A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view.
|
||||
|
||||
Default:
|
||||
|
||||
[
|
||||
(
|
||||
'rest_framework.permissions.AllowAny',
|
||||
]
|
||||
)
|
||||
|
||||
#### DEFAULT_THROTTLE_CLASSES
|
||||
## DEFAULT_THROTTLE_CLASSES
|
||||
|
||||
A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.
|
||||
|
||||
Default: `[]`
|
||||
Default: `()`
|
||||
|
||||
#### DEFAULT_CONTENT_NEGOTIATION_CLASS
|
||||
## DEFAULT_MODEL_SERIALIZER_CLASS
|
||||
|
||||
A content negotiation class, that determines how a renderer is selected for the response, given an incoming request.
|
||||
**TODO**
|
||||
|
||||
Default: `'rest_framework.negotiation.DefaultContentNegotiation'`
|
||||
Default: `rest_framework.serializers.ModelSerializer`
|
||||
|
||||
#### DEFAULT_SCHEMA_CLASS
|
||||
## DEFAULT_PAGINATION_SERIALIZER_CLASS
|
||||
|
||||
A view inspector class that will be used for schema generation.
|
||||
**TODO**
|
||||
|
||||
Default: `'rest_framework.schemas.openapi.AutoSchema'`
|
||||
Default: `rest_framework.pagination.PaginationSerializer`
|
||||
|
||||
---
|
||||
## FILTER_BACKEND
|
||||
|
||||
## Generic view settings
|
||||
The filter backend class that should be used for generic filtering. If set to `None` then generic filtering is disabled.
|
||||
|
||||
*The following settings control the behavior of the generic class-based views.*
|
||||
|
||||
#### DEFAULT_FILTER_BACKENDS
|
||||
|
||||
A list of filter backend classes that should be used for generic filtering.
|
||||
If set to `None` then generic filtering is disabled.
|
||||
|
||||
#### DEFAULT_PAGINATION_CLASS
|
||||
|
||||
The default class to use for queryset pagination. If set to `None`, pagination
|
||||
is disabled by default. See the pagination documentation for further guidance on
|
||||
[setting](pagination.md#setting-the-pagination-style) and
|
||||
[modifying](pagination.md#modifying-the-pagination-style) the pagination style.
|
||||
|
||||
Default: `None`
|
||||
|
||||
#### PAGE_SIZE
|
||||
## PAGINATE_BY
|
||||
|
||||
The default page size to use for pagination. If set to `None`, pagination is disabled by default.
|
||||
|
||||
Default: `None`
|
||||
|
||||
### SEARCH_PARAM
|
||||
## PAGINATE_BY_KWARG
|
||||
|
||||
The name of a query parameter, which can be used to specify the search term used by `SearchFilter`.
|
||||
|
||||
Default: `search`
|
||||
|
||||
#### ORDERING_PARAM
|
||||
|
||||
The name of a query parameter, which can be used to specify the ordering of results returned by `OrderingFilter`.
|
||||
|
||||
Default: `ordering`
|
||||
|
||||
---
|
||||
|
||||
## Versioning settings
|
||||
|
||||
#### DEFAULT_VERSION
|
||||
|
||||
The value that should be used for `request.version` when no versioning information is present.
|
||||
The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If set to `None`, clients may not override the default page size.
|
||||
|
||||
Default: `None`
|
||||
|
||||
#### ALLOWED_VERSIONS
|
||||
|
||||
If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set.
|
||||
|
||||
Default: `None`
|
||||
|
||||
#### VERSION_PARAM
|
||||
|
||||
The string that should used for any versioning parameters, such as in the media type or URL query parameters.
|
||||
|
||||
Default: `'version'`
|
||||
|
||||
#### DEFAULT_VERSIONING_CLASS
|
||||
|
||||
The default versioning scheme to use.
|
||||
|
||||
Default: `None`
|
||||
|
||||
---
|
||||
|
||||
## Authentication settings
|
||||
|
||||
*The following settings control the behavior of unauthenticated requests.*
|
||||
|
||||
#### UNAUTHENTICATED_USER
|
||||
## UNAUTHENTICATED_USER
|
||||
|
||||
The class that should be used to initialize `request.user` for unauthenticated requests.
|
||||
(If removing authentication entirely, e.g. by removing `django.contrib.auth` from
|
||||
`INSTALLED_APPS`, set `UNAUTHENTICATED_USER` to `None`.)
|
||||
|
||||
Default: `django.contrib.auth.models.AnonymousUser`
|
||||
|
||||
#### UNAUTHENTICATED_TOKEN
|
||||
## UNAUTHENTICATED_TOKEN
|
||||
|
||||
The class that should be used to initialize `request.auth` for unauthenticated requests.
|
||||
|
||||
Default: `None`
|
||||
|
||||
---
|
||||
## FORM_METHOD_OVERRIDE
|
||||
|
||||
## Test settings
|
||||
The name of a form field that may be used to override the HTTP method of the form.
|
||||
|
||||
*The following settings control the behavior of APIRequestFactory and APIClient*
|
||||
If the value of this setting is `None` then form method overloading will be disabled.
|
||||
|
||||
#### TEST_REQUEST_DEFAULT_FORMAT
|
||||
Default: `'_method'`
|
||||
|
||||
The default format that should be used when making test requests.
|
||||
## FORM_CONTENT_OVERRIDE
|
||||
|
||||
This should match up with the format of one of the renderer classes in the `TEST_REQUEST_RENDERER_CLASSES` setting.
|
||||
The name of a form field that may be used to override the content of the form payload. Must be used together with `FORM_CONTENTTYPE_OVERRIDE`.
|
||||
|
||||
Default: `'multipart'`
|
||||
If either setting is `None` then form content overloading will be disabled.
|
||||
|
||||
#### TEST_REQUEST_RENDERER_CLASSES
|
||||
Default: `'_content'`
|
||||
|
||||
The renderer classes that are supported when building test requests.
|
||||
## FORM_CONTENTTYPE_OVERRIDE
|
||||
|
||||
The format of any of these renderer classes may be used when constructing a test request, for example: `client.post('/users', {'username': 'jamie'}, format='json')`
|
||||
The name of a form field that may be used to override the content type of the form payload. Must be used together with `FORM_CONTENT_OVERRIDE`.
|
||||
|
||||
Default:
|
||||
If either setting is `None` then form content overloading will be disabled.
|
||||
|
||||
[
|
||||
'rest_framework.renderers.MultiPartRenderer',
|
||||
'rest_framework.renderers.JSONRenderer'
|
||||
]
|
||||
Default: `'_content_type'`
|
||||
|
||||
---
|
||||
## URL_ACCEPT_OVERRIDE
|
||||
|
||||
## Schema generation controls
|
||||
The name of a URL parameter that may be used to override the HTTP `Accept` header.
|
||||
|
||||
#### SCHEMA_COERCE_PATH_PK
|
||||
If the value of this setting is `None` then URL accept overloading will be disabled.
|
||||
|
||||
If set, this maps the `'pk'` identifier in the URL conf onto the actual field
|
||||
name when generating a schema path parameter. Typically this will be `'id'`.
|
||||
This gives a more suitable representation as "primary key" is an implementation
|
||||
detail, whereas "identifier" is a more general concept.
|
||||
Default: `'accept'`
|
||||
|
||||
Default: `True`
|
||||
|
||||
#### SCHEMA_COERCE_METHOD_NAMES
|
||||
|
||||
If set, this is used to map internal viewset method names onto external action
|
||||
names used in the schema generation. This allows us to generate names that
|
||||
are more suitable for an external representation than those that are used
|
||||
internally in the codebase.
|
||||
|
||||
Default: `{'retrieve': 'read', 'destroy': 'delete'}`
|
||||
|
||||
---
|
||||
|
||||
## Content type controls
|
||||
|
||||
#### URL_FORMAT_OVERRIDE
|
||||
|
||||
The name of a URL parameter that may be used to override the default content negotiation `Accept` header behavior, by using a `format=…` query parameter in the request URL.
|
||||
|
||||
For example: `http://example.com/organizations/?format=csv`
|
||||
|
||||
If the value of this setting is `None` then URL format overrides will be disabled.
|
||||
## URL_FORMAT_OVERRIDE
|
||||
|
||||
Default: `'format'`
|
||||
|
||||
#### FORMAT_SUFFIX_KWARG
|
||||
## FORMAT_SUFFIX_KWARG
|
||||
|
||||
The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using `format_suffix_patterns` to include suffixed URL patterns.
|
||||
|
||||
For example: `http://example.com/organizations.csv/`
|
||||
**TODO**
|
||||
|
||||
Default: `'format'`
|
||||
|
||||
---
|
||||
|
||||
## Date and time formatting
|
||||
|
||||
*The following settings are used to control how date and time representations may be parsed and rendered.*
|
||||
|
||||
#### DATETIME_FORMAT
|
||||
|
||||
A format string that should be used by default for rendering the output of `DateTimeField` serializer fields. If `None`, then `DateTimeField` serializer fields will return Python `datetime` objects, and the datetime encoding will be determined by the renderer.
|
||||
|
||||
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
|
||||
|
||||
Default: `'iso-8601'`
|
||||
|
||||
#### DATETIME_INPUT_FORMATS
|
||||
|
||||
A list of format strings that should be used by default for parsing inputs to `DateTimeField` serializer fields.
|
||||
|
||||
May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings.
|
||||
|
||||
Default: `['iso-8601']`
|
||||
|
||||
#### DATE_FORMAT
|
||||
|
||||
A format string that should be used by default for rendering the output of `DateField` serializer fields. If `None`, then `DateField` serializer fields will return Python `date` objects, and the date encoding will be determined by the renderer.
|
||||
|
||||
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
|
||||
|
||||
Default: `'iso-8601'`
|
||||
|
||||
#### DATE_INPUT_FORMATS
|
||||
|
||||
A list of format strings that should be used by default for parsing inputs to `DateField` serializer fields.
|
||||
|
||||
May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings.
|
||||
|
||||
Default: `['iso-8601']`
|
||||
|
||||
#### TIME_FORMAT
|
||||
|
||||
A format string that should be used by default for rendering the output of `TimeField` serializer fields. If `None`, then `TimeField` serializer fields will return Python `time` objects, and the time encoding will be determined by the renderer.
|
||||
|
||||
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
|
||||
|
||||
Default: `'iso-8601'`
|
||||
|
||||
#### TIME_INPUT_FORMATS
|
||||
|
||||
A list of format strings that should be used by default for parsing inputs to `TimeField` serializer fields.
|
||||
|
||||
May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings.
|
||||
|
||||
Default: `['iso-8601']`
|
||||
|
||||
---
|
||||
|
||||
## Encodings
|
||||
|
||||
#### UNICODE_JSON
|
||||
|
||||
When set to `True`, JSON responses will allow unicode characters in responses. For example:
|
||||
|
||||
{"unicode black star":"★"}
|
||||
|
||||
When set to `False`, JSON responses will escape non-ascii characters, like so:
|
||||
|
||||
{"unicode black star":"\u2605"}
|
||||
|
||||
Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses.
|
||||
|
||||
Default: `True`
|
||||
|
||||
#### COMPACT_JSON
|
||||
|
||||
When set to `True`, JSON responses will return compact representations, with no spacing after `':'` and `','` characters. For example:
|
||||
|
||||
{"is_admin":false,"email":"jane@example"}
|
||||
|
||||
When set to `False`, JSON responses will return slightly more verbose representations, like so:
|
||||
|
||||
{"is_admin": false, "email": "jane@example"}
|
||||
|
||||
The default style is to return minified responses, in line with [Heroku's API design guidelines][heroku-minified-json].
|
||||
|
||||
Default: `True`
|
||||
|
||||
#### STRICT_JSON
|
||||
|
||||
When set to `True`, JSON rendering and parsing will only observe syntactically valid JSON, raising an exception for the extended float values (`nan`, `inf`, `-inf`) accepted by Python's `json` module. This is the recommended setting, as these values are not generally supported. e.g., neither Javascript's `JSON.Parse` nor PostgreSQL's JSON data type accept these values.
|
||||
|
||||
When set to `False`, JSON rendering and parsing will be permissive. However, these values are still invalid and will need to be specially handled in your code.
|
||||
|
||||
Default: `True`
|
||||
|
||||
#### COERCE_DECIMAL_TO_STRING
|
||||
|
||||
When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations.
|
||||
|
||||
When set to `True`, the serializer `DecimalField` class will return strings instead of `Decimal` objects. When set to `False`, serializers will return `Decimal` objects, which the default JSON encoder will return as floats.
|
||||
|
||||
Default: `True`
|
||||
|
||||
---
|
||||
|
||||
## View names and descriptions
|
||||
|
||||
**The following settings are used to generate the view names and descriptions, as used in responses to `OPTIONS` requests, and as used in the browsable API.**
|
||||
|
||||
#### VIEW_NAME_FUNCTION
|
||||
|
||||
A string representing the function that should be used when generating view names.
|
||||
|
||||
This should be a function with the following signature:
|
||||
|
||||
view_name(self)
|
||||
|
||||
* `self`: The view instance. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `self.__class__.__name__`.
|
||||
|
||||
If the view instance inherits `ViewSet`, it may have been initialized with several optional arguments:
|
||||
|
||||
* `name`: A name explicitly provided to a view in the viewset. Typically, this value should be used as-is when provided.
|
||||
* `suffix`: Text used when differentiating individual views in a viewset. This argument is mutually exclusive to `name`.
|
||||
* `detail`: Boolean that differentiates an individual view in a viewset as either being a 'list' or 'detail' view.
|
||||
|
||||
Default: `'rest_framework.views.get_view_name'`
|
||||
|
||||
#### VIEW_DESCRIPTION_FUNCTION
|
||||
|
||||
A string representing the function that should be used when generating view descriptions.
|
||||
|
||||
This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support `rst` markup in your view docstrings being output in the browsable API.
|
||||
|
||||
This should be a function with the following signature:
|
||||
|
||||
view_description(self, html=False)
|
||||
|
||||
* `self`: The view instance. Typically the description function would inspect the docstring of the class when generating a description, by accessing `self.__class__.__doc__`
|
||||
* `html`: A boolean indicating if HTML output is required. `True` when used in the browsable API, and `False` when used in generating `OPTIONS` responses.
|
||||
|
||||
If the view instance inherits `ViewSet`, it may have been initialized with several optional arguments:
|
||||
|
||||
* `description`: A description explicitly provided to the view in the viewset. Typically, this is set by extra viewset `action`s, and should be used as-is.
|
||||
|
||||
Default: `'rest_framework.views.get_view_description'`
|
||||
|
||||
## HTML Select Field cutoffs
|
||||
|
||||
Global settings for [select field cutoffs for rendering relational fields](relations.md#select-field-cutoffs) in the browsable API.
|
||||
|
||||
#### HTML_SELECT_CUTOFF
|
||||
|
||||
Global setting for the `html_cutoff` value. Must be an integer.
|
||||
|
||||
Default: 1000
|
||||
|
||||
#### HTML_SELECT_CUTOFF_TEXT
|
||||
|
||||
A string representing a global setting for `html_cutoff_text`.
|
||||
|
||||
Default: `"More than {count} items..."`
|
||||
|
||||
---
|
||||
|
||||
## Miscellaneous settings
|
||||
|
||||
#### EXCEPTION_HANDLER
|
||||
|
||||
A string representing the function that should be used when returning a response for any given exception. If the function returns `None`, a 500 error will be raised.
|
||||
|
||||
This setting can be changed to support error responses other than the default `{"detail": "Failure..."}` responses. For example, you can use it to provide API responses like `{"errors": [{"message": "Failure...", "code": ""} ...]}`.
|
||||
|
||||
This should be a function with the following signature:
|
||||
|
||||
exception_handler(exc, context)
|
||||
|
||||
* `exc`: The exception.
|
||||
|
||||
Default: `'rest_framework.views.exception_handler'`
|
||||
|
||||
#### NON_FIELD_ERRORS_KEY
|
||||
|
||||
A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors.
|
||||
|
||||
Default: `'non_field_errors'`
|
||||
|
||||
#### URL_FIELD_NAME
|
||||
|
||||
A string representing the key that should be used for the URL fields generated by `HyperlinkedModelSerializer`.
|
||||
|
||||
Default: `'url'`
|
||||
|
||||
#### NUM_PROXIES
|
||||
|
||||
An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to `None` then less strict IP matching will be used by the throttle classes.
|
||||
|
||||
Default: `None`
|
||||
|
||||
[cite]: https://www.python.org/dev/peps/pep-0020/
|
||||
[rfc4627]: https://www.ietf.org/rfc/rfc4627.txt
|
||||
[heroku-minified-json]: https://github.com/interagent/http-api-design#keep-json-minified-in-all-responses
|
||||
[strftime]: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
|
||||
[cite]: http://www.python.org/dev/peps/pep-0020/
|
||||
|
|
|
@ -1,18 +1,14 @@
|
|||
---
|
||||
source:
|
||||
- status.py
|
||||
---
|
||||
<a class="github" href="status.py"></a>
|
||||
|
||||
# Status Codes
|
||||
|
||||
> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
|
||||
> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
|
||||
>
|
||||
> — [RFC 2324][rfc2324], Hyper Text Coffee Pot Control Protocol
|
||||
|
||||
Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make your code more obvious and readable.
|
||||
Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make more code more obvious and readable.
|
||||
|
||||
from rest_framework import status
|
||||
from rest_framework.response import Response
|
||||
|
||||
def empty_view(self):
|
||||
content = {'please move along': 'nothing to see here'}
|
||||
|
@ -20,18 +16,6 @@ Using bare status codes in your responses isn't recommended. REST framework inc
|
|||
|
||||
The full set of HTTP status codes included in the `status` module is listed below.
|
||||
|
||||
The module also includes a set of helper functions for testing if a status code is in a given range.
|
||||
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APITestCase
|
||||
|
||||
class ExampleTestCase(APITestCase):
|
||||
def test_url_root(self):
|
||||
url = reverse('index')
|
||||
response = self.client.get(url)
|
||||
self.assertTrue(status.is_success(response.status_code))
|
||||
|
||||
|
||||
For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616]
|
||||
and [RFC 6585][rfc6585].
|
||||
|
||||
|
@ -41,8 +25,6 @@ This class of status code indicates a provisional response. There are no 1xx st
|
|||
|
||||
HTTP_100_CONTINUE
|
||||
HTTP_101_SWITCHING_PROTOCOLS
|
||||
HTTP_102_PROCESSING
|
||||
HTTP_103_EARLY_HINTS
|
||||
|
||||
## Successful - 2xx
|
||||
|
||||
|
@ -55,11 +37,8 @@ This class of status code indicates that the client's request was successfully r
|
|||
HTTP_204_NO_CONTENT
|
||||
HTTP_205_RESET_CONTENT
|
||||
HTTP_206_PARTIAL_CONTENT
|
||||
HTTP_207_MULTI_STATUS
|
||||
HTTP_208_ALREADY_REPORTED
|
||||
HTTP_226_IM_USED
|
||||
|
||||
## Redirection - 3xx
|
||||
## Redirection - 3xx
|
||||
|
||||
This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.
|
||||
|
||||
|
@ -71,11 +50,10 @@ This class of status code indicates that further action needs to be taken by the
|
|||
HTTP_305_USE_PROXY
|
||||
HTTP_306_RESERVED
|
||||
HTTP_307_TEMPORARY_REDIRECT
|
||||
HTTP_308_PERMANENT_REDIRECT
|
||||
|
||||
## Client Error - 4xx
|
||||
|
||||
The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
|
||||
The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
|
||||
|
||||
HTTP_400_BAD_REQUEST
|
||||
HTTP_401_UNAUTHORIZED
|
||||
|
@ -95,20 +73,13 @@ The 4xx class of status code is intended for cases in which the client seems to
|
|||
HTTP_415_UNSUPPORTED_MEDIA_TYPE
|
||||
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
|
||||
HTTP_417_EXPECTATION_FAILED
|
||||
HTTP_421_MISDIRECTED_REQUEST
|
||||
HTTP_422_UNPROCESSABLE_ENTITY
|
||||
HTTP_423_LOCKED
|
||||
HTTP_424_FAILED_DEPENDENCY
|
||||
HTTP_425_TOO_EARLY
|
||||
HTTP_426_UPGRADE_REQUIRED
|
||||
HTTP_428_PRECONDITION_REQUIRED
|
||||
HTTP_429_TOO_MANY_REQUESTS
|
||||
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
|
||||
HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS
|
||||
|
||||
## Server Error - 5xx
|
||||
|
||||
Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
|
||||
Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
|
||||
|
||||
HTTP_500_INTERNAL_SERVER_ERROR
|
||||
HTTP_501_NOT_IMPLEMENTED
|
||||
|
@ -116,23 +87,9 @@ Response status codes beginning with the digit "5" indicate cases in which the s
|
|||
HTTP_503_SERVICE_UNAVAILABLE
|
||||
HTTP_504_GATEWAY_TIMEOUT
|
||||
HTTP_505_HTTP_VERSION_NOT_SUPPORTED
|
||||
HTTP_506_VARIANT_ALSO_NEGOTIATES
|
||||
HTTP_507_INSUFFICIENT_STORAGE
|
||||
HTTP_508_LOOP_DETECTED
|
||||
HTTP_509_BANDWIDTH_LIMIT_EXCEEDED
|
||||
HTTP_510_NOT_EXTENDED
|
||||
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED
|
||||
|
||||
## Helper functions
|
||||
|
||||
The following helper functions are available for identifying the category of the response code.
|
||||
|
||||
is_informational() # 1xx
|
||||
is_success() # 2xx
|
||||
is_redirect() # 3xx
|
||||
is_client_error() # 4xx
|
||||
is_server_error() # 5xx
|
||||
|
||||
[rfc2324]: https://www.ietf.org/rfc/rfc2324.txt
|
||||
[rfc2616]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
|
||||
[rfc6585]: https://tools.ietf.org/html/rfc6585
|
||||
[rfc2324]: http://www.ietf.org/rfc/rfc2324.txt
|
||||
[rfc2616]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
|
||||
[rfc6585]: http://tools.ietf.org/html/rfc6585
|
||||
|
|
|
@ -1,421 +0,0 @@
|
|||
---
|
||||
source:
|
||||
- test.py
|
||||
---
|
||||
|
||||
# Testing
|
||||
|
||||
> Code without tests is broken as designed.
|
||||
>
|
||||
> — [Jacob Kaplan-Moss][cite]
|
||||
|
||||
REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.
|
||||
|
||||
# APIRequestFactory
|
||||
|
||||
Extends [Django's existing `RequestFactory` class][requestfactory].
|
||||
|
||||
## Creating test requests
|
||||
|
||||
The `APIRequestFactory` class supports an almost identical API to Django's standard `RequestFactory` class. This means that the standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available.
|
||||
|
||||
from rest_framework.test import APIRequestFactory
|
||||
|
||||
# Using the standard RequestFactory API to create a form POST request
|
||||
factory = APIRequestFactory()
|
||||
request = factory.post('/notes/', {'title': 'new idea'})
|
||||
|
||||
# Using the standard RequestFactory API to encode JSON data
|
||||
request = factory.post('/notes/', {'title': 'new idea'}, content_type='application/json')
|
||||
|
||||
#### Using the `format` argument
|
||||
|
||||
Methods which create a request body, such as `post`, `put` and `patch`, include a `format` argument, which make it easy to generate requests using a wide set of request formats. When using this argument, the factory will select an appropriate renderer and its configured `content_type`. For example:
|
||||
|
||||
# Create a JSON POST request
|
||||
factory = APIRequestFactory()
|
||||
request = factory.post('/notes/', {'title': 'new idea'}, format='json')
|
||||
|
||||
By default the available formats are `'multipart'` and `'json'`. For compatibility with Django's existing `RequestFactory` the default format is `'multipart'`.
|
||||
|
||||
To support a wider set of request formats, or change the default format, [see the configuration section][configuration].
|
||||
|
||||
#### Explicitly encoding the request body
|
||||
|
||||
If you need to explicitly encode the request body, you can do so by setting the `content_type` flag. For example:
|
||||
|
||||
request = factory.post('/notes/', yaml.dump({'title': 'new idea'}), content_type='application/yaml')
|
||||
|
||||
#### PUT and PATCH with form data
|
||||
|
||||
One difference worth noting between Django's `RequestFactory` and REST framework's `APIRequestFactory` is that multipart form data will be encoded for methods other than just `.post()`.
|
||||
|
||||
For example, using `APIRequestFactory`, you can make a form PUT request like so:
|
||||
|
||||
factory = APIRequestFactory()
|
||||
request = factory.put('/notes/547/', {'title': 'remember to email dave'})
|
||||
|
||||
Using Django's `RequestFactory`, you'd need to explicitly encode the data yourself:
|
||||
|
||||
from django.test.client import encode_multipart, RequestFactory
|
||||
|
||||
factory = RequestFactory()
|
||||
data = {'title': 'remember to email dave'}
|
||||
content = encode_multipart('BoUnDaRyStRiNg', data)
|
||||
content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
|
||||
request = factory.put('/notes/547/', content, content_type=content_type)
|
||||
|
||||
## Forcing authentication
|
||||
|
||||
When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials.
|
||||
|
||||
To forcibly authenticate a request, use the `force_authenticate()` method.
|
||||
|
||||
from rest_framework.test import force_authenticate
|
||||
|
||||
factory = APIRequestFactory()
|
||||
user = User.objects.get(username='olivia')
|
||||
view = AccountDetail.as_view()
|
||||
|
||||
# Make an authenticated request to the view...
|
||||
request = factory.get('/accounts/django-superstars/')
|
||||
force_authenticate(request, user=user)
|
||||
response = view(request)
|
||||
|
||||
The signature for the method is `force_authenticate(request, user=None, token=None)`. When making the call, either or both of the user and token may be set.
|
||||
|
||||
For example, when forcibly authenticating using a token, you might do something like the following:
|
||||
|
||||
user = User.objects.get(username='olivia')
|
||||
request = factory.get('/accounts/django-superstars/')
|
||||
force_authenticate(request, user=user, token=user.auth_token)
|
||||
|
||||
---
|
||||
|
||||
**Note**: `force_authenticate` directly sets `request.user` to the in-memory `user` instance. If you are re-using the same `user` instance across multiple tests that update the saved `user` state, you may need to call [`refresh_from_db()`][refresh_from_db_docs] between tests.
|
||||
|
||||
---
|
||||
|
||||
**Note**: When using `APIRequestFactory`, the object that is returned is Django's standard `HttpRequest`, and not REST framework's `Request` object, which is only generated once the view is called.
|
||||
|
||||
This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting `.token` directly will have no effect, and setting `.user` directly will only work if session authentication is being used.
|
||||
|
||||
# Request will only authenticate if `SessionAuthentication` is in use.
|
||||
request = factory.get('/accounts/django-superstars/')
|
||||
request.user = user
|
||||
response = view(request)
|
||||
|
||||
---
|
||||
|
||||
## Forcing CSRF validation
|
||||
|
||||
By default, requests created with `APIRequestFactory` will not have CSRF validation applied when passed to a REST framework view. If you need to explicitly turn CSRF validation on, you can do so by setting the `enforce_csrf_checks` flag when instantiating the factory.
|
||||
|
||||
factory = APIRequestFactory(enforce_csrf_checks=True)
|
||||
|
||||
---
|
||||
|
||||
**Note**: It's worth noting that Django's standard `RequestFactory` doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.
|
||||
|
||||
---
|
||||
|
||||
# APIClient
|
||||
|
||||
Extends [Django's existing `Client` class][client].
|
||||
|
||||
## Making requests
|
||||
|
||||
The `APIClient` class supports the same request interface as Django's standard `Client` class. This means that the standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. For example:
|
||||
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
client = APIClient()
|
||||
client.post('/notes/', {'title': 'new idea'}, format='json')
|
||||
|
||||
To support a wider set of request formats, or change the default format, [see the configuration section][configuration].
|
||||
|
||||
## Authenticating
|
||||
|
||||
#### .login(**kwargs)
|
||||
|
||||
The `login` method functions exactly as it does with Django's regular `Client` class. This allows you to authenticate requests against any views which include `SessionAuthentication`.
|
||||
|
||||
# Make all requests in the context of a logged in session.
|
||||
client = APIClient()
|
||||
client.login(username='lauren', password='secret')
|
||||
|
||||
To logout, call the `logout` method as usual.
|
||||
|
||||
# Log out
|
||||
client.logout()
|
||||
|
||||
The `login` method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.
|
||||
|
||||
#### .credentials(**kwargs)
|
||||
|
||||
The `credentials` method can be used to set headers that will then be included on all subsequent requests by the test client.
|
||||
|
||||
from rest_framework.authtoken.models import Token
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
# Include an appropriate `Authorization:` header on all requests.
|
||||
token = Token.objects.get(user__username='lauren')
|
||||
client = APIClient()
|
||||
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
|
||||
|
||||
Note that calling `credentials` a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments.
|
||||
|
||||
# Stop including any credentials
|
||||
client.credentials()
|
||||
|
||||
The `credentials` method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.
|
||||
|
||||
#### .force_authenticate(user=None, token=None)
|
||||
|
||||
Sometimes you may want to bypass authentication entirely and force all requests by the test client to be automatically treated as authenticated.
|
||||
|
||||
This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.
|
||||
|
||||
user = User.objects.get(username='lauren')
|
||||
client = APIClient()
|
||||
client.force_authenticate(user=user)
|
||||
|
||||
To unauthenticate subsequent requests, call `force_authenticate` setting the user and/or token to `None`.
|
||||
|
||||
client.force_authenticate(user=None)
|
||||
|
||||
## CSRF validation
|
||||
|
||||
By default CSRF validation is not applied when using `APIClient`. If you need to explicitly enable CSRF validation, you can do so by setting the `enforce_csrf_checks` flag when instantiating the client.
|
||||
|
||||
client = APIClient(enforce_csrf_checks=True)
|
||||
|
||||
As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling `login()`.
|
||||
|
||||
---
|
||||
|
||||
# RequestsClient
|
||||
|
||||
REST framework also includes a client for interacting with your application
|
||||
using the popular Python library, `requests`. This may be useful if:
|
||||
|
||||
* You are expecting to interface with the API primarily from another Python service,
|
||||
and want to test the service at the same level as the client will see.
|
||||
* You want to write tests in such a way that they can also be run against a staging or
|
||||
live environment. (See "Live tests" below.)
|
||||
|
||||
This exposes exactly the same interface as if you were using a requests session
|
||||
directly.
|
||||
|
||||
from rest_framework.test import RequestsClient
|
||||
|
||||
client = RequestsClient()
|
||||
response = client.get('http://testserver/users/')
|
||||
assert response.status_code == 200
|
||||
|
||||
Note that the requests client requires you to pass fully qualified URLs.
|
||||
|
||||
## RequestsClient and working with the database
|
||||
|
||||
The `RequestsClient` class is useful if you want to write tests that solely interact with the service interface. This is a little stricter than using the standard Django test client, as it means that all interactions should be via the API.
|
||||
|
||||
If you're using `RequestsClient` you'll want to ensure that test setup, and results assertions are performed as regular API calls, rather than interacting with the database models directly. For example, rather than checking that `Customer.objects.count() == 3` you would list the customers endpoint, and ensure that it contains three records.
|
||||
|
||||
## Headers & Authentication
|
||||
|
||||
Custom headers and authentication credentials can be provided in the same way
|
||||
as [when using a standard `requests.Session` instance][session_objects].
|
||||
|
||||
from requests.auth import HTTPBasicAuth
|
||||
|
||||
client.auth = HTTPBasicAuth('user', 'pass')
|
||||
client.headers.update({'x-test': 'true'})
|
||||
|
||||
## CSRF
|
||||
|
||||
If you're using `SessionAuthentication` then you'll need to include a CSRF token
|
||||
for any `POST`, `PUT`, `PATCH` or `DELETE` requests.
|
||||
|
||||
You can do so by following the same flow that a JavaScript based client would use.
|
||||
First, make a `GET` request in order to obtain a CSRF token, then present that
|
||||
token in the following request.
|
||||
|
||||
For example...
|
||||
|
||||
client = RequestsClient()
|
||||
|
||||
# Obtain a CSRF token.
|
||||
response = client.get('http://testserver/homepage/')
|
||||
assert response.status_code == 200
|
||||
csrftoken = response.cookies['csrftoken']
|
||||
|
||||
# Interact with the API.
|
||||
response = client.post('http://testserver/organisations/', json={
|
||||
'name': 'MegaCorp',
|
||||
'status': 'active'
|
||||
}, headers={'X-CSRFToken': csrftoken})
|
||||
assert response.status_code == 200
|
||||
|
||||
## Live tests
|
||||
|
||||
With careful usage both the `RequestsClient` and the `CoreAPIClient` provide
|
||||
the ability to write test cases that can run either in development, or be run
|
||||
directly against your staging server or production environment.
|
||||
|
||||
Using this style to create basic tests of a few core pieces of functionality is
|
||||
a powerful way to validate your live service. Doing so may require some careful
|
||||
attention to setup and teardown to ensure that the tests run in a way that they
|
||||
do not directly affect customer data.
|
||||
|
||||
---
|
||||
|
||||
# CoreAPIClient
|
||||
|
||||
The CoreAPIClient allows you to interact with your API using the Python
|
||||
`coreapi` client library.
|
||||
|
||||
# Fetch the API schema
|
||||
client = CoreAPIClient()
|
||||
schema = client.get('http://testserver/schema/')
|
||||
|
||||
# Create a new organisation
|
||||
params = {'name': 'MegaCorp', 'status': 'active'}
|
||||
client.action(schema, ['organisations', 'create'], params)
|
||||
|
||||
# Ensure that the organisation exists in the listing
|
||||
data = client.action(schema, ['organisations', 'list'])
|
||||
assert(len(data) == 1)
|
||||
assert(data == [{'name': 'MegaCorp', 'status': 'active'}])
|
||||
|
||||
## Headers & Authentication
|
||||
|
||||
Custom headers and authentication may be used with `CoreAPIClient` in a
|
||||
similar way as with `RequestsClient`.
|
||||
|
||||
from requests.auth import HTTPBasicAuth
|
||||
|
||||
client = CoreAPIClient()
|
||||
client.session.auth = HTTPBasicAuth('user', 'pass')
|
||||
client.session.headers.update({'x-test': 'true'})
|
||||
|
||||
---
|
||||
|
||||
# API Test cases
|
||||
|
||||
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`
|
||||
* `APITestCase`
|
||||
* `APILiveServerTestCase`
|
||||
|
||||
## Example
|
||||
|
||||
You can use any of REST framework's test case classes as you would for the regular Django test case classes. The `self.client` attribute will be an `APIClient` instance.
|
||||
|
||||
from django.urls import reverse
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APITestCase
|
||||
from myproject.apps.core.models import Account
|
||||
|
||||
class AccountTests(APITestCase):
|
||||
def test_create_account(self):
|
||||
"""
|
||||
Ensure we can create a new account object.
|
||||
"""
|
||||
url = reverse('account-list')
|
||||
data = {'name': 'DabApps'}
|
||||
response = self.client.post(url, data, format='json')
|
||||
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
|
||||
self.assertEqual(Account.objects.count(), 1)
|
||||
self.assertEqual(Account.objects.get().name, 'DabApps')
|
||||
|
||||
---
|
||||
|
||||
# URLPatternsTestCase
|
||||
|
||||
REST framework also provides a test case class for isolating `urlpatterns` on a per-class basis. Note that this inherits from Django's `SimpleTestCase`, and will most likely need to be mixed with another test case class.
|
||||
|
||||
## Example
|
||||
|
||||
from django.urls import include, path, reverse
|
||||
from rest_framework.test import APITestCase, URLPatternsTestCase
|
||||
|
||||
|
||||
class AccountTests(APITestCase, URLPatternsTestCase):
|
||||
urlpatterns = [
|
||||
path('api/', include('api.urls')),
|
||||
]
|
||||
|
||||
def test_create_account(self):
|
||||
"""
|
||||
Ensure we can create a new account object.
|
||||
"""
|
||||
url = reverse('account-list')
|
||||
response = self.client.get(url, format='json')
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(len(response.data), 1)
|
||||
|
||||
---
|
||||
|
||||
# Testing responses
|
||||
|
||||
## Checking the response data
|
||||
|
||||
When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.
|
||||
|
||||
For example, it's easier to inspect `response.data`:
|
||||
|
||||
response = self.client.get('/users/4/')
|
||||
self.assertEqual(response.data, {'id': 4, 'username': 'lauren'})
|
||||
|
||||
Instead of inspecting the result of parsing `response.content`:
|
||||
|
||||
response = self.client.get('/users/4/')
|
||||
self.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})
|
||||
|
||||
## Rendering responses
|
||||
|
||||
If you're testing views directly using `APIRequestFactory`, the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access `response.content`, you'll first need to render the response.
|
||||
|
||||
view = UserDetail.as_view()
|
||||
request = factory.get('/users/4')
|
||||
response = view(request, pk='4')
|
||||
response.render() # Cannot access `response.content` without this.
|
||||
self.assertEqual(response.content, '{"username": "lauren", "id": 4}')
|
||||
|
||||
---
|
||||
|
||||
# Configuration
|
||||
|
||||
## Setting the default format
|
||||
|
||||
The default format used to make test requests may be set using the `TEST_REQUEST_DEFAULT_FORMAT` setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your `settings.py` file:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
...
|
||||
'TEST_REQUEST_DEFAULT_FORMAT': 'json'
|
||||
}
|
||||
|
||||
## Setting the available formats
|
||||
|
||||
If you need to test requests using something other than multipart or json requests, you can do so by setting the `TEST_REQUEST_RENDERER_CLASSES` setting.
|
||||
|
||||
For example, to add support for using `format='html'` in test requests, you might have something like this in your `settings.py` file.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
...
|
||||
'TEST_REQUEST_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.MultiPartRenderer',
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.TemplateHTMLRenderer'
|
||||
]
|
||||
}
|
||||
|
||||
[cite]: https://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper
|
||||
[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/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
|
|
@ -1,7 +1,4 @@
|
|||
---
|
||||
source:
|
||||
- throttling.py
|
||||
---
|
||||
<a class="github" href="throttling.py"></a>
|
||||
|
||||
# Throttling
|
||||
|
||||
|
@ -9,20 +6,18 @@ source:
|
|||
>
|
||||
> [Twitter API rate limiting response][cite]
|
||||
|
||||
[cite]: https://dev.twitter.com/docs/error-codes-responses
|
||||
|
||||
Throttling is similar to [permissions], in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.
|
||||
|
||||
As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.
|
||||
|
||||
Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.
|
||||
|
||||
Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.
|
||||
Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.
|
||||
|
||||
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.
|
||||
|
@ -35,27 +30,22 @@ If any throttle check fails an `exceptions.Throttled` exception will be raised,
|
|||
The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_CLASSES` and `DEFAULT_THROTTLE_RATES` settings. For example.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_THROTTLE_CLASSES': [
|
||||
'DEFAULT_THROTTLE_CLASSES': (
|
||||
'rest_framework.throttling.AnonRateThrottle',
|
||||
'rest_framework.throttling.UserRateThrottle'
|
||||
],
|
||||
),
|
||||
'DEFAULT_THROTTLE_RATES': {
|
||||
'anon': '100/day',
|
||||
'user': '1000/day'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
The rates used in `DEFAULT_THROTTLE_RATES` can be specified over a period of second, minute, hour or day. The period must be specified after the `/` separator using `s`, `m`, `h` or `d`, respectively. For increased clarity, extended units such as `second`, `minute`, `hour`, `day` or even abbreviations like `sec`, `min`, `hr` are allowed, as only the first character is relevant to identify the rate.
|
||||
The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period.
|
||||
|
||||
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.throttling import UserRateThrottle
|
||||
from rest_framework.views import APIView
|
||||
You can also set the throttling policy on a per-view basis, using the `APIView` class based views.
|
||||
|
||||
class ExampleView(APIView):
|
||||
throttle_classes = [UserRateThrottle]
|
||||
throttle_classes = (UserThrottle,)
|
||||
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
|
@ -63,77 +53,38 @@ using the `APIView` class-based views.
|
|||
}
|
||||
return Response(content)
|
||||
|
||||
If you're using the `@api_view` decorator with function based views you can use the following decorator.
|
||||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
|
||||
@api_view(['GET'])
|
||||
@throttle_classes([UserRateThrottle])
|
||||
@api_view('GET')
|
||||
@throttle_classes(UserThrottle)
|
||||
def example_view(request, format=None):
|
||||
content = {
|
||||
'status': 'request was permitted'
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
It's also possible to set throttle classes for routes that are created using the `@action` decorator.
|
||||
Throttle classes set in this way will override any viewset level class settings.
|
||||
|
||||
@action(detail=True, methods=["post"], throttle_classes=[UserRateThrottle])
|
||||
def example_adhoc_method(request, pk=None):
|
||||
content = {
|
||||
'status': 'request was permitted'
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
## 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.
|
||||
|
||||
If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the `NUM_PROXIES` setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the `X-Forwarded-For` header, once any application proxy IP addresses have first been excluded. If set to zero, then the `REMOTE_ADDR` value will always be used as the identifying IP address.
|
||||
|
||||
It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](https://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client.
|
||||
|
||||
Further context on how the `X-Forwarded-For` header works, and identifying a remote client IP can be [found here][identifying-clients].
|
||||
|
||||
## Setting up the cache
|
||||
|
||||
The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate [cache settings][cache-setting]. The default value of `LocMemCache` backend should be okay for simple setups. See Django's [cache documentation][cache-docs] for more details.
|
||||
|
||||
If you need to use a cache other than `'default'`, you can do so by creating a custom throttle class and setting the `cache` attribute. For example:
|
||||
|
||||
from django.core.cache import caches
|
||||
|
||||
class CustomAnonRateThrottle(AnonRateThrottle):
|
||||
cache = caches['alternate']
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## AnonRateThrottle
|
||||
|
||||
The `AnonRateThrottle` will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.
|
||||
The `AnonThrottle` will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.
|
||||
|
||||
The allowed request rate is determined from one of the following (in order of preference).
|
||||
|
||||
* The `rate` property on the class, which may be provided by overriding `AnonRateThrottle` and setting the property.
|
||||
* The `rate` property on the class, which may be provided by overriding `AnonThrottle` and setting the property.
|
||||
* The `DEFAULT_THROTTLE_RATES['anon']` setting.
|
||||
|
||||
`AnonRateThrottle` is suitable if you want to restrict the rate of requests from unknown sources.
|
||||
`AnonThrottle` is suitable if you want to restrict the rate of requests from unknown sources.
|
||||
|
||||
## UserRateThrottle
|
||||
|
||||
The `UserRateThrottle` will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.
|
||||
The `UserThrottle` will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.
|
||||
|
||||
The allowed request rate is determined from one of the following (in order of preference).
|
||||
|
||||
* The `rate` property on the class, which may be provided by overriding `UserRateThrottle` and setting the property.
|
||||
* The `rate` property on the class, which may be provided by overriding `UserThrottle` and setting the property.
|
||||
* The `DEFAULT_THROTTLE_RATES['user']` setting.
|
||||
|
||||
An API may have multiple `UserRateThrottles` in place at the same time. To do so, override `UserRateThrottle` and set a unique "scope" for each class.
|
||||
|
@ -149,21 +100,21 @@ For example, multiple user throttle rates could be implemented by using the foll
|
|||
...and the following settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_THROTTLE_CLASSES': [
|
||||
'DEFAULT_THROTTLE_CLASSES': (
|
||||
'example.throttles.BurstRateThrottle',
|
||||
'example.throttles.SustainedRateThrottle'
|
||||
],
|
||||
),
|
||||
'DEFAULT_THROTTLE_RATES': {
|
||||
'burst': '60/min',
|
||||
'sustained': '1000/day'
|
||||
}
|
||||
}
|
||||
|
||||
`UserRateThrottle` is suitable if you want simple global rate restrictions per-user.
|
||||
`UserThrottle` is suitable if you want simple global rate restrictions per-user.
|
||||
|
||||
## ScopedRateThrottle
|
||||
|
||||
The `ScopedRateThrottle` class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a `.throttle_scope` property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.
|
||||
The `ScopedThrottle` class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a `.throttle_scope` property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.
|
||||
|
||||
The allowed request rate is determined by the `DEFAULT_THROTTLE_RATES` setting using a key from the request "scope".
|
||||
|
||||
|
@ -172,21 +123,21 @@ For example, given the following views...
|
|||
class ContactListView(APIView):
|
||||
throttle_scope = 'contacts'
|
||||
...
|
||||
|
||||
class ContactDetailView(APIView):
|
||||
|
||||
class ContactDetailView(ApiView):
|
||||
throttle_scope = 'contacts'
|
||||
...
|
||||
|
||||
class UploadView(APIView):
|
||||
class UploadView(APIView):
|
||||
throttle_scope = 'uploads'
|
||||
...
|
||||
|
||||
|
||||
...and the following settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_THROTTLE_CLASSES': [
|
||||
'rest_framework.throttling.ScopedRateThrottle',
|
||||
],
|
||||
'DEFAULT_THROTTLE_CLASSES': (
|
||||
'rest_framework.throttling.ScopedRateThrottle'
|
||||
),
|
||||
'DEFAULT_THROTTLE_RATES': {
|
||||
'contacts': '1000/day',
|
||||
'uploads': '20/day'
|
||||
|
@ -199,25 +150,8 @@ User requests to either `ContactListView` or `ContactDetailView` would be restri
|
|||
|
||||
# Custom throttles
|
||||
|
||||
To create a custom throttle, override `BaseThrottle` and implement `.allow_request(self, request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise.
|
||||
To create a custom throttle, override `BaseThrottle` and implement `.allow_request(request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise.
|
||||
|
||||
Optionally you may also override the `.wait()` method. If implemented, `.wait()` should return a recommended number of seconds to wait before attempting the next request, or `None`. The `.wait()` method will only be called if `.allow_request()` has previously returned `False`.
|
||||
|
||||
If the `.wait()` method is implemented and the request is throttled, then a `Retry-After` header will be included in the response.
|
||||
|
||||
## Example
|
||||
|
||||
The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.
|
||||
|
||||
import random
|
||||
|
||||
class RandomRateThrottle(throttling.BaseThrottle):
|
||||
def allow_request(self, request, view):
|
||||
return random.randint(1, 10) != 1
|
||||
|
||||
[cite]: https://developer.twitter.com/en/docs/basics/rate-limiting
|
||||
[permissions]: permissions.md
|
||||
[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
|
||||
[race]: https://en.wikipedia.org/wiki/Race_condition#Data_race
|
||||
|
|
|
@ -1,312 +0,0 @@
|
|||
---
|
||||
source:
|
||||
- validators.py
|
||||
---
|
||||
|
||||
# Validators
|
||||
|
||||
> Validators can be useful for re-using validation logic between different types of fields.
|
||||
>
|
||||
> — [Django documentation][cite]
|
||||
|
||||
Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.
|
||||
|
||||
However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.
|
||||
|
||||
## Validation in REST framework
|
||||
|
||||
Validation in Django REST framework serializers is handled a little differently to how validation works in Django's `ModelForm` class.
|
||||
|
||||
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.
|
||||
* 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.
|
||||
|
||||
#### Example
|
||||
|
||||
As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.
|
||||
|
||||
class CustomerReportRecord(models.Model):
|
||||
time_raised = models.DateTimeField(default=timezone.now, editable=False)
|
||||
reference = models.CharField(unique=True, max_length=20)
|
||||
description = models.TextField()
|
||||
|
||||
Here's a basic `ModelSerializer` that we can use for creating or updating instances of `CustomerReportRecord`:
|
||||
|
||||
class CustomerReportSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = CustomerReportRecord
|
||||
|
||||
If we open up the Django shell using `manage.py shell` we can now
|
||||
|
||||
>>> from project.example.serializers import CustomerReportSerializer
|
||||
>>> serializer = CustomerReportSerializer()
|
||||
>>> print(repr(serializer))
|
||||
CustomerReportSerializer():
|
||||
id = IntegerField(label='ID', read_only=True)
|
||||
time_raised = DateTimeField(read_only=True)
|
||||
reference = CharField(max_length=20, validators=[UniqueValidator(queryset=CustomerReportRecord.objects.all())])
|
||||
description = CharField(style={'type': 'textarea'})
|
||||
|
||||
The interesting bit here is the `reference` field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.
|
||||
|
||||
Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below. REST framework validators, like their Django counterparts, implement the `__eq__` method, allowing you to compare instances for equality.
|
||||
|
||||
---
|
||||
|
||||
## UniqueValidator
|
||||
|
||||
This validator can be used to enforce the `unique=True` constraint on model fields.
|
||||
It takes a single required argument, and an optional `messages` argument:
|
||||
|
||||
* `queryset` *required* - This is the queryset against which uniqueness should be enforced.
|
||||
* `message` - The error message that should be used when validation fails.
|
||||
* `lookup` - The lookup used to find an existing instance with the value being validated. Defaults to `'exact'`.
|
||||
|
||||
This validator should be applied to *serializer fields*, like so:
|
||||
|
||||
from rest_framework.validators import UniqueValidator
|
||||
|
||||
slug = SlugField(
|
||||
max_length=100,
|
||||
validators=[UniqueValidator(queryset=BlogPost.objects.all())]
|
||||
)
|
||||
|
||||
## UniqueTogetherValidator
|
||||
|
||||
This validator can be used to enforce `unique_together` constraints on model instances.
|
||||
It has two required arguments, and a single optional `messages` argument:
|
||||
|
||||
* `queryset` *required* - This is the queryset against which uniqueness should be enforced.
|
||||
* `fields` *required* - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.
|
||||
* `message` - The error message that should be used when validation fails.
|
||||
|
||||
The validator should be applied to *serializer classes*, like so:
|
||||
|
||||
from rest_framework.validators import UniqueTogetherValidator
|
||||
|
||||
class ExampleSerializer(serializers.Serializer):
|
||||
# ...
|
||||
class Meta:
|
||||
# ToDo items belong to a parent list, and have an ordering defined
|
||||
# by the 'position' field. No two items in a given list may share
|
||||
# the same position.
|
||||
validators = [
|
||||
UniqueTogetherValidator(
|
||||
queryset=ToDoItem.objects.all(),
|
||||
fields=['list', 'position']
|
||||
)
|
||||
]
|
||||
|
||||
---
|
||||
|
||||
**Note**: The `UniqueTogetherValidator` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
|
||||
|
||||
---
|
||||
|
||||
## UniqueForDateValidator
|
||||
|
||||
## UniqueForMonthValidator
|
||||
|
||||
## UniqueForYearValidator
|
||||
|
||||
These validators can be used to enforce the `unique_for_date`, `unique_for_month` and `unique_for_year` constraints on model instances. They take the following arguments:
|
||||
|
||||
* `queryset` *required* - This is the queryset against which uniqueness should be enforced.
|
||||
* `field` *required* - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.
|
||||
* `date_field` *required* - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.
|
||||
* `message` - The error message that should be used when validation fails.
|
||||
|
||||
The validator should be applied to *serializer classes*, like so:
|
||||
|
||||
from rest_framework.validators import UniqueForYearValidator
|
||||
|
||||
class ExampleSerializer(serializers.Serializer):
|
||||
# ...
|
||||
class Meta:
|
||||
# Blog posts should have a slug that is unique for the current year.
|
||||
validators = [
|
||||
UniqueForYearValidator(
|
||||
queryset=BlogPostItem.objects.all(),
|
||||
field='slug',
|
||||
date_field='published'
|
||||
)
|
||||
]
|
||||
|
||||
The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class `default=...`, because the value being used for the default wouldn't be generated until after the validation has run.
|
||||
|
||||
There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using `ModelSerializer` you'll probably simply rely on the defaults that REST framework generates for you, but if you are using `Serializer` or simply want more explicit control, use on of the styles demonstrated below.
|
||||
|
||||
#### Using with a writable date field.
|
||||
|
||||
If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a `default` argument, or by setting `required=True`.
|
||||
|
||||
published = serializers.DateTimeField(required=True)
|
||||
|
||||
#### Using with a read-only date field.
|
||||
|
||||
If you want the date field to be visible, but not editable by the user, then set `read_only=True` and additionally set a `default=...` argument.
|
||||
|
||||
published = serializers.DateTimeField(read_only=True, default=timezone.now)
|
||||
|
||||
#### Using with a hidden date field.
|
||||
|
||||
If you want the date field to be entirely hidden from the user, then use `HiddenField`. This field type does not accept user input, but instead always returns its default value to the `validated_data` in the serializer.
|
||||
|
||||
published = serializers.HiddenField(default=timezone.now)
|
||||
|
||||
---
|
||||
|
||||
**Note**: The `UniqueFor<Range>Validator` classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request).
|
||||
|
||||
---
|
||||
|
||||
# Advanced field defaults
|
||||
|
||||
Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that *is* available as input to the validator.
|
||||
For this purposes use `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation.
|
||||
|
||||
**Note:** Using a `read_only=True` field is excluded from writable fields so it won't use a `default=…` argument. Look [3.8 announcement](https://www.django-rest-framework.org/community/3.8-announcement/#altered-the-behaviour-of-read_only-plus-default-on-field).
|
||||
|
||||
REST framework includes a couple of defaults that may be useful in this context.
|
||||
|
||||
#### CurrentUserDefault
|
||||
|
||||
A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.
|
||||
|
||||
owner = serializers.HiddenField(
|
||||
default=serializers.CurrentUserDefault()
|
||||
)
|
||||
|
||||
#### CreateOnlyDefault
|
||||
|
||||
A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted.
|
||||
|
||||
It takes a single argument, which is the default value or callable that should be used during create operations.
|
||||
|
||||
created_at = serializers.DateTimeField(
|
||||
default=serializers.CreateOnlyDefault(timezone.now)
|
||||
)
|
||||
|
||||
---
|
||||
|
||||
# Limitations of validators
|
||||
|
||||
There are some ambiguous cases where you'll need to instead handle validation
|
||||
explicitly, rather than relying on the default serializer classes that
|
||||
`ModelSerializer` generates.
|
||||
|
||||
In these cases you may want to disable the automatically generated validators,
|
||||
by specifying an empty list for the serializer `Meta.validators` attribute.
|
||||
|
||||
## Optional fields
|
||||
|
||||
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 behavior
|
||||
of the validation is ambiguous.
|
||||
|
||||
In this case you will typically need to exclude the validator from the
|
||||
serializer class, and instead write any validation logic explicitly, either
|
||||
in the `.validate()` method, or else in the view.
|
||||
|
||||
For example:
|
||||
|
||||
class BillingRecordSerializer(serializers.ModelSerializer):
|
||||
def validate(self, attrs):
|
||||
# Apply custom validation either here, or in the view.
|
||||
|
||||
class Meta:
|
||||
fields = ['client', 'date', 'amount']
|
||||
extra_kwargs = {'client': {'required': False}}
|
||||
validators = [] # Remove a default "unique together" constraint.
|
||||
|
||||
## Updating nested serializers
|
||||
|
||||
When applying an update to an existing instance, uniqueness validators will
|
||||
exclude the current instance from the uniqueness check. The current instance
|
||||
is available in the context of the uniqueness check, because it exists as
|
||||
an attribute on the serializer, having initially been passed using
|
||||
`instance=...` when instantiating the serializer.
|
||||
|
||||
In the case of update operations on *nested* serializers there's no way of
|
||||
applying this exclusion, because the instance is not available.
|
||||
|
||||
Again, you'll probably want to explicitly remove the validator from the
|
||||
serializer class, and write the code for the validation constraint
|
||||
explicitly, in a `.validate()` method, or in the view.
|
||||
|
||||
## Debugging complex cases
|
||||
|
||||
If you're not sure exactly what behavior a `ModelSerializer` class will
|
||||
generate it is usually a good idea to run `manage.py shell`, and print
|
||||
an instance of the serializer, so that you can inspect the fields and
|
||||
validators that it automatically generates for you.
|
||||
|
||||
>>> serializer = MyComplexModelSerializer()
|
||||
>>> print(serializer)
|
||||
class MyComplexModelSerializer:
|
||||
my_fields = ...
|
||||
|
||||
Also keep in mind that with complex cases it can often be better to explicitly
|
||||
define your serializer classes, rather than relying on the default
|
||||
`ModelSerializer` behavior. This involves a little more code, but ensures
|
||||
that the resulting behavior is more transparent.
|
||||
|
||||
---
|
||||
|
||||
# Writing custom validators
|
||||
|
||||
You can use any of Django's existing validators, or write your own custom validators.
|
||||
|
||||
## Function based
|
||||
|
||||
A validator may be any callable that raises a `serializers.ValidationError` on failure.
|
||||
|
||||
def even_number(value):
|
||||
if value % 2 != 0:
|
||||
raise serializers.ValidationError('This field must be an even number.')
|
||||
|
||||
#### Field-level validation
|
||||
|
||||
You can specify custom field-level validation by adding `.validate_<field_name>` methods
|
||||
to your `Serializer` subclass. This is documented in the
|
||||
[Serializer docs](https://www.django-rest-framework.org/api-guide/serializers/#field-level-validation)
|
||||
|
||||
## Class-based
|
||||
|
||||
To write a class-based validator, use the `__call__` method. Class-based validators are useful as they allow you to parameterize and reuse behavior.
|
||||
|
||||
class MultipleOf:
|
||||
def __init__(self, base):
|
||||
self.base = base
|
||||
|
||||
def __call__(self, value):
|
||||
if value % self.base != 0:
|
||||
message = 'This field must be a multiple of %d.' % self.base
|
||||
raise serializers.ValidationError(message)
|
||||
|
||||
#### Accessing the context
|
||||
|
||||
In some advanced cases you might want a validator to be passed the serializer
|
||||
field it is being used with as additional context. You can do so by setting
|
||||
a `requires_context = True` attribute on the validator class. The `__call__` method
|
||||
will then be called with the `serializer_field`
|
||||
or `serializer` as an additional argument.
|
||||
|
||||
class MultipleOf:
|
||||
requires_context = True
|
||||
|
||||
def __call__(self, value, serializer_field):
|
||||
...
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/ref/validators/
|
|
@ -1,223 +0,0 @@
|
|||
---
|
||||
source:
|
||||
- versioning.py
|
||||
---
|
||||
|
||||
# Versioning
|
||||
|
||||
> Versioning an interface is just a "polite" way to kill deployed clients.
|
||||
>
|
||||
> — [Roy Fielding][cite].
|
||||
|
||||
API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes.
|
||||
|
||||
Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers.
|
||||
|
||||
There are a number of valid approaches to approaching versioning. [Non-versioned systems can also be appropriate][roy-fielding-on-versioning], particularly if you're engineering for very long-term systems with multiple clients outside of your control.
|
||||
|
||||
## Versioning with REST framework
|
||||
|
||||
When API versioning is enabled, the `request.version` attribute will contain a string that corresponds to the version requested in the incoming client request.
|
||||
|
||||
By default, versioning is not enabled, and `request.version` will always return `None`.
|
||||
|
||||
#### Varying behavior based on the version
|
||||
|
||||
How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example:
|
||||
|
||||
def get_serializer_class(self):
|
||||
if self.request.version == 'v1':
|
||||
return AccountSerializerVersion1
|
||||
return AccountSerializer
|
||||
|
||||
#### Reversing URLs for versioned APIs
|
||||
|
||||
The `reverse` function included by REST framework ties in with the versioning scheme. You need to make sure to include the current `request` as a keyword argument, like so.
|
||||
|
||||
from rest_framework.reverse import reverse
|
||||
|
||||
reverse('bookings-list', request=request)
|
||||
|
||||
The above function will apply any URL transformations appropriate to the request version. For example:
|
||||
|
||||
* If `NamespaceVersioning` was being used, and the API version was 'v1', then the URL lookup used would be `'v1:bookings-list'`, which might resolve to a URL like `http://example.org/v1/bookings/`.
|
||||
* If `QueryParameterVersioning` was being used, and the API version was `1.0`, then the returned URL might be something like `http://example.org/bookings/?version=1.0`
|
||||
|
||||
#### Versioned APIs and hyperlinked serializers
|
||||
|
||||
When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer.
|
||||
|
||||
def get(self, request):
|
||||
queryset = Booking.objects.all()
|
||||
serializer = BookingsSerializer(queryset, many=True, context={'request': request})
|
||||
return Response({'all_bookings': serializer.data})
|
||||
|
||||
Doing so will allow any returned URLs to include the appropriate versioning.
|
||||
|
||||
## Configuring the versioning scheme
|
||||
|
||||
The versioning scheme is defined by the `DEFAULT_VERSIONING_CLASS` settings key.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'
|
||||
}
|
||||
|
||||
Unless it is explicitly set, the value for `DEFAULT_VERSIONING_CLASS` will be `None`. In this case the `request.version` attribute will always return `None`.
|
||||
|
||||
You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the `versioning_class` attribute.
|
||||
|
||||
class ProfileList(APIView):
|
||||
versioning_class = versioning.QueryParameterVersioning
|
||||
|
||||
#### Other versioning settings
|
||||
|
||||
The following settings keys are also used to control versioning:
|
||||
|
||||
* `DEFAULT_VERSION`. The value that should be used for `request.version` when no versioning information is present. Defaults to `None`.
|
||||
* `ALLOWED_VERSIONS`. If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version is not in this set. Note that the value used for the `DEFAULT_VERSION` setting is always considered to be part of the `ALLOWED_VERSIONS` set (unless it is `None`). Defaults to `None`.
|
||||
* `VERSION_PARAM`. The string that should be used for any versioning parameters, such as in the media type or URL query parameters. Defaults to `'version'`.
|
||||
|
||||
You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the `default_version`, `allowed_versions` and `version_param` class variables. For example, if you want to use `URLPathVersioning`:
|
||||
|
||||
from rest_framework.versioning import URLPathVersioning
|
||||
from rest_framework.views import APIView
|
||||
|
||||
class ExampleVersioning(URLPathVersioning):
|
||||
default_version = ...
|
||||
allowed_versions = ...
|
||||
version_param = ...
|
||||
|
||||
class ExampleView(APIVIew):
|
||||
versioning_class = ExampleVersioning
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## AcceptHeaderVersioning
|
||||
|
||||
This scheme requires the client to specify the version as part of the media type in the `Accept` header. The version is included as a media type parameter, that supplements the main media type.
|
||||
|
||||
Here's an example HTTP request using the accept header versioning style.
|
||||
|
||||
GET /bookings/ HTTP/1.1
|
||||
Host: example.com
|
||||
Accept: application/json; version=1.0
|
||||
|
||||
In the example request above `request.version` attribute would return the string `'1.0'`.
|
||||
|
||||
Versioning based on accept headers is [generally considered][klabnik-guidelines] as [best practice][heroku-guidelines], although other styles may be suitable depending on your client requirements.
|
||||
|
||||
#### Using accept headers with vendor media types
|
||||
|
||||
Strictly speaking the `json` media type is not specified as [including additional parameters][json-parameters]. If you are building a well-specified public API you might consider using a [vendor media type][vendor-media-type]. To do so, configure your renderers to use a JSON based renderer with a custom media type:
|
||||
|
||||
class BookingsAPIRenderer(JSONRenderer):
|
||||
media_type = 'application/vnd.megacorp.bookings+json'
|
||||
|
||||
Your client requests would now look like this:
|
||||
|
||||
GET /bookings/ HTTP/1.1
|
||||
Host: example.com
|
||||
Accept: application/vnd.megacorp.bookings+json; version=1.0
|
||||
|
||||
## URLPathVersioning
|
||||
|
||||
This scheme requires the client to specify the version as part of the URL path.
|
||||
|
||||
GET /v1/bookings/ HTTP/1.1
|
||||
Host: example.com
|
||||
Accept: application/json
|
||||
|
||||
Your URL conf must include a pattern that matches the version with a `'version'` keyword argument, so that this information is available to the versioning scheme.
|
||||
|
||||
urlpatterns = [
|
||||
re_path(
|
||||
r'^(?P<version>(v1|v2))/bookings/$',
|
||||
bookings_list,
|
||||
name='bookings-list'
|
||||
),
|
||||
re_path(
|
||||
r'^(?P<version>(v1|v2))/bookings/(?P<pk>[0-9]+)/$',
|
||||
bookings_detail,
|
||||
name='bookings-detail'
|
||||
)
|
||||
]
|
||||
|
||||
## NamespaceVersioning
|
||||
|
||||
To the client, this scheme is the same as `URLPathVersioning`. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments.
|
||||
|
||||
GET /v1/something/ HTTP/1.1
|
||||
Host: example.com
|
||||
Accept: application/json
|
||||
|
||||
With this scheme the `request.version` attribute is determined based on the `namespace` that matches the incoming request path.
|
||||
|
||||
In the following example we're giving a set of views two different possible URL prefixes, each under a different namespace:
|
||||
|
||||
# bookings/urls.py
|
||||
urlpatterns = [
|
||||
re_path(r'^$', bookings_list, name='bookings-list'),
|
||||
re_path(r'^(?P<pk>[0-9]+)/$', bookings_detail, name='bookings-detail')
|
||||
]
|
||||
|
||||
# urls.py
|
||||
urlpatterns = [
|
||||
re_path(r'^v1/bookings/', include('bookings.urls', namespace='v1')),
|
||||
re_path(r'^v2/bookings/', include('bookings.urls', namespace='v2'))
|
||||
]
|
||||
|
||||
Both `URLPathVersioning` and `NamespaceVersioning` are reasonable if you just need a simple versioning scheme. The `URLPathVersioning` approach might be better suitable for small ad-hoc projects, and the `NamespaceVersioning` is probably easier to manage for larger projects.
|
||||
|
||||
## HostNameVersioning
|
||||
|
||||
The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL.
|
||||
|
||||
For example the following is an HTTP request to the `http://v1.example.com/bookings/` URL:
|
||||
|
||||
GET /bookings/ HTTP/1.1
|
||||
Host: v1.example.com
|
||||
Accept: application/json
|
||||
|
||||
By default this implementation expects the hostname to match this simple regular expression:
|
||||
|
||||
^([a-zA-Z0-9]+)\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+$
|
||||
|
||||
Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname.
|
||||
|
||||
The `HostNameVersioning` scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as `127.0.0.1`. There are various online tutorials on how to [access localhost with a custom subdomain][lvh] which you may find helpful in this case.
|
||||
|
||||
Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions.
|
||||
|
||||
## QueryParameterVersioning
|
||||
|
||||
This scheme is a simple style that includes the version as a query parameter in the URL. For example:
|
||||
|
||||
GET /something/?version=0.1 HTTP/1.1
|
||||
Host: example.com
|
||||
Accept: application/json
|
||||
|
||||
---
|
||||
|
||||
# Custom versioning schemes
|
||||
|
||||
To implement a custom versioning scheme, subclass `BaseVersioning` and override the `.determine_version` method.
|
||||
|
||||
## Example
|
||||
|
||||
The following example uses a custom `X-API-Version` header to determine the requested version.
|
||||
|
||||
class XAPIVersionScheme(versioning.BaseVersioning):
|
||||
def determine_version(self, request, *args, **kwargs):
|
||||
return request.META.get('HTTP_X_API_VERSION', None)
|
||||
|
||||
If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the `.reverse()` method on the class. See the source code for examples.
|
||||
|
||||
[cite]: https://www.slideshare.net/evolve_conference/201308-fielding-evolve/31
|
||||
[roy-fielding-on-versioning]: https://www.infoq.com/articles/roy-fielding-on-versioning
|
||||
[klabnik-guidelines]: http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http#i_want_my_api_to_be_versioned
|
||||
[heroku-guidelines]: https://github.com/interagent/http-api-design/blob/master/en/foundations/require-versioning-in-the-accepts-header.md
|
||||
[json-parameters]: https://tools.ietf.org/html/rfc4627#section-6
|
||||
[vendor-media-type]: https://en.wikipedia.org/wiki/Internet_media_type#Vendor_tree
|
||||
[lvh]: https://reinteractive.net/posts/199-developing-and-testing-rails-applications-with-subdomains
|
|
@ -1,12 +1,8 @@
|
|||
---
|
||||
source:
|
||||
- decorators.py
|
||||
- views.py
|
||||
---
|
||||
<a class="github" href="decorators.py"></a> <a class="github" href="views.py"></a>
|
||||
|
||||
# Class-based Views
|
||||
# Class Based Views
|
||||
|
||||
> Django's class-based views are a welcome departure from the old-style views.
|
||||
> Django's class based views are a welcome departure from the old-style views.
|
||||
>
|
||||
> — [Reinout van Rees][cite]
|
||||
|
||||
|
@ -26,17 +22,16 @@ For example:
|
|||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from rest_framework import authentication, permissions
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
class ListUsers(APIView):
|
||||
"""
|
||||
View to list all users in the system.
|
||||
|
||||
|
||||
* Requires token authentication.
|
||||
* Only admin users are able to access this view.
|
||||
"""
|
||||
authentication_classes = [authentication.TokenAuthentication]
|
||||
permission_classes = [permissions.IsAdminUser]
|
||||
authentication_classes = (authentication.TokenAuthentication,)
|
||||
permission_classes = (permissions.IsAdminUser,)
|
||||
|
||||
def get(self, request, format=None):
|
||||
"""
|
||||
|
@ -45,13 +40,6 @@ For example:
|
|||
usernames = [user.username for user in User.objects.all()]
|
||||
return Response(usernames)
|
||||
|
||||
---
|
||||
|
||||
**Note**: The full methods, attributes on, and relations between Django REST Framework's `APIView`, `GenericAPIView`, various `Mixins`, and `Viewsets` can be initially complex. In addition to the documentation here, the [Classy Django REST Framework][classy-drf] resource provides a browsable reference, with full methods and attributes, for each of Django REST Framework's class-based views.
|
||||
|
||||
---
|
||||
|
||||
|
||||
## API policy attributes
|
||||
|
||||
The following attributes control the pluggable aspects of API views.
|
||||
|
@ -66,7 +54,7 @@ The following attributes control the pluggable aspects of API views.
|
|||
|
||||
### .permission_classes
|
||||
|
||||
### .content_negotiation_class
|
||||
### .content_negotiation_class
|
||||
|
||||
## API policy instantiation methods
|
||||
|
||||
|
@ -84,22 +72,20 @@ The following methods are used by REST framework to instantiate the various plug
|
|||
|
||||
### .get_content_negotiator(self)
|
||||
|
||||
### .get_exception_handler(self)
|
||||
|
||||
## API policy implementation methods
|
||||
|
||||
The following methods are called before dispatching to the handler method.
|
||||
|
||||
### .check_permissions(self, request)
|
||||
### .check_permissions(...)
|
||||
|
||||
### .check_throttles(self, request)
|
||||
### .check_throttles(...)
|
||||
|
||||
### .perform_content_negotiation(self, request, force=False)
|
||||
### .perform_content_negotiation(...)
|
||||
|
||||
## Dispatch methods
|
||||
|
||||
The following methods are called directly by the view's `.dispatch()` method.
|
||||
These perform any actions that need to occur before or after calling the handler methods such as `.get()`, `.post()`, `put()`, `patch()` and `.delete()`.
|
||||
These perform any actions that need to occur before or after calling the handler methods such as `.get()`, `.post()`, `put()` and `.delete()`.
|
||||
|
||||
### .initial(self, request, \*args, **kwargs)
|
||||
|
||||
|
@ -124,7 +110,7 @@ You won't typically need to override this method.
|
|||
|
||||
### .finalize_response(self, request, response, \*args, **kwargs)
|
||||
|
||||
Ensures that any `Response` object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.
|
||||
Ensures that any `Response` object returned from the handler method will be rendered into the correct content type, as determined by the content negotation.
|
||||
|
||||
You won't typically need to override this method.
|
||||
|
||||
|
@ -132,45 +118,36 @@ You won't typically need to override this method.
|
|||
|
||||
# Function Based Views
|
||||
|
||||
> Saying [that class-based views] is always the superior solution is a mistake.
|
||||
> Saying [that Class based views] is always the superior solution is a mistake.
|
||||
>
|
||||
> — [Nick Coghlan][cite2]
|
||||
|
||||
REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed.
|
||||
REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed.
|
||||
|
||||
## @api_view()
|
||||
|
||||
**Signature:** `@api_view(http_method_names=['GET'])`
|
||||
**Signature:** `@api_view(http_method_names)`
|
||||
|
||||
The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
|
||||
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.response import Response
|
||||
|
||||
@api_view()
|
||||
@api_view(['GET'])
|
||||
def hello_world(request):
|
||||
return Response({"message": "Hello, world!"})
|
||||
|
||||
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 behavior, specify which methods the view allows, like so:
|
||||
|
||||
@api_view(['GET', 'POST'])
|
||||
def hello_world(request):
|
||||
if request.method == 'POST':
|
||||
return Response({"message": "Got some data!", "data": request.data})
|
||||
return Response({"message": "Hello, world!"})
|
||||
|
||||
This view will use the default renderers, parsers, authentication classes etc specified in the [settings](settings).
|
||||
|
||||
## API policy decorators
|
||||
|
||||
To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle][throttling] to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
|
||||
To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle](throttling) to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
|
||||
|
||||
from rest_framework.decorators import api_view, throttle_classes
|
||||
from rest_framework.throttling import UserRateThrottle
|
||||
|
||||
class OncePerDayUserThrottle(UserRateThrottle):
|
||||
rate = '1/day'
|
||||
rate = '1/day'
|
||||
|
||||
@api_view(['GET'])
|
||||
@throttle_classes([OncePerDayUserThrottle])
|
||||
|
@ -189,39 +166,7 @@ The available decorators are:
|
|||
|
||||
Each of these decorators takes a single argument which must be a list or tuple of classes.
|
||||
|
||||
|
||||
## View schema decorator
|
||||
|
||||
To override the default schema generation for function based views you may use
|
||||
the `@schema` decorator. This must come *after* (below) the `@api_view`
|
||||
decorator. For example:
|
||||
|
||||
from rest_framework.decorators import api_view, schema
|
||||
from rest_framework.schemas import AutoSchema
|
||||
|
||||
class CustomAutoSchema(AutoSchema):
|
||||
def get_link(self, path, method, base_url):
|
||||
# override view introspection here...
|
||||
|
||||
@api_view(['GET'])
|
||||
@schema(CustomAutoSchema())
|
||||
def view(request):
|
||||
return Response({"message": "Hello for today! See you tomorrow!"})
|
||||
|
||||
This decorator takes a single `AutoSchema` instance, an `AutoSchema` subclass
|
||||
instance or `ManualSchema` instance as described in the [Schemas documentation][schemas].
|
||||
You may pass `None` in order to exclude the view from schema generation.
|
||||
|
||||
@api_view(['GET'])
|
||||
@schema(None)
|
||||
def view(request):
|
||||
return Response({"message": "Will not appear in schema!"})
|
||||
|
||||
|
||||
[cite]: https://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
|
||||
[cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
|
||||
[cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html
|
||||
[settings]: settings.md
|
||||
[throttling]: throttling.md
|
||||
[schemas]: schemas.md
|
||||
[classy-drf]: http://www.cdrf.co
|
||||
|
||||
[settings]: api-guide/settings.md
|
||||
[throttling]: api-guide/throttling.md
|
||||
|
|
|
@ -1,333 +0,0 @@
|
|||
---
|
||||
source:
|
||||
- viewsets.py
|
||||
---
|
||||
|
||||
# ViewSets
|
||||
|
||||
> After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.
|
||||
>
|
||||
> — [Ruby on Rails Documentation][cite]
|
||||
|
||||
|
||||
Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
|
||||
|
||||
A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`.
|
||||
|
||||
The method handlers for a `ViewSet` are only bound to the corresponding actions at the point of finalizing the view, using the `.as_view()` method.
|
||||
|
||||
Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.
|
||||
|
||||
## Example
|
||||
|
||||
Let's define a simple viewset that can be used to list or retrieve all the users in the system.
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.shortcuts import get_object_or_404
|
||||
from myapps.serializers import UserSerializer
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.response import Response
|
||||
|
||||
class UserViewSet(viewsets.ViewSet):
|
||||
"""
|
||||
A simple ViewSet for listing or retrieving users.
|
||||
"""
|
||||
def list(self, request):
|
||||
queryset = User.objects.all()
|
||||
serializer = UserSerializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
def retrieve(self, request, pk=None):
|
||||
queryset = User.objects.all()
|
||||
user = get_object_or_404(queryset, pk=pk)
|
||||
serializer = UserSerializer(user)
|
||||
return Response(serializer.data)
|
||||
|
||||
If we need to, we can bind this viewset into two separate views, like so:
|
||||
|
||||
user_list = UserViewSet.as_view({'get': 'list'})
|
||||
user_detail = UserViewSet.as_view({'get': 'retrieve'})
|
||||
|
||||
Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated.
|
||||
|
||||
from myapp.views import UserViewSet
|
||||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register(r'users', UserViewSet, basename='user')
|
||||
urlpatterns = router.urls
|
||||
|
||||
Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
A viewset for viewing and editing user instances.
|
||||
"""
|
||||
serializer_class = UserSerializer
|
||||
queryset = User.objects.all()
|
||||
|
||||
There are two main advantages of using a `ViewSet` class over using a `View` class.
|
||||
|
||||
* Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views.
|
||||
* By using routers, we no longer need to deal with wiring up the URL conf ourselves.
|
||||
|
||||
Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.
|
||||
|
||||
|
||||
## ViewSet actions
|
||||
|
||||
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:
|
||||
|
||||
class UserViewSet(viewsets.ViewSet):
|
||||
"""
|
||||
Example empty viewset demonstrating the standard
|
||||
actions that will be handled by a router class.
|
||||
|
||||
If you're using format suffixes, make sure to also include
|
||||
the `format=None` keyword argument for each action.
|
||||
"""
|
||||
|
||||
def list(self, request):
|
||||
pass
|
||||
|
||||
def create(self, request):
|
||||
pass
|
||||
|
||||
def retrieve(self, request, pk=None):
|
||||
pass
|
||||
|
||||
def update(self, request, pk=None):
|
||||
pass
|
||||
|
||||
def partial_update(self, request, pk=None):
|
||||
pass
|
||||
|
||||
def destroy(self, request, pk=None):
|
||||
pass
|
||||
|
||||
## Introspecting ViewSet actions
|
||||
|
||||
During dispatch, the following attributes are available on the `ViewSet`.
|
||||
|
||||
* `basename` - the base to use for the URL names that are created.
|
||||
* `action` - the name of the current action (e.g., `list`, `create`).
|
||||
* `detail` - boolean indicating if the current action is configured for a list or detail view.
|
||||
* `suffix` - the display suffix for the viewset type - mirrors the `detail` attribute.
|
||||
* `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 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):
|
||||
"""
|
||||
Instantiates and returns the list of permissions that this view requires.
|
||||
"""
|
||||
if self.action == 'list':
|
||||
permission_classes = [IsAuthenticated]
|
||||
else:
|
||||
permission_classes = [IsAdminUser]
|
||||
return [permission() for permission in permission_classes]
|
||||
|
||||
**Note**: the `action` attribute is not available in the `get_parsers`, `get_authenticators` and `get_content_negotiator` methods, as it is set _after_ they are called in the framework lifecycle. If you override one of these methods and try to access the `action` attribute in them, you will get an `AttributeError` error.
|
||||
|
||||
## Marking extra actions for routing
|
||||
|
||||
If you have ad-hoc methods that should be routable, you can mark them as such with the `@action` decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the `detail` argument to `True` or `False`. The router will configure its URL patterns accordingly. e.g., the `DefaultRouter` will configure detail actions to contain `pk` in their URL patterns.
|
||||
|
||||
A more complete example of extra actions:
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import status, viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from myapp.serializers import UserSerializer, PasswordSerializer
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
A viewset that provides the standard actions
|
||||
"""
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
|
||||
@action(detail=True, methods=['post'])
|
||||
def set_password(self, request, pk=None):
|
||||
user = self.get_object()
|
||||
serializer = PasswordSerializer(data=request.data)
|
||||
if serializer.is_valid():
|
||||
user.set_password(serializer.validated_data['password'])
|
||||
user.save()
|
||||
return Response({'status': 'password set'})
|
||||
else:
|
||||
return Response(serializer.errors,
|
||||
status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
@action(detail=False)
|
||||
def recent_users(self, request):
|
||||
recent_users = User.objects.all().order_by('-last_login')
|
||||
|
||||
page = self.paginate_queryset(recent_users)
|
||||
if page is not None:
|
||||
serializer = self.get_serializer(page, many=True)
|
||||
return self.get_paginated_response(serializer.data)
|
||||
|
||||
serializer = self.get_serializer(recent_users, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
The `action` decorator will route `GET` requests by default, but may also accept other HTTP methods by setting the `methods` argument. For example:
|
||||
|
||||
@action(detail=True, methods=['post', 'delete'])
|
||||
def unset_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
Argument `methods` also supports HTTP methods defined as [HTTPMethod](https://docs.python.org/3/library/http.html#http.HTTPMethod). Example below is identical to the one above:
|
||||
|
||||
from http import HTTPMethod
|
||||
|
||||
@action(detail=True, methods=[HTTPMethod.POST, HTTPMethod.DELETE])
|
||||
def unset_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
The decorator allows you to override any viewset-level configuration such as `permission_classes`, `serializer_class`, `filter_backends`...:
|
||||
|
||||
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])
|
||||
def set_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
The two new actions will then be available at the urls `^users/{pk}/set_password/$` and `^users/{pk}/unset_password/$`. Use the `url_path` and `url_name` parameters to change the URL segment and the reverse URL name of the action.
|
||||
|
||||
To view all extra actions, call the `.get_extra_actions()` method.
|
||||
|
||||
### Routing additional HTTP methods for extra actions
|
||||
|
||||
Extra actions can map additional HTTP methods to separate `ViewSet` methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments.
|
||||
|
||||
```python
|
||||
@action(detail=True, methods=["put"], name="Change Password")
|
||||
def password(self, request, pk=None):
|
||||
"""Update the user's password."""
|
||||
...
|
||||
|
||||
|
||||
@password.mapping.delete
|
||||
def delete_password(self, request, pk=None):
|
||||
"""Delete the user's password."""
|
||||
...
|
||||
```
|
||||
|
||||
## Reversing action URLs
|
||||
|
||||
If you need to get the URL of an action, use the `.reverse_action()` method. This is a convenience wrapper for `reverse()`, automatically passing the view's `request` object and prepending the `url_name` with the `.basename` attribute.
|
||||
|
||||
Note that the `basename` is provided by the router during `ViewSet` registration. If you are not using a router, then you must provide the `basename` argument to the `.as_view()` method.
|
||||
|
||||
Using the example from the previous section:
|
||||
|
||||
```pycon
|
||||
>>> view.reverse_action("set-password", args=["1"])
|
||||
'http://localhost:8000/api/users/1/set_password'
|
||||
```
|
||||
|
||||
Alternatively, you can use the `url_name` attribute set by the `@action` decorator.
|
||||
|
||||
```pycon
|
||||
>>> view.reverse_action(view.set_password.url_name, args=['1'])
|
||||
'http://localhost:8000/api/users/1/set_password'
|
||||
```
|
||||
|
||||
The `url_name` argument for `.reverse_action()` should match the same argument to the `@action` decorator. Additionally, this method can be used to reverse the default actions, such as `list` and `create`.
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## ViewSet
|
||||
|
||||
The `ViewSet` class inherits from `APIView`. You can use any of the standard attributes such as `permission_classes`, `authentication_classes` in order to control the API policy on the viewset.
|
||||
|
||||
The `ViewSet` class does not provide any implementations of actions. In order to use a `ViewSet` class you'll override the class and define the action implementations explicitly.
|
||||
|
||||
## GenericViewSet
|
||||
|
||||
The `GenericViewSet` class inherits from `GenericAPIView`, and provides the default set of `get_object`, `get_queryset` methods and other generic view base behavior, but does not include any actions by default.
|
||||
|
||||
In order to use a `GenericViewSet` class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.
|
||||
|
||||
## ModelViewSet
|
||||
|
||||
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()`.
|
||||
|
||||
#### Example
|
||||
|
||||
Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example:
|
||||
|
||||
class AccountViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
A simple ViewSet for viewing and editing accounts.
|
||||
"""
|
||||
queryset = Account.objects.all()
|
||||
serializer_class = AccountSerializer
|
||||
permission_classes = [IsAccountAdminOrReadOnly]
|
||||
|
||||
Note that you can use any of the standard attributes or method overrides provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically determines the queryset it should operate on, you might do something like this:
|
||||
|
||||
class AccountViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
A simple ViewSet for viewing and editing the accounts
|
||||
associated with the user.
|
||||
"""
|
||||
serializer_class = AccountSerializer
|
||||
permission_classes = [IsAccountAdminOrReadOnly]
|
||||
|
||||
def get_queryset(self):
|
||||
return self.request.user.accounts.all()
|
||||
|
||||
Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the basename of your Model automatically, and so you will have to specify the `basename` kwarg as part of your [router registration][routers].
|
||||
|
||||
Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.
|
||||
|
||||
## ReadOnlyModelViewSet
|
||||
|
||||
The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`.
|
||||
|
||||
#### Example
|
||||
|
||||
As with `ModelViewSet`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example:
|
||||
|
||||
class AccountViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
"""
|
||||
A simple ViewSet for viewing accounts.
|
||||
"""
|
||||
queryset = Account.objects.all()
|
||||
serializer_class = AccountSerializer
|
||||
|
||||
Again, as with `ModelViewSet`, you can use any of the standard attributes and method overrides available to `GenericAPIView`.
|
||||
|
||||
# Custom ViewSet base classes
|
||||
|
||||
You may need to provide custom `ViewSet` classes that do not have the full set of `ModelViewSet` actions, or that customize the behavior in some other way.
|
||||
|
||||
## Example
|
||||
|
||||
To create a base viewset class that provides `create`, `list` and `retrieve` operations, inherit from `GenericViewSet`, and mixin the required actions:
|
||||
|
||||
from rest_framework import mixins, viewsets
|
||||
|
||||
class CreateListRetrieveViewSet(mixins.CreateModelMixin,
|
||||
mixins.ListModelMixin,
|
||||
mixins.RetrieveModelMixin,
|
||||
viewsets.GenericViewSet):
|
||||
"""
|
||||
A viewset that provides `retrieve`, `create`, and `list` actions.
|
||||
|
||||
To use it, override the class and set the `.queryset` and
|
||||
`.serializer_class` attributes.
|
||||
"""
|
||||
pass
|
||||
|
||||
By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple viewsets across your API.
|
||||
|
||||
[cite]: https://guides.rubyonrails.org/action_controller_overview.html
|
||||
[routers]: routers.md
|
|
@ -1,965 +0,0 @@
|
|||
# Django REST framework 3.0
|
||||
|
||||
The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views.
|
||||
|
||||
**This release is incremental in nature. There *are* some breaking API changes, and upgrading *will* require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.**
|
||||
|
||||
The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.
|
||||
|
||||
3.0 is the first of three releases that have been funded by our recent [Kickstarter campaign][kickstarter].
|
||||
|
||||
As ever, a huge thank you to our many [wonderful sponsors][sponsors]. If you're looking for a Django gig, and want to work with smart community-minded folks, you should probably check out that list and see who's hiring.
|
||||
|
||||
---
|
||||
|
||||
## New features
|
||||
|
||||
Notable features of this new release include:
|
||||
|
||||
* Printable representations on serializers that allow you to inspect exactly what fields are present on the instance.
|
||||
* Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit `ModelSerializer` class and the explicit `Serializer` class.
|
||||
* A new `BaseSerializer` class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic.
|
||||
* A cleaner fields API including new classes such as `ListField` and `MultipleChoiceField`.
|
||||
* [Super simple default implementations][mixins.py] for the generic views.
|
||||
* 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.
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
#### REST framework: Under the hood.
|
||||
|
||||
This talk from the [Django: Under the Hood](https://www.djangounderthehood.com/) event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.
|
||||
|
||||
<iframe style="display: block; margin: 0 auto 0 auto" width="560" height="315" src="//www.youtube.com/embed/3cSsbe-tA0E" frameborder="0" allowfullscreen></iframe>
|
||||
|
||||
---
|
||||
|
||||
*Below is an in-depth guide to the API changes and migration notes for 3.0.*
|
||||
|
||||
## Request objects
|
||||
|
||||
#### The `.data` and `.query_params` properties.
|
||||
|
||||
The usage of `request.DATA` and `request.FILES` is now pending deprecation in favor of a single `request.data` attribute that contains *all* the parsed data.
|
||||
|
||||
Having separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports.
|
||||
|
||||
You may now pass all the request data to a serializer class in a single argument:
|
||||
|
||||
# Do this...
|
||||
ExampleSerializer(data=request.data)
|
||||
|
||||
Instead of passing the files argument separately:
|
||||
|
||||
# Don't do this...
|
||||
ExampleSerializer(data=request.DATA, files=request.FILES)
|
||||
|
||||
|
||||
The usage of `request.QUERY_PARAMS` is now pending deprecation in favor of the lowercased `request.query_params`.
|
||||
|
||||
---
|
||||
|
||||
## Serializers
|
||||
|
||||
#### Single-step object creation.
|
||||
|
||||
Previously the serializers used a two-step object creation, as follows:
|
||||
|
||||
1. Validating the data would create an object instance. This instance would be available as `serializer.object`.
|
||||
2. Calling `serializer.save()` would then save the object instance to the database.
|
||||
|
||||
This style is in-line with how the `ModelForm` class works in Django, but is problematic for a number of reasons:
|
||||
|
||||
* Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when `.save()` is called.
|
||||
* Instantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. `ExampleModel.objects.create(...)`. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.
|
||||
* The two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save?
|
||||
|
||||
We now use single-step object creation, like so:
|
||||
|
||||
1. Validating the data makes the cleaned data available as `serializer.validated_data`.
|
||||
2. Calling `serializer.save()` then saves and returns the new object instance.
|
||||
|
||||
The resulting API changes are further detailed below.
|
||||
|
||||
#### The `.create()` and `.update()` methods.
|
||||
|
||||
The `.restore_object()` method is now removed, and we instead have two separate methods, `.create()` and `.update()`. These methods work slightly different to the previous `.restore_object()`.
|
||||
|
||||
When using the `.create()` and `.update()` methods you should both create *and save* the object instance. This is in contrast to the previous `.restore_object()` behavior that would instantiate the object but not save it.
|
||||
|
||||
These methods also replace the optional `.save_object()` method, which no longer exists.
|
||||
|
||||
The following example from the tutorial previously used `restore_object()` to handle both creating and updating object instances.
|
||||
|
||||
def restore_object(self, attrs, instance=None):
|
||||
if instance:
|
||||
# Update existing instance
|
||||
instance.title = attrs.get('title', instance.title)
|
||||
instance.code = attrs.get('code', instance.code)
|
||||
instance.linenos = attrs.get('linenos', instance.linenos)
|
||||
instance.language = attrs.get('language', instance.language)
|
||||
instance.style = attrs.get('style', instance.style)
|
||||
return instance
|
||||
|
||||
# Create new instance
|
||||
return Snippet(**attrs)
|
||||
|
||||
This would now be split out into two separate methods.
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
instance.title = validated_data.get('title', instance.title)
|
||||
instance.code = validated_data.get('code', instance.code)
|
||||
instance.linenos = validated_data.get('linenos', instance.linenos)
|
||||
instance.language = validated_data.get('language', instance.language)
|
||||
instance.style = validated_data.get('style', instance.style)
|
||||
instance.save()
|
||||
return instance
|
||||
|
||||
def create(self, validated_data):
|
||||
return Snippet.objects.create(**validated_data)
|
||||
|
||||
Note that these methods should return the newly created object instance.
|
||||
|
||||
#### Use `.validated_data` instead of `.object`.
|
||||
|
||||
You must now use the `.validated_data` attribute if you need to inspect the data before saving, rather than using the `.object` attribute, which no longer exists.
|
||||
|
||||
For example the following code *is no longer valid*:
|
||||
|
||||
if serializer.is_valid():
|
||||
name = serializer.object.name # Inspect validated field data.
|
||||
logging.info('Creating ticket "%s"' % name)
|
||||
serializer.object.user = request.user # Include the user when saving.
|
||||
serializer.save()
|
||||
|
||||
Instead of using `.object` to inspect a partially constructed instance, you would now use `.validated_data` to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the `.save()` method as keyword arguments.
|
||||
|
||||
The corresponding code would now look like this:
|
||||
|
||||
if serializer.is_valid():
|
||||
name = serializer.validated_data['name'] # Inspect validated field data.
|
||||
logging.info('Creating ticket "%s"' % name)
|
||||
serializer.save(user=request.user) # Include the user when saving.
|
||||
|
||||
#### Using `.is_valid(raise_exception=True)`
|
||||
|
||||
The `.is_valid()` method now takes an optional boolean flag, `raise_exception`.
|
||||
|
||||
Calling `.is_valid(raise_exception=True)` will cause a `ValidationError` to be raised if the serializer data contains validation errors. This error will be handled by REST framework's default exception handler, allowing you to remove error response handling from your view code.
|
||||
|
||||
The handling and formatting of error responses may be altered globally by using the `EXCEPTION_HANDLER` settings key.
|
||||
|
||||
This change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides.
|
||||
|
||||
#### Using `serializers.ValidationError`.
|
||||
|
||||
Previously `serializers.ValidationError` error was simply a synonym for `django.core.exceptions.ValidationError`. This has now been altered so that it inherits from the standard `APIException` base class.
|
||||
|
||||
The reason behind this is that Django's `ValidationError` class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers.
|
||||
|
||||
For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you should prefer using the `serializers.ValidationError` exception class, and not Django's built-in exception.
|
||||
|
||||
We strongly recommend that you use the namespaced import style of `import serializers` and not `from serializers import ValidationError` in order to avoid any potential confusion.
|
||||
|
||||
#### Change to `validate_<field_name>`.
|
||||
|
||||
The `validate_<field_name>` method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field:
|
||||
|
||||
def validate_score(self, attrs, source):
|
||||
if attrs['score'] % 10 != 0:
|
||||
raise serializers.ValidationError('This field should be a multiple of ten.')
|
||||
return attrs
|
||||
|
||||
This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value.
|
||||
|
||||
def validate_score(self, value):
|
||||
if value % 10 != 0:
|
||||
raise serializers.ValidationError('This field should be a multiple of ten.')
|
||||
return value
|
||||
|
||||
Any ad-hoc validation that applies to more than one field should go in the `.validate(self, attrs)` method as usual.
|
||||
|
||||
Because `.validate_<field_name>` would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use `.validate()` instead.
|
||||
|
||||
You can either return `non_field_errors` from the validate method by raising a simple `ValidationError`
|
||||
|
||||
def validate(self, attrs):
|
||||
# serializer.errors == {'non_field_errors': ['A non field error']}
|
||||
raise serializers.ValidationError('A non field error')
|
||||
|
||||
Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the `ValidationError`, like so:
|
||||
|
||||
def validate(self, attrs):
|
||||
# serializer.errors == {'my_field': ['A field error']}
|
||||
raise serializers.ValidationError({'my_field': 'A field error'})
|
||||
|
||||
This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.
|
||||
|
||||
#### Removal of `transform_<field_name>`.
|
||||
|
||||
The under-used `transform_<field_name>` on serializer classes is no longer provided. Instead you should just override `to_representation()` if you need to apply any modifications to the representation style.
|
||||
|
||||
For example:
|
||||
|
||||
def to_representation(self, instance):
|
||||
ret = super(UserSerializer, self).to_representation(instance)
|
||||
ret['username'] = ret['username'].lower()
|
||||
return ret
|
||||
|
||||
Dropping the extra point of API means there's now only one right way to do things. This helps with repetition and reinforcement of the core API, rather than having multiple differing approaches.
|
||||
|
||||
If you absolutely need to preserve `transform_<field_name>` behavior, for example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, or serializer base class that add the behavior back in. For example:
|
||||
|
||||
class BaseModelSerializer(ModelSerializer):
|
||||
"""
|
||||
A custom ModelSerializer class that preserves 2.x style `transform_<field_name>` behavior.
|
||||
"""
|
||||
def to_representation(self, instance):
|
||||
ret = super(BaseModelSerializer, self).to_representation(instance)
|
||||
for key, value in ret.items():
|
||||
method = getattr(self, 'transform_' + key, None)
|
||||
if method is not None:
|
||||
ret[key] = method(value)
|
||||
return ret
|
||||
|
||||
#### Differences between ModelSerializer validation and ModelForm.
|
||||
|
||||
This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes.
|
||||
|
||||
For the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different.
|
||||
|
||||
The one difference that you do need to note is that the `.clean()` method will not be called as part of serializer validation, as it would be if using a `ModelForm`. Use the serializer `.validate()` method to perform a final validation step on incoming data where required.
|
||||
|
||||
There may be some cases where you really do need to keep validation logic in the model `.clean()` method, and cannot instead separate it into the serializer `.validate()`. You can do so by explicitly instantiating a model instance in the `.validate()` method.
|
||||
|
||||
def validate(self, attrs):
|
||||
instance = ExampleModel(**attrs)
|
||||
instance.clean()
|
||||
return attrs
|
||||
|
||||
Again, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path.
|
||||
|
||||
#### Writable nested serialization.
|
||||
|
||||
REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic:
|
||||
|
||||
* There can be complex dependencies involved in order of saving multiple related model instances.
|
||||
* It's unclear what behavior the user should expect when related models are passed `None` data.
|
||||
* It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records.
|
||||
|
||||
Using the `depth` option on `ModelSerializer` will now create **read-only nested serializers** by default.
|
||||
|
||||
If you try to use a writable nested serializer without writing a custom `create()` and/or `update()` method you'll see an assertion error when you attempt to save the serializer. For example:
|
||||
|
||||
>>> class ProfileSerializer(serializers.ModelSerializer):
|
||||
>>> class Meta:
|
||||
>>> model = Profile
|
||||
>>> fields = ['address', 'phone']
|
||||
>>>
|
||||
>>> class UserSerializer(serializers.ModelSerializer):
|
||||
>>> profile = ProfileSerializer()
|
||||
>>> class Meta:
|
||||
>>> model = User
|
||||
>>> fields = ['username', 'email', 'profile']
|
||||
>>>
|
||||
>>> data = {
|
||||
>>> 'username': 'lizzy',
|
||||
>>> 'email': 'lizzy@example.com',
|
||||
>>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}
|
||||
>>> }
|
||||
>>>
|
||||
>>> serializer = UserSerializer(data=data)
|
||||
>>> serializer.save()
|
||||
AssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields.
|
||||
|
||||
To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the `create()` and/or `update()` methods explicitly.
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer):
|
||||
profile = ProfileSerializer()
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ['username', 'email', 'profile']
|
||||
|
||||
def create(self, validated_data):
|
||||
profile_data = validated_data.pop('profile')
|
||||
user = User.objects.create(**validated_data)
|
||||
Profile.objects.create(user=user, **profile_data)
|
||||
return user
|
||||
|
||||
The single-step object creation makes this far simpler and more obvious than the previous `.restore_object()` behavior.
|
||||
|
||||
#### Printable serializer representations.
|
||||
|
||||
Serializer instances now support a printable representation that allows you to inspect the fields present on the instance.
|
||||
|
||||
For instance, given the following example model:
|
||||
|
||||
class LocationRating(models.Model):
|
||||
location = models.CharField(max_length=100)
|
||||
rating = models.IntegerField()
|
||||
created_by = models.ForeignKey(User)
|
||||
|
||||
Let's create a simple `ModelSerializer` class corresponding to the `LocationRating` model.
|
||||
|
||||
class LocationRatingSerializer(serializer.ModelSerializer):
|
||||
class Meta:
|
||||
model = LocationRating
|
||||
|
||||
We can now inspect the serializer representation in the Django shell, using `python manage.py shell`...
|
||||
|
||||
>>> serializer = LocationRatingSerializer()
|
||||
>>> print(serializer) # Or use `print serializer` in Python 2.x
|
||||
LocationRatingSerializer():
|
||||
id = IntegerField(label='ID', read_only=True)
|
||||
location = CharField(max_length=100)
|
||||
rating = IntegerField()
|
||||
created_by = PrimaryKeyRelatedField(queryset=User.objects.all())
|
||||
|
||||
#### The `extra_kwargs` option.
|
||||
|
||||
The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDeprecation` and replaced with a more generic `extra_kwargs`.
|
||||
|
||||
class MySerializer(serializer.ModelSerializer):
|
||||
class Meta:
|
||||
model = MyModel
|
||||
fields = ['id', 'email', 'notes', 'is_admin']
|
||||
extra_kwargs = {
|
||||
'is_admin': {'write_only': True}
|
||||
}
|
||||
|
||||
Alternatively, specify the field explicitly on the serializer class:
|
||||
|
||||
class MySerializer(serializer.ModelSerializer):
|
||||
is_admin = serializers.BooleanField(write_only=True)
|
||||
|
||||
class Meta:
|
||||
model = MyModel
|
||||
fields = ['id', 'email', 'notes', 'is_admin']
|
||||
|
||||
The `read_only_fields` option remains as a convenient shortcut for the more common case.
|
||||
|
||||
#### Changes to `HyperlinkedModelSerializer`.
|
||||
|
||||
The `view_name` and `lookup_field` options have been moved to `PendingDeprecation`. They are no longer required, as you can use the `extra_kwargs` argument instead:
|
||||
|
||||
class MySerializer(serializer.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = MyModel
|
||||
fields = ['url', 'email', 'notes', 'is_admin']
|
||||
extra_kwargs = {
|
||||
'url': {'lookup_field': 'uuid'}
|
||||
}
|
||||
|
||||
Alternatively, specify the field explicitly on the serializer class:
|
||||
|
||||
class MySerializer(serializer.HyperlinkedModelSerializer):
|
||||
url = serializers.HyperlinkedIdentityField(
|
||||
view_name='mymodel-detail',
|
||||
lookup_field='uuid'
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = MyModel
|
||||
fields = ['url', 'email', 'notes', 'is_admin']
|
||||
|
||||
#### Fields for model methods and properties.
|
||||
|
||||
With `ModelSerializer` you can now specify field names in the `fields` option that refer to model methods or properties. For example, suppose you have the following model:
|
||||
|
||||
class Invitation(models.Model):
|
||||
created = models.DateTimeField()
|
||||
to_email = models.EmailField()
|
||||
message = models.CharField(max_length=1000)
|
||||
|
||||
def expiry_date(self):
|
||||
return self.created + datetime.timedelta(days=30)
|
||||
|
||||
You can include `expiry_date` as a field option on a `ModelSerializer` class.
|
||||
|
||||
class InvitationSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Invitation
|
||||
fields = ['to_email', 'message', 'expiry_date']
|
||||
|
||||
These fields will be mapped to `serializers.ReadOnlyField()` instances.
|
||||
|
||||
>>> serializer = InvitationSerializer()
|
||||
>>> print(repr(serializer))
|
||||
InvitationSerializer():
|
||||
to_email = EmailField(max_length=75)
|
||||
message = CharField(max_length=1000)
|
||||
expiry_date = ReadOnlyField()
|
||||
|
||||
#### The `ListSerializer` class.
|
||||
|
||||
The `ListSerializer` class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.
|
||||
|
||||
class MultipleUserSerializer(ListSerializer):
|
||||
child = UserSerializer()
|
||||
|
||||
You can also still use the `many=True` argument to serializer classes. It's worth noting that `many=True` argument transparently creates a `ListSerializer` instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase.
|
||||
|
||||
You will typically want to *continue to use the existing `many=True` flag* rather than declaring `ListSerializer` classes explicitly, but declaring the classes explicitly can be useful if you need to write custom `create` or `update` methods for bulk updates, or provide for other custom behavior.
|
||||
|
||||
See also the new `ListField` class, which validates input in the same way, but does not include the serializer interfaces of `.is_valid()`, `.data`, `.save()` and so on.
|
||||
|
||||
#### The `BaseSerializer` class.
|
||||
|
||||
REST framework now includes a simple `BaseSerializer` class that can be used to easily support alternative serialization and deserialization styles.
|
||||
|
||||
This class implements the same basic API as the `Serializer` class:
|
||||
|
||||
* `.data` - Returns the outgoing primitive representation.
|
||||
* `.is_valid()` - Deserializes and validates incoming data.
|
||||
* `.validated_data` - Returns the validated incoming data.
|
||||
* `.errors` - Returns an errors during validation.
|
||||
* `.save()` - Persists the validated data into an object instance.
|
||||
|
||||
There are four methods that can be overridden, depending on what functionality you want the serializer class to support:
|
||||
|
||||
* `.to_representation()` - Override this to support serialization, for read operations.
|
||||
* `.to_internal_value()` - Override this to support deserialization, for write operations.
|
||||
* `.create()` and `.update()` - Override either or both of these to support saving instances.
|
||||
|
||||
Because this class provides the same interface as the `Serializer` class, you can use it with the existing generic class-based views exactly as you would for a regular `Serializer` or `ModelSerializer`.
|
||||
|
||||
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.
|
||||
|
||||
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:
|
||||
|
||||
class HighScore(models.Model):
|
||||
created = models.DateTimeField(auto_now_add=True)
|
||||
player_name = models.CharField(max_length=10)
|
||||
score = models.IntegerField()
|
||||
|
||||
It's simple to create a read-only serializer for converting `HighScore` instances into primitive data types.
|
||||
|
||||
class HighScoreSerializer(serializers.BaseSerializer):
|
||||
def to_representation(self, obj):
|
||||
return {
|
||||
'score': obj.score,
|
||||
'player_name': obj.player_name
|
||||
}
|
||||
|
||||
We can now use this class to serialize single `HighScore` instances:
|
||||
|
||||
@api_view(['GET'])
|
||||
def high_score(request, pk):
|
||||
instance = HighScore.objects.get(pk=pk)
|
||||
serializer = HighScoreSerializer(instance)
|
||||
return Response(serializer.data)
|
||||
|
||||
Or use it to serialize multiple instances:
|
||||
|
||||
@api_view(['GET'])
|
||||
def all_high_scores(request):
|
||||
queryset = HighScore.objects.order_by('-score')
|
||||
serializer = HighScoreSerializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
##### 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 `ValidationError` if the supplied data is in an incorrect format.
|
||||
|
||||
Once you've implemented `.to_internal_value()`, the basic validation API will be available on the serializer, and you will be able to use `.is_valid()`, `.validated_data` and `.errors`.
|
||||
|
||||
If you want to also support `.save()` you'll need to also implement either or both of the `.create()` and `.update()` methods.
|
||||
|
||||
Here's a complete example of our previous `HighScoreSerializer`, that's been updated to support both read and write operations.
|
||||
|
||||
class HighScoreSerializer(serializers.BaseSerializer):
|
||||
def to_internal_value(self, data):
|
||||
score = data.get('score')
|
||||
player_name = data.get('player_name')
|
||||
|
||||
# Perform the data validation.
|
||||
if not score:
|
||||
raise ValidationError({
|
||||
'score': 'This field is required.'
|
||||
})
|
||||
if not player_name:
|
||||
raise ValidationError({
|
||||
'player_name': 'This field is required.'
|
||||
})
|
||||
if len(player_name) > 10:
|
||||
raise ValidationError({
|
||||
'player_name': 'May not be more than 10 characters.'
|
||||
})
|
||||
|
||||
# Return the validated values. This will be available as
|
||||
# the `.validated_data` property.
|
||||
return {
|
||||
'score': int(score),
|
||||
'player_name': player_name
|
||||
}
|
||||
|
||||
def to_representation(self, obj):
|
||||
return {
|
||||
'score': obj.score,
|
||||
'player_name': obj.player_name
|
||||
}
|
||||
|
||||
def create(self, validated_data):
|
||||
return HighScore.objects.create(**validated_data)
|
||||
|
||||
#### Creating new generic serializers with `BaseSerializer`.
|
||||
|
||||
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.
|
||||
|
||||
class ObjectSerializer(serializers.BaseSerializer):
|
||||
"""
|
||||
A read-only serializer that coerces arbitrary complex objects
|
||||
into primitive representations.
|
||||
"""
|
||||
def to_representation(self, obj):
|
||||
for attribute_name in dir(obj):
|
||||
attribute = getattr(obj, attribute_name)
|
||||
if attribute_name.startswith('_'):
|
||||
# Ignore private attributes.
|
||||
pass
|
||||
elif hasattr(attribute, '__call__'):
|
||||
# Ignore methods and other callables.
|
||||
pass
|
||||
elif isinstance(attribute, (str, int, bool, float, type(None))):
|
||||
# Primitive types can be passed through unmodified.
|
||||
output[attribute_name] = attribute
|
||||
elif isinstance(attribute, list):
|
||||
# Recursively deal with items in lists.
|
||||
output[attribute_name] = [
|
||||
self.to_representation(item) for item in attribute
|
||||
]
|
||||
elif isinstance(attribute, dict):
|
||||
# Recursively deal with items in dictionaries.
|
||||
output[attribute_name] = {
|
||||
str(key): self.to_representation(value)
|
||||
for key, value in attribute.items()
|
||||
}
|
||||
else:
|
||||
# Force anything else to its string representation.
|
||||
output[attribute_name] = str(attribute)
|
||||
|
||||
---
|
||||
|
||||
## Serializer fields
|
||||
|
||||
#### The `Field` and `ReadOnly` field classes.
|
||||
|
||||
There are some minor tweaks to the field base classes.
|
||||
|
||||
Previously we had these two base classes:
|
||||
|
||||
* `Field` as the base class for read-only fields. A default implementation was included for serializing data.
|
||||
* `WritableField` as the base class for read-write fields.
|
||||
|
||||
We now use the following:
|
||||
|
||||
* `Field` is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.
|
||||
* `ReadOnlyField` is a concrete implementation for read-only fields that simply returns the attribute value without modification.
|
||||
|
||||
#### The `required`, `allow_null`, `allow_blank` and `default` arguments.
|
||||
|
||||
REST framework now has more explicit and clear control over validating empty values for fields.
|
||||
|
||||
Previously the meaning of the `required=False` keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be `None` or the empty string.
|
||||
|
||||
We now have a better separation, with separate `required`, `allow_null` and `allow_blank` arguments.
|
||||
|
||||
The following set of arguments are used to control validation of empty values:
|
||||
|
||||
* `required=False`: The value does not need to be present in the input, and will not be passed to `.create()` or `.update()` if it is not seen.
|
||||
* `default=<value>`: The value does not need to be present in the input, and a default value will be passed to `.create()` or `.update()` if it is not seen.
|
||||
* `allow_null=True`: `None` is a valid input.
|
||||
* `allow_blank=True`: `''` is valid input. For `CharField` and subclasses only.
|
||||
|
||||
Typically you'll want to use `required=False` if the corresponding model field has a default value, and additionally set either `allow_null=True` or `allow_blank=True` if required.
|
||||
|
||||
The `default` argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the `required` argument when a default is specified, and doing so will result in an error.
|
||||
|
||||
#### Coercing output types.
|
||||
|
||||
The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an `IntegerField` would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior.
|
||||
|
||||
#### Removal of `.validate()`.
|
||||
|
||||
The `.validate()` method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override `to_internal_value()`.
|
||||
|
||||
class UppercaseCharField(serializers.CharField):
|
||||
def to_internal_value(self, data):
|
||||
value = super(UppercaseCharField, self).to_internal_value(data)
|
||||
if value != value.upper():
|
||||
raise serializers.ValidationError('The input should be uppercase only.')
|
||||
return value
|
||||
|
||||
Previously validation errors could be raised in either `.to_native()` or `.validate()`, making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.
|
||||
|
||||
#### The `ListField` class.
|
||||
|
||||
The `ListField` class has now been added. This field validates list input. It takes a `child` keyword argument which is used to specify the field used to validate each item in the list. For example:
|
||||
|
||||
scores = ListField(child=IntegerField(min_value=0, max_value=100))
|
||||
|
||||
You can also use a declarative style to create new subclasses of `ListField`, like this:
|
||||
|
||||
class ScoresField(ListField):
|
||||
child = IntegerField(min_value=0, max_value=100)
|
||||
|
||||
We can now use the `ScoresField` class inside another serializer:
|
||||
|
||||
scores = ScoresField()
|
||||
|
||||
See also the new `ListSerializer` class, which validates input in the same way, but also includes the serializer interfaces of `.is_valid()`, `.data`, `.save()` and so on.
|
||||
|
||||
#### The `ChoiceField` class may now accept a flat list.
|
||||
|
||||
The `ChoiceField` class may now accept a list of choices in addition to the existing style of using a list of pairs of `(name, display_value)`. The following is now valid:
|
||||
|
||||
color = ChoiceField(choices=['red', 'green', 'blue'])
|
||||
|
||||
#### The `MultipleChoiceField` class.
|
||||
|
||||
The `MultipleChoiceField` class has been added. This field acts like `ChoiceField`, but returns a set, which may include none, one or many of the valid choices.
|
||||
|
||||
#### Changes to the custom field API.
|
||||
|
||||
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
|
||||
|
||||
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behavior in a way that did not simply lookup the field value from the object. For example...
|
||||
|
||||
def field_to_native(self, obj, field_name):
|
||||
"""A custom read-only field that returns the class name."""
|
||||
return obj.__class__.__name__
|
||||
|
||||
Now if you need to access the entire object you'll instead need to override one or both of the following:
|
||||
|
||||
* Use `get_attribute` to modify the attribute value passed to `to_representation()`.
|
||||
* Use `get_value` to modify the data value passed `to_internal_value()`.
|
||||
|
||||
For example:
|
||||
|
||||
def get_attribute(self, obj):
|
||||
# Pass the entire object through to `to_representation()`,
|
||||
# instead of the standard attribute lookup.
|
||||
return obj
|
||||
|
||||
def to_representation(self, value):
|
||||
return value.__class__.__name__
|
||||
|
||||
#### Explicit `queryset` required on relational fields.
|
||||
|
||||
Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a `ModelSerializer`.
|
||||
|
||||
This code *would be valid* in `2.4.3`:
|
||||
|
||||
class AccountSerializer(serializers.ModelSerializer):
|
||||
organizations = serializers.SlugRelatedField(slug_field='name')
|
||||
|
||||
class Meta:
|
||||
model = Account
|
||||
|
||||
However this code *would not be valid* in `3.0`:
|
||||
|
||||
# Missing `queryset`
|
||||
class AccountSerializer(serializers.Serializer):
|
||||
organizations = serializers.SlugRelatedField(slug_field='name')
|
||||
|
||||
def restore_object(self, attrs, instance=None):
|
||||
# ...
|
||||
|
||||
The queryset argument is now always required for writable relational fields.
|
||||
This removes some magic and makes it easier and more obvious to move between implicit `ModelSerializer` classes and explicit `Serializer` classes.
|
||||
|
||||
class AccountSerializer(serializers.ModelSerializer):
|
||||
organizations = serializers.SlugRelatedField(
|
||||
slug_field='name',
|
||||
queryset=Organization.objects.all()
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Account
|
||||
|
||||
The `queryset` argument is only ever required for writable fields, and is not required or valid for fields with `read_only=True`.
|
||||
|
||||
#### Optional argument to `SerializerMethodField`.
|
||||
|
||||
The argument to `SerializerMethodField` is now optional, and defaults to `get_<field_name>`. For example the following is valid:
|
||||
|
||||
class AccountSerializer(serializers.Serializer):
|
||||
# `method_name='get_billing_details'` by default.
|
||||
billing_details = serializers.SerializerMethodField()
|
||||
|
||||
def get_billing_details(self, account):
|
||||
return calculate_billing(account)
|
||||
|
||||
In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code *will raise an error*:
|
||||
|
||||
billing_details = serializers.SerializerMethodField('get_billing_details')
|
||||
|
||||
#### Enforcing consistent `source` usage.
|
||||
|
||||
I've see several codebases that unnecessarily include the `source` argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that `source` is usually not required.
|
||||
|
||||
The following usage will *now raise an error*:
|
||||
|
||||
email = serializers.EmailField(source='email')
|
||||
|
||||
#### The `UniqueValidator` and `UniqueTogetherValidator` classes.
|
||||
|
||||
REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit `Serializer` class instead of using `ModelSerializer`.
|
||||
|
||||
The `UniqueValidator` should be applied to a serializer field, and takes a single `queryset` argument.
|
||||
|
||||
from rest_framework import serializers
|
||||
from rest_framework.validators import UniqueValidator
|
||||
|
||||
class OrganizationSerializer(serializers.Serializer):
|
||||
url = serializers.HyperlinkedIdentityField(view_name='organization_detail')
|
||||
created = serializers.DateTimeField(read_only=True)
|
||||
name = serializers.CharField(
|
||||
max_length=100,
|
||||
validators=UniqueValidator(queryset=Organization.objects.all())
|
||||
)
|
||||
|
||||
The `UniqueTogetherValidator` should be applied to a serializer, and takes a `queryset` argument and a `fields` argument which should be a list or tuple of field names.
|
||||
|
||||
class RaceResultSerializer(serializers.Serializer):
|
||||
category = serializers.ChoiceField(['5k', '10k'])
|
||||
position = serializers.IntegerField()
|
||||
name = serializers.CharField(max_length=100)
|
||||
|
||||
class Meta:
|
||||
validators = [UniqueTogetherValidator(
|
||||
queryset=RaceResult.objects.all(),
|
||||
fields=['category', 'position']
|
||||
)]
|
||||
|
||||
#### The `UniqueForDateValidator` classes.
|
||||
|
||||
REST framework also now includes explicit validator classes for validating the `unique_for_date`, `unique_for_month`, and `unique_for_year` model field constraints. These are used internally instead of calling into `Model.full_clean()`.
|
||||
|
||||
These classes are documented in the [Validators](../api-guide/validators.md) section of the documentation.
|
||||
|
||||
---
|
||||
|
||||
## Generic views
|
||||
|
||||
#### Simplification of view logic.
|
||||
|
||||
The view logic for the default method handlers has been significantly simplified, due to the new serializers API.
|
||||
|
||||
#### Changes to pre/post save hooks.
|
||||
|
||||
The `pre_save` and `post_save` hooks no longer exist, but are replaced with `perform_create(self, serializer)` and `perform_update(self, serializer)`.
|
||||
|
||||
These methods should save the object instance by calling `serializer.save()`, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.
|
||||
|
||||
For example:
|
||||
|
||||
def perform_create(self, serializer):
|
||||
# Include the owner attribute directly, rather than from request data.
|
||||
instance = serializer.save(owner=self.request.user)
|
||||
# Perform a custom post-save action.
|
||||
send_email(instance.to_email, instance.message)
|
||||
|
||||
The `pre_delete` and `post_delete` hooks no longer exist, and are replaced with `.perform_destroy(self, instance)`, which should delete the instance and perform any custom actions.
|
||||
|
||||
def perform_destroy(self, instance):
|
||||
# Perform a custom pre-delete action.
|
||||
send_deletion_alert(user=instance.created_by, deleted=instance)
|
||||
# Delete the object instance.
|
||||
instance.delete()
|
||||
|
||||
#### Removal of view attributes.
|
||||
|
||||
The `.object` and `.object_list` attributes are no longer set on the view instance. Treating views as mutable object instances that store state during the processing of the view tends to be poor design, and can lead to obscure flow logic.
|
||||
|
||||
I would personally recommend that developers treat view instances as immutable objects in their application code.
|
||||
|
||||
#### PUT as create.
|
||||
|
||||
Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses.
|
||||
|
||||
Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious.
|
||||
|
||||
If you need to restore the previous behavior you may want to include [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views.
|
||||
|
||||
#### Customizing error responses.
|
||||
|
||||
The generic views now raise `ValidationFailed` exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a `400 Bad Request` response directly.
|
||||
|
||||
This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views.
|
||||
|
||||
---
|
||||
|
||||
## The metadata API
|
||||
|
||||
Behavior for dealing with `OPTIONS` requests was previously built directly into the class-based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework.
|
||||
|
||||
This makes it far easier to use a different style for `OPTIONS` responses throughout your API, and makes it possible to create third-party metadata policies.
|
||||
|
||||
---
|
||||
|
||||
## Serializers as HTML forms
|
||||
|
||||
REST framework 3.0 includes templated HTML form rendering for serializers.
|
||||
|
||||
This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.
|
||||
|
||||
Significant changes that you do need to be aware of include:
|
||||
|
||||
* Nested HTML forms are now supported, for example, a `UserSerializer` with a nested `ProfileSerializer` will now render a nested `fieldset` when used in the browsable API.
|
||||
* Nested lists of HTML forms are not yet supported, but are planned for 3.1.
|
||||
* Because we now use templated HTML form generation, **the `widget` option is no longer available for serializer fields**. You can instead control the template that is used for a given field, by using the `style` dictionary.
|
||||
|
||||
#### The `style` keyword argument for serializer fields.
|
||||
|
||||
The `style` keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the `HTMLFormRenderer` uses the `base_template` key to determine which template to render the field with.
|
||||
|
||||
For example, to use a `textarea` control instead of the default `input` control, you would use the following…
|
||||
|
||||
additional_notes = serializers.CharField(
|
||||
style={'base_template': 'textarea.html'}
|
||||
)
|
||||
|
||||
Similarly, to use a radio button control instead of the default `select` control, you would use the following…
|
||||
|
||||
color_channel = serializers.ChoiceField(
|
||||
choices=['red', 'blue', 'green'],
|
||||
style={'base_template': 'radio.html'}
|
||||
)
|
||||
|
||||
This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.
|
||||
|
||||
---
|
||||
|
||||
## API style
|
||||
|
||||
There are some improvements in the default style we use in our API responses.
|
||||
|
||||
#### Unicode JSON by default.
|
||||
|
||||
Unicode JSON is now the default. The `UnicodeJSONRenderer` class no longer exists, and the `UNICODE_JSON` setting has been added. To revert this behavior use the new setting:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'UNICODE_JSON': False
|
||||
}
|
||||
|
||||
#### Compact JSON by default.
|
||||
|
||||
We now output compact JSON in responses by default. For example, we return:
|
||||
|
||||
{"email":"amy@example.com","is_admin":true}
|
||||
|
||||
Instead of the following:
|
||||
|
||||
{"email": "amy@example.com", "is_admin": true}
|
||||
|
||||
The `COMPACT_JSON` setting has been added, and can be used to revert this behavior if needed:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'COMPACT_JSON': False
|
||||
}
|
||||
|
||||
#### File fields as URLs
|
||||
|
||||
The `FileField` and `ImageField` classes are now represented as URLs by default. You should ensure you set Django's [standard `MEDIA_URL` setting](https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-MEDIA_URL) appropriately, and ensure your application [serves the uploaded files](https://docs.djangoproject.com/en/stable/howto/static-files/#serving-uploaded-files-in-development).
|
||||
|
||||
You can revert this behavior, and display filenames in the representation by using the `UPLOADED_FILES_USE_URL` settings key:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'UPLOADED_FILES_USE_URL': False
|
||||
}
|
||||
|
||||
You can also modify serializer fields individually, using the `use_url` argument:
|
||||
|
||||
uploaded_file = serializers.FileField(use_url=False)
|
||||
|
||||
Also note that you should pass the `request` object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form `https://example.com/url_path/filename.txt`. For example:
|
||||
|
||||
context = {'request': request}
|
||||
serializer = ExampleSerializer(instance, context=context)
|
||||
return Response(serializer.data)
|
||||
|
||||
If the request is omitted from the context, the returned URLs will be of the form `/url_path/filename.txt`.
|
||||
|
||||
#### Throttle headers using `Retry-After`.
|
||||
|
||||
The custom `X-Throttle-Wait-Second` header has now been dropped in favor of the standard `Retry-After` header. You can revert this behavior if needed by writing a custom exception handler for your application.
|
||||
|
||||
#### Date and time objects as ISO-8601 strings in serializer data.
|
||||
|
||||
Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as `Date`, `Time` and `DateTime` objects, and later coerced to strings by the renderer.
|
||||
|
||||
You can modify this behavior globally by settings the existing `DATE_FORMAT`, `DATETIME_FORMAT` and `TIME_FORMAT` settings keys. Setting these values to `None` instead of their default value of `'iso-8601'` will result in native objects being returned in serializer data.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
# Return native `Date` and `Time` objects in `serializer.data`
|
||||
'DATETIME_FORMAT': None
|
||||
'DATE_FORMAT': None
|
||||
'TIME_FORMAT': None
|
||||
}
|
||||
|
||||
You can also modify serializer fields individually, using the `date_format`, `time_format` and `datetime_format` arguments:
|
||||
|
||||
# Return `DateTime` instances in `serializer.data`, not strings.
|
||||
created = serializers.DateTimeField(format=None)
|
||||
|
||||
#### Decimals as strings in serializer data.
|
||||
|
||||
Decimals are now coerced to strings by default in the serializer output. Previously they were returned as `Decimal` objects, and later coerced to strings by the renderer.
|
||||
|
||||
You can modify this behavior globally by using the `COERCE_DECIMAL_TO_STRING` settings key.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'COERCE_DECIMAL_TO_STRING': False
|
||||
}
|
||||
|
||||
Or modify it on an individual serializer field, using the `coerce_to_string` keyword argument.
|
||||
|
||||
# Return `Decimal` instances in `serializer.data`, not strings.
|
||||
amount = serializers.DecimalField(
|
||||
max_digits=10,
|
||||
decimal_places=2,
|
||||
coerce_to_string=False
|
||||
)
|
||||
|
||||
The default JSON renderer will return float objects for un-coerced `Decimal` instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.
|
||||
|
||||
---
|
||||
|
||||
## Miscellaneous notes
|
||||
|
||||
* The serializer `ChoiceField` does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.
|
||||
* Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party "autocomplete" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand.
|
||||
* Some of the default validation error messages were rewritten and might no longer be pre-translated. You can still [create language files with Django][django-localization] if you wish to localize them.
|
||||
* `APIException` subclasses could previously take any arbitrary type in the `detail` argument. These exceptions now use translatable text strings, and as a result call `force_text` on the `detail` argument, which *must be a string*. If you need complex arguments to an `APIException` class, you should subclass it and override the `__init__()` method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.
|
||||
|
||||
---
|
||||
|
||||
## What's coming next
|
||||
|
||||
3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.
|
||||
|
||||
The 3.1 release is planned to address improvements in the following components:
|
||||
|
||||
* Public API for using serializers as HTML forms.
|
||||
* Request parsing, mediatypes & the implementation of the browsable API.
|
||||
* Introduction of a new pagination API.
|
||||
* Better support for API versioning.
|
||||
|
||||
The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.
|
||||
|
||||
You can follow development on the GitHub site, where we use [milestones to indicate planning timescales](https://github.com/encode/django-rest-framework/milestones).
|
||||
|
||||
[kickstarter]: https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3
|
||||
[sponsors]: https://www.django-rest-framework.org/community/kickstarter-announcement/#sponsors
|
||||
[mixins.py]: https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py
|
||||
[django-localization]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#localization-how-to-create-language-files
|
|
@ -1,209 +0,0 @@
|
|||
# Django REST framework 3.1
|
||||
|
||||
The 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality.
|
||||
|
||||
Some highlights include:
|
||||
|
||||
* A super-smart cursor pagination scheme.
|
||||
* An improved pagination API, supporting header or in-body pagination styles.
|
||||
* Pagination controls rendering in the browsable API.
|
||||
* Better support for API versioning.
|
||||
* Built-in internationalization support.
|
||||
* Support for Django 1.8's `HStoreField` and `ArrayField`.
|
||||
|
||||
---
|
||||
|
||||
## Pagination
|
||||
|
||||
The pagination API has been improved, making it both easier to use, and more powerful.
|
||||
|
||||
A guide to the headline features follows. For full details, see [the pagination documentation][pagination].
|
||||
|
||||
Note that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes.
|
||||
|
||||
* The `PAGINATE_BY` settings key will continue to work but is now pending deprecation. The more obviously named `PAGE_SIZE` settings key should now be used instead.
|
||||
* The `PAGINATE_BY_PARAM`, `MAX_PAGINATE_BY` settings keys will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.
|
||||
* The `paginate_by`, `page_query_param`, `paginate_by_param` and `max_paginate_by` generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.
|
||||
* The `pagination_serializer_class` view attribute and `DEFAULT_PAGINATION_SERIALIZER_CLASS` settings key **are no longer valid**. The pagination API does not use serializers to determine the output format, and you'll need to instead override the `get_paginated_response` method on a pagination class in order to specify how the output format is controlled.
|
||||
|
||||
#### New pagination schemes.
|
||||
|
||||
Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default.
|
||||
|
||||
The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for [this blog post](https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api) on the subject.
|
||||
|
||||
#### Pagination controls in the browsable API.
|
||||
|
||||
Paginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API:
|
||||
|
||||

|
||||
|
||||
The cursor based pagination renders a more simple style of control:
|
||||
|
||||

|
||||
|
||||
#### Support for header-based pagination.
|
||||
|
||||
The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the `Link` or `Content-Range` headers.
|
||||
|
||||
For more information, see the [custom pagination styles](../api-guide/pagination/#custom-pagination-styles) documentation.
|
||||
|
||||
---
|
||||
|
||||
## Versioning
|
||||
|
||||
We've made it [easier to build versioned APIs][versioning]. Built-in schemes for versioning include both URL based and Accept header based variations.
|
||||
|
||||
When using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request.
|
||||
|
||||
For example, when using `NamespaceVersioning`, and the following hyperlinked serializer:
|
||||
|
||||
class AccountsSerializer(serializer.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = Accounts
|
||||
fields = ['account_name', 'users']
|
||||
|
||||
The output representation would match the version used on the incoming request. Like so:
|
||||
|
||||
GET http://example.org/v2/accounts/10 # Version 'v2'
|
||||
|
||||
{
|
||||
"account_name": "europa",
|
||||
"users": [
|
||||
"http://example.org/v2/users/12", # Version 'v2'
|
||||
"http://example.org/v2/users/54",
|
||||
"http://example.org/v2/users/87"
|
||||
]
|
||||
}
|
||||
|
||||
---
|
||||
|
||||
## Internationalization
|
||||
|
||||
REST framework now includes a built-in set of translations, and [supports internationalized error responses][internationalization]. This allows you to either change the default language, or to allow clients to specify the language via the `Accept-Language` header.
|
||||
|
||||
You can change the default language by using the standard Django `LANGUAGE_CODE` setting:
|
||||
|
||||
LANGUAGE_CODE = "es-es"
|
||||
|
||||
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE_CLASSES` setting:
|
||||
|
||||
MIDDLEWARE_CLASSES = [
|
||||
...
|
||||
'django.middleware.locale.LocaleMiddleware'
|
||||
]
|
||||
|
||||
When per-request internationalization is enabled, client requests will respect the `Accept-Language` header where possible. For example, let's make a request for an unsupported media type:
|
||||
|
||||
**Request**
|
||||
|
||||
GET /api/users HTTP/1.1
|
||||
Accept: application/xml
|
||||
Accept-Language: es-es
|
||||
Host: example.org
|
||||
|
||||
**Response**
|
||||
|
||||
HTTP/1.0 406 NOT ACCEPTABLE
|
||||
|
||||
{
|
||||
"detail": "No se ha podido satisfacer la solicitud de cabecera de Accept."
|
||||
}
|
||||
|
||||
Note that the structure of the error responses is still the same. We still have a `detail` key in the response. If needed you can modify this behavior too, by using a [custom exception handler][custom-exception-handler].
|
||||
|
||||
We include built-in translations both for standard exception cases, and for serializer validation errors.
|
||||
|
||||
The full list of supported languages can be found on our [Transifex project page](https://www.transifex.com/django-rest-framework-1/django-rest-framework/).
|
||||
|
||||
If you only wish to support a subset of the supported languages, use Django's standard `LANGUAGES` setting:
|
||||
|
||||
LANGUAGES = [
|
||||
('de', _('German')),
|
||||
('en', _('English')),
|
||||
]
|
||||
|
||||
For more details, see the [internationalization documentation][internationalization].
|
||||
|
||||
Many thanks to [Craig Blaszczyk](https://github.com/jakul) for helping push this through.
|
||||
|
||||
---
|
||||
|
||||
## New field types
|
||||
|
||||
Django 1.8's new `ArrayField`, `HStoreField` and `UUIDField` are now all fully supported.
|
||||
|
||||
This work also means that we now have both `serializers.DictField()`, and `serializers.ListField()` types, allowing you to express and validate a wider set of representations.
|
||||
|
||||
If you're building a new 1.8 project, then you should probably consider using `UUIDField` as the primary keys for all your models. This style will work automatically with hyperlinked serializers, returning URLs in the following style:
|
||||
|
||||
http://example.org/api/purchases/9b1a433f-e90d-4948-848b-300fdc26365d
|
||||
|
||||
---
|
||||
|
||||
## ModelSerializer API
|
||||
|
||||
The serializer redesign in 3.0 did not include any public API for modifying how ModelSerializer classes automatically generate a set of fields from a given mode class. We've now re-introduced an API for this, allowing you to create new ModelSerializer base classes that behave differently, such as using a different default style for relationships.
|
||||
|
||||
For more information, see the documentation on [customizing field mappings][customizing-field-mappings] for ModelSerializer classes.
|
||||
|
||||
---
|
||||
|
||||
## Moving packages out of core
|
||||
|
||||
We've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to `pip install` the new packages, and change any import paths.
|
||||
|
||||
We're making this change in order to help distribute the maintenance workload, and keep better focus of the core essentials of the framework.
|
||||
|
||||
The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained [Django OAuth toolkit](https://github.com/jazzband/django-oauth-toolkit) has now been promoted as our recommended option for integrating OAuth support.
|
||||
|
||||
The following packages are now moved out of core and should be separately installed:
|
||||
|
||||
* OAuth - [djangorestframework-oauth](https://jpadilla.github.io/django-rest-framework-oauth/)
|
||||
* XML - [djangorestframework-xml](https://jpadilla.github.io/django-rest-framework-xml/)
|
||||
* YAML - [djangorestframework-yaml](https://jpadilla.github.io/django-rest-framework-yaml/)
|
||||
* JSONP - [djangorestframework-jsonp](https://jpadilla.github.io/django-rest-framework-jsonp/)
|
||||
|
||||
It's worth reiterating that this change in policy shouldn't mean any work in your codebase other than adding a new requirement and modifying some import paths. For example to install XML rendering, you would now do:
|
||||
|
||||
pip install djangorestframework-xml
|
||||
|
||||
And modify your settings, like so:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
'rest_framework_xml.renderers.XMLRenderer'
|
||||
]
|
||||
}
|
||||
|
||||
Thanks go to the latest member of our maintenance team, [José Padilla](https://github.com/jpadilla/), for handling this work and taking on ownership of these packages.
|
||||
|
||||
---
|
||||
|
||||
## Deprecations
|
||||
|
||||
The `request.DATA`, `request.FILES` and `request.QUERY_PARAMS` attributes move from pending deprecation, to deprecated. Use `request.data` and `request.query_params` instead, as discussed in the 3.0 release notes.
|
||||
|
||||
The ModelSerializer Meta options for `write_only_fields`, `view_name` and `lookup_field` are also moved from pending deprecation, to deprecated. Use `extra_kwargs` instead, as discussed in the 3.0 release notes.
|
||||
|
||||
All these attributes and options will still work in 3.1, but their usage will raise a warning. They will be fully removed in 3.2.
|
||||
|
||||
---
|
||||
|
||||
## What's next?
|
||||
|
||||
The next focus will be on HTML renderings of API output and will include:
|
||||
|
||||
* HTML form rendering of serializers.
|
||||
* Filtering controls built-in to the browsable API.
|
||||
* An alternative admin-style interface.
|
||||
|
||||
This will either be made as a single 3.2 release, or split across two separate releases, with the HTML forms and filter controls coming in 3.2, and the admin-style interface coming in a 3.3 release.
|
||||
|
||||
[custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling
|
||||
[pagination]: ../api-guide/pagination.md
|
||||
[versioning]: ../api-guide/versioning.md
|
||||
[internationalization]: ../topics/internationalization.md
|
||||
[customizing-field-mappings]: ../api-guide/serializers.md#customizing-field-mappings
|
|
@ -1,148 +0,0 @@
|
|||
<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.10
|
||||
|
||||
The 3.10 release drops support for Python 2.
|
||||
|
||||
* Our supported Python versions are now: 3.5, 3.6, and 3.7.
|
||||
* Our supported Django versions are now: 1.11, 2.0, 2.1, and 2.2.
|
||||
|
||||
## OpenAPI Schema Generation
|
||||
|
||||
Since we first introduced schema support in Django REST Framework 3.5, OpenAPI has emerged as the widely adopted standard for modeling Web APIs.
|
||||
|
||||
This release begins the deprecation process for the CoreAPI based schema generation, and introduces OpenAPI schema generation in its place.
|
||||
|
||||
---
|
||||
|
||||
## Continuing to use CoreAPI
|
||||
|
||||
If you're currently using the CoreAPI schemas, you'll need to make sure to
|
||||
update your REST framework settings to include `DEFAULT_SCHEMA_CLASS` explicitly.
|
||||
|
||||
**settings.py**:
|
||||
|
||||
```python
|
||||
REST_FRAMEWORK = {
|
||||
...: ...,
|
||||
"DEFAULT_SCHEMA_CLASS": "rest_framework.schemas.coreapi.AutoSchema",
|
||||
}
|
||||
```
|
||||
|
||||
You'll still be able to keep using CoreAPI schemas, API docs, and client for the
|
||||
foreseeable future. We'll aim to ensure that the CoreAPI schema generator remains
|
||||
available as a third party package, even once it has eventually been removed
|
||||
from REST framework, scheduled for version 3.12.
|
||||
|
||||
We have removed the old documentation for the CoreAPI based schema generation.
|
||||
You may view the [Legacy CoreAPI documentation here][legacy-core-api-docs].
|
||||
|
||||
----
|
||||
|
||||
## OpenAPI Quickstart
|
||||
|
||||
You can generate a static OpenAPI schema, using the `generateschema` management
|
||||
command.
|
||||
|
||||
Alternately, to have the project serve an API schema, use the `get_schema_view()`
|
||||
shortcut.
|
||||
|
||||
In your `urls.py`:
|
||||
|
||||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
|
||||
urlpatterns = [
|
||||
# ...
|
||||
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
|
||||
# * `title` and `description` parameters are passed to `SchemaGenerator`.
|
||||
# * Provide view name for use with `reverse()`.
|
||||
path(
|
||||
"openapi",
|
||||
get_schema_view(title="Your Project", description="API for all things …"),
|
||||
name="openapi-schema",
|
||||
),
|
||||
# ...
|
||||
]
|
||||
```
|
||||
|
||||
### Customization
|
||||
|
||||
For customizations that you want to apply across the entire API, you can subclass `rest_framework.schemas.openapi.SchemaGenerator` and provide it as an argument
|
||||
to the `generateschema` command or `get_schema_view()` helper function.
|
||||
|
||||
For specific per-view customizations, you can subclass `AutoSchema`,
|
||||
making sure to set `schema = <YourCustomClass>` on the view.
|
||||
|
||||
For more details, see the [API Schema documentation](../api-guide/schemas.md).
|
||||
|
||||
### API Documentation
|
||||
|
||||
There are some great third party options for documenting your API, based on the
|
||||
OpenAPI schema.
|
||||
|
||||
See the [Documenting you API](../topics/documenting-your-api.md) section for more details.
|
||||
|
||||
---
|
||||
|
||||
## Feature Roadmap
|
||||
|
||||
Given that our OpenAPI schema generation is a new feature, it's likely that there
|
||||
will still be some iterative improvements for us to make. There will be two
|
||||
main cases here:
|
||||
|
||||
* Expanding the supported range of OpenAPI schemas that are generated by default.
|
||||
* Improving the ability for developers to customize the output.
|
||||
|
||||
We'll aim to bring the first type of change quickly in point releases. For the
|
||||
second kind we'd like to adopt a slower approach, to make sure we keep the API
|
||||
simple, and as widely applicable as possible, before we bring in API changes.
|
||||
|
||||
It's also possible that we'll end up implementing API documentation and API client
|
||||
tooling that are driven by the OpenAPI schema. The `apistar` project has a
|
||||
significant amount of work towards this. However, if we do so, we'll plan
|
||||
on keeping any tooling outside of the core framework.
|
||||
|
||||
---
|
||||
|
||||
## Funding
|
||||
|
||||
REST framework is a *collaboratively funded project*. If you use
|
||||
REST framework commercially we strongly encourage you to invest in its
|
||||
continued development by **[signing up for a paid plan][funding]**.
|
||||
|
||||
*Every single sign-up helps us make REST framework long-term financially sustainable.*
|
||||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" 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://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
|
||||
<li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless-plus-text.png)">Kloudless</a></li>
|
||||
<li><a href="https://lightsonsoftware.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/lightson-dark.png)">Lights On Software</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=banner&utm_campaign=drf), [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), and [Lights On Software](https://lightsonsoftware.com).*
|
||||
|
||||
[legacy-core-api-docs]:https://github.com/encode/django-rest-framework/blob/3.14.0/docs/coreapi/index.md
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
|
@ -1,118 +0,0 @@
|
|||
<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.11
|
||||
|
||||
The 3.11 release adds support for Django 3.0.
|
||||
|
||||
* Our supported Python versions are now: 3.5, 3.6, 3.7, and 3.8.
|
||||
* Our supported Django versions are now: 1.11, 2.0, 2.1, 2.2, and 3.0.
|
||||
|
||||
This release will be the last to support Python 3.5 or Django 1.11.
|
||||
|
||||
## OpenAPI Schema Generation Improvements
|
||||
|
||||
The OpenAPI schema generation continues to mature. Some highlights in 3.11
|
||||
include:
|
||||
|
||||
* Automatic mapping of Django REST Framework renderers and parsers into OpenAPI
|
||||
request and response media-types.
|
||||
* Improved mapping JSON schema mapping types, for example in HStoreFields, and
|
||||
with large integer values.
|
||||
* Porting of the old CoreAPI parsing of docstrings to form OpenAPI operation
|
||||
descriptions.
|
||||
|
||||
In this example view operation descriptions for the `get` and `post` methods will
|
||||
be extracted from the class docstring:
|
||||
|
||||
```python
|
||||
class DocStringExampleListView(APIView):
|
||||
"""
|
||||
get: A description of my GET operation.
|
||||
post: A description of my POST operation.
|
||||
"""
|
||||
|
||||
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
...
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
...
|
||||
```
|
||||
|
||||
## Validator / Default Context
|
||||
|
||||
In some circumstances a Validator class or a Default class may need to access the serializer field with which it is called, or the `.context` with which the serializer was instantiated. In particular:
|
||||
|
||||
* Uniqueness validators need to be able to determine the name of the field to which they are applied, in order to run an appropriate database query.
|
||||
* The `CurrentUserDefault` needs to be able to determine the context with which the serializer was instantiated, in order to return the current user instance.
|
||||
|
||||
Our previous approach to this was that implementations could include a `set_context` method, which would be called prior to validation. However this approach had issues with potential race conditions. We have now move this approach into a pending deprecation state. It will continue to function, but will be escalated to a deprecated state in 3.12, and removed entirely in 3.13.
|
||||
|
||||
Instead, validators or defaults which require the serializer context, should include a `requires_context = True` attribute on the class.
|
||||
|
||||
The `__call__` method should then include an additional `serializer_field` argument.
|
||||
|
||||
Validator implementations will look like this:
|
||||
|
||||
```python
|
||||
class CustomValidator:
|
||||
requires_context = True
|
||||
|
||||
def __call__(self, value, serializer_field):
|
||||
...
|
||||
```
|
||||
|
||||
Default implementations will look like this:
|
||||
|
||||
```python
|
||||
class CustomDefault:
|
||||
requires_context = True
|
||||
|
||||
def __call__(self, serializer_field):
|
||||
...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Funding
|
||||
|
||||
REST framework is a *collaboratively funded project*. If you use
|
||||
REST framework commercially we strongly encourage you to invest in its
|
||||
continued development by **[signing up for a paid plan][funding]**.
|
||||
|
||||
*Every single sign-up helps us make REST framework long-term financially sustainable.*
|
||||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" 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://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
|
||||
<li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless-plus-text.png)">Kloudless</a></li>
|
||||
<li><a href="https://lightsonsoftware.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/lightson-dark.png)">Lights On Software</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>
|
||||
</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=banner&utm_campaign=drf), [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), and [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship).*
|
||||
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
|
@ -1,181 +0,0 @@
|
|||
<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.12
|
||||
|
||||
REST framework 3.12 brings a handful of refinements to the OpenAPI schema
|
||||
generation, plus support for Django's new database-agnostic `JSONField`,
|
||||
and some improvements to the `SearchFilter` class.
|
||||
|
||||
## Grouping operations with tags.
|
||||
|
||||
Open API schemas will now automatically include tags, based on the first element
|
||||
in the URL path.
|
||||
|
||||
For example...
|
||||
|
||||
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']`
|
||||
|
||||
The tags used for a particular view may also be overridden...
|
||||
|
||||
```python
|
||||
class MyOrders(APIView):
|
||||
schema = AutoSchema(tags=["users", "orders"])
|
||||
...
|
||||
```
|
||||
|
||||
See [the schema documentation](https://www.django-rest-framework.org/api-guide/schemas/#grouping-operations-with-tags) for more information.
|
||||
|
||||
## Customizing the operation ID.
|
||||
|
||||
REST framework automatically determines operation IDs to use in OpenAPI
|
||||
schemas. The latest version provides more control for overriding the behaviour
|
||||
used to generate the operation IDs.
|
||||
|
||||
See [the schema documentation](https://www.django-rest-framework.org/api-guide/schemas/#operationid) for more information.
|
||||
|
||||
## Support for OpenAPI components.
|
||||
|
||||
In order to output more graceful OpenAPI schemes, REST framework 3.12 now
|
||||
defines components in the schema, and then references them inside request
|
||||
and response objects. This is in contrast with the previous approach, which
|
||||
fully expanded the request and response bodies for each operation.
|
||||
|
||||
The names used for a component default to using the serializer class name, [but
|
||||
may be overridden if needed](https://www.django-rest-framework.org/api-guide/schemas/#components
|
||||
)...
|
||||
|
||||
```python
|
||||
class MyOrders(APIView):
|
||||
schema = AutoSchema(component_name="OrderDetails")
|
||||
```
|
||||
|
||||
## More Public API
|
||||
|
||||
Many methods on the `AutoSchema` class have now been promoted to public API,
|
||||
allowing you to more fully customize the schema generation. The following methods
|
||||
are now available for overriding...
|
||||
|
||||
* `get_path_parameters`
|
||||
* `get_pagination_parameters`
|
||||
* `get_filter_parameters`
|
||||
* `get_request_body`
|
||||
* `get_responses`
|
||||
* `get_serializer`
|
||||
* `get_paginator`
|
||||
* `map_serializer`
|
||||
* `map_field`
|
||||
* `map_choice_field`
|
||||
* `map_field_validators`
|
||||
* `allows_filters`.
|
||||
|
||||
See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#per-view-customization)
|
||||
for details on using custom `AutoSchema` subclasses.
|
||||
|
||||
## Support for JSONField.
|
||||
|
||||
Django 3.1 deprecated the existing `django.contrib.postgres.fields.JSONField`
|
||||
in favour of a new database-agnositic `JSONField`.
|
||||
|
||||
REST framework 3.12 now supports this new model field, and `ModelSerializer`
|
||||
classes will correctly map the model field.
|
||||
|
||||
## SearchFilter improvements
|
||||
|
||||
There are a couple of significant improvements to the `SearchFilter` class.
|
||||
|
||||
### Nested searches against JSONField and HStoreField
|
||||
|
||||
The class now supports nested search within `JSONField` and `HStoreField`, using
|
||||
the double underscore notation for traversing which element of the field the
|
||||
search should apply to.
|
||||
|
||||
```python
|
||||
class SitesSearchView(generics.ListAPIView):
|
||||
"""
|
||||
An API view to return a list of archaeological sites, optionally filtered
|
||||
by a search against the site name or location. (Location searches are
|
||||
matched against the region and country names.)
|
||||
"""
|
||||
|
||||
queryset = Sites.objects.all()
|
||||
serializer_class = SitesSerializer
|
||||
filter_backends = [filters.SearchFilter]
|
||||
search_fields = ["site_name", "location__region", "location__country"]
|
||||
```
|
||||
|
||||
### Searches against annotate fields
|
||||
|
||||
Django allows querysets to create additional virtual fields, using the `.annotate`
|
||||
method. We now support searching against annotate fields.
|
||||
|
||||
```python
|
||||
class PublisherSearchView(generics.ListAPIView):
|
||||
"""
|
||||
Search for publishers, optionally filtering the search against the average
|
||||
rating of all their books.
|
||||
"""
|
||||
|
||||
queryset = Publisher.objects.annotate(avg_rating=Avg("book__rating"))
|
||||
serializer_class = PublisherSerializer
|
||||
filter_backends = [filters.SearchFilter]
|
||||
search_fields = ["avg_rating"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Deprecations
|
||||
|
||||
### `serializers.NullBooleanField`
|
||||
|
||||
`serializers.NullBooleanField` is now pending deprecation, and will be removed in 3.14.
|
||||
|
||||
Instead use `serializers.BooleanField` field and set `allow_null=True` which does the same thing.
|
||||
|
||||
---
|
||||
|
||||
## Funding
|
||||
|
||||
REST framework is a *collaboratively funded project*. If you use
|
||||
REST framework commercially we strongly encourage you to invest in its
|
||||
continued development by **[signing up for a paid plan][funding]**.
|
||||
|
||||
*Every single sign-up helps us make REST framework long-term financially sustainable.*
|
||||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" 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://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
|
||||
<li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless-plus-text.png)">Kloudless</a></li>
|
||||
<li><a href="https://lightsonsoftware.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/lightson-dark.png)">Lights On Software</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>
|
||||
</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=banner&utm_campaign=drf), [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), and [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship).*
|
||||
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
|
@ -1,55 +0,0 @@
|
|||
<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.
|
|
@ -1,72 +0,0 @@
|
|||
<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_exception` 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_exception` 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.
|
||||
|
||||
---
|
||||
|
||||
## Deprecations
|
||||
|
||||
### `serializers.NullBooleanField`
|
||||
|
||||
`serializers.NullBooleanField` was moved to pending deprecation in 3.12, and deprecated in 3.13. It has now been removed from the core framework.
|
||||
|
||||
Instead use `serializers.BooleanField` field and set `allow_null=True` which does the same thing.
|
|
@ -1,50 +0,0 @@
|
|||
<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.15
|
||||
|
||||
At the Internet, on March 15th, 2024, with 176 commits by 138 authors, we are happy to announce the release of Django REST framework 3.15.
|
||||
|
||||
## Django 5.0 and Python 3.12 support
|
||||
|
||||
The latest release now fully supports Django 5.0 and Python 3.12.
|
||||
|
||||
The current minimum versions of Django still is 3.0 and Python 3.6.
|
||||
|
||||
## Primary Support of UniqueConstraint
|
||||
|
||||
`ModelSerializer` generates validators for [UniqueConstraint](https://docs.djangoproject.com/en/4.0/ref/models/constraints/#uniqueconstraint) (both UniqueValidator and UniqueTogetherValidator)
|
||||
|
||||
## SimpleRouter non-regex matching support
|
||||
|
||||
By default the URLs created by `SimpleRouter` use regular expressions. This behavior can be modified by setting the `use_regex_path` argument to `False` when instantiating the router.
|
||||
|
||||
## ZoneInfo as the primary source of timezone data
|
||||
|
||||
Dependency on pytz has been removed and deprecation warnings have been added, Django will provide ZoneInfo instances as long as USE_DEPRECATED_PYTZ is not enabled. More info on the migration can be found [in this guide](https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html).
|
||||
|
||||
## Align `SearchFilter` behaviour to `django.contrib.admin` search
|
||||
|
||||
Searches now may contain _quoted phrases_ with spaces, each phrase is considered as a single search term, and it will raise a validation error if any null-character is provided in search. See the [Filtering API guide](../api-guide/filtering.md) for more information.
|
||||
|
||||
## Other fixes and improvements
|
||||
|
||||
There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behaviour.
|
||||
|
||||
See the [release notes](release-notes.md) page for a complete listing.
|
|
@ -1,42 +0,0 @@
|
|||
<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.16
|
||||
|
||||
At the Internet, on March 28th, 2025, we are happy to announce the release of Django REST framework 3.16.
|
||||
|
||||
## Updated Django and Python support
|
||||
|
||||
The latest release now fully supports Django 5.1 and the upcoming 5.2 LTS as well as Python 3.13.
|
||||
|
||||
The current minimum versions of Django is now 4.2 and Python 3.9.
|
||||
|
||||
## Django LoginRequiredMiddleware
|
||||
|
||||
The new `LoginRequiredMiddleware` introduced by Django 5.1 can now be used alongside Django REST Framework, however it is not honored for API views as an equivalent behaviour can be configured via `DEFAULT_AUTHENTICATION_CLASSES`. See [our dedicated section](../api-guide/authentication.md#django-51-loginrequiredmiddleware) in the docs for more information.
|
||||
|
||||
## Improved support for UniqueConstraint
|
||||
|
||||
The generation of validators for [UniqueConstraint](https://docs.djangoproject.com/en/stable/ref/models/constraints/#uniqueconstraint) has been improved to support better nullable fields and constraints with conditions.
|
||||
|
||||
## Other fixes and improvements
|
||||
|
||||
There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behaviour.
|
||||
|
||||
See the [release notes](release-notes.md) page for a complete listing.
|
|
@ -1,113 +0,0 @@
|
|||
# Django REST framework 3.2
|
||||
|
||||
The 3.2 release is the first version to include an admin interface for the browsable API.
|
||||
|
||||

|
||||
|
||||
This interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing `BrowsableAPIRenderer`, or used together with it, allowing you to switch between the two styles as required.
|
||||
|
||||
We've also fixed a huge number of issues, and made numerous cleanups and improvements.
|
||||
|
||||
Over the course of the 3.1.x series we've [resolved nearly 600 tickets](https://github.com/encode/django-rest-framework/issues?utf8=%E2%9C%93&q=closed%3A%3E2015-03-05) on our GitHub issue tracker. This means we're currently running at a rate of **closing around 100 issues or pull requests per month**.
|
||||
|
||||
None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking [a look through our sponsors](https://www.django-rest-framework.org/community/kickstarter-announcement/#sponsors) and finding out who's hiring.
|
||||
|
||||
## AdminRenderer
|
||||
|
||||
To include `AdminRenderer` simply add it to your settings:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.AdminRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer'
|
||||
],
|
||||
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
|
||||
'PAGE_SIZE': 100
|
||||
}
|
||||
|
||||
There are some limitations to the `AdminRenderer`, in particular it is not yet able to handle list or dictionary inputs, as we do not have any HTML form fields that support those.
|
||||
|
||||
Also note that this is an initial release and we do not yet have a public API for modifying the behavior or documentation on overriding the templates.
|
||||
|
||||
The idea is to get this released to users early, so we can start getting feedback and release a more fully featured version in 3.3.
|
||||
|
||||
## Supported versions
|
||||
|
||||
This release drops support for Django 1.4.
|
||||
|
||||
Our supported Django versions are now 1.5.6+, 1.6.3+, 1.7 and 1.8.
|
||||
|
||||
## Deprecations
|
||||
|
||||
There are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy.
|
||||
|
||||
* `request.DATA` was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of `request.data` instead.
|
||||
* `request.QUERY_PARAMS` was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of `request.query_params` instead.
|
||||
* The following `ModelSerializer.Meta` options have now been removed: `write_only_fields`, `view_name`, `lookup_field`. Use the more general `extra_kwargs` option instead.
|
||||
|
||||
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly in 'pending deprecation', and has now escalated to 'deprecated'. They will continue to function but will raise errors.
|
||||
|
||||
* `view.paginate_by` - Use `paginator.page_size` instead.
|
||||
* `view.page_query_param` - Use `paginator.page_query_param` instead.
|
||||
* `view.paginate_by_param` - Use `paginator.page_size_query_param` instead.
|
||||
* `view.max_paginate_by` - Use `paginator.max_page_size` instead.
|
||||
* `settings.PAGINATE_BY` - Use `paginator.page_size` instead.
|
||||
* `settings.PAGINATE_BY_PARAM` - Use `paginator.page_size_query_param` instead.
|
||||
* `settings.MAX_PAGINATE_BY` - Use `paginator.max_page_size` instead.
|
||||
|
||||
## Modifications to list behaviors
|
||||
|
||||
There are a couple of bug fixes that are worth calling out as they introduce differing behavior.
|
||||
|
||||
These are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project.
|
||||
|
||||
### 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.
|
||||
|
||||
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.
|
||||
|
||||
Previously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has `blank=True` set.
|
||||
|
||||
Here's what the mapping looks like in practice:
|
||||
|
||||
* `models.ManyToManyField()` → `serializers.PrimaryKeyRelatedField(many=True, allow_empty=False)`
|
||||
* `models.ManyToManyField(blank=True)` → `serializers.PrimaryKeyRelatedField(many=True)`
|
||||
|
||||
The upshot is this: If you have many to many fields in your models, then make sure you've included the argument `blank=True` if you want to allow empty inputs in the equivalent `ModelSerializer` fields.
|
||||
|
||||
### List fields and allow_null
|
||||
|
||||
When using `allow_null` with `ListField` or a nested `many=True` serializer the previous behavior was to allow `null` values as items in the list. The behavior is now to allow `null` values instead of the list.
|
||||
|
||||
For example, take the following field:
|
||||
|
||||
NestedSerializer(many=True, allow_null=True)
|
||||
|
||||
Previously the validation behavior would be:
|
||||
|
||||
* `[{…}, null, {…}]` is **valid**.
|
||||
* `null` is **invalid**.
|
||||
|
||||
Our validation behavior as of 3.2.0 is now:
|
||||
|
||||
* `[{…}, null, {…}]` is **invalid**.
|
||||
* `null` is **valid**.
|
||||
|
||||
If you want to allow `null` child items, you'll need to instead specify `allow_null` on the child class, using an explicit `ListField` instead of `many=True`. For example:
|
||||
|
||||
ListField(child=NestedSerializer(allow_null=True))
|
||||
|
||||
## What's next?
|
||||
|
||||
The 3.3 release is currently planned for the start of October, and will be the last Kickstarter-funded release.
|
||||
|
||||
This release is planned to include:
|
||||
|
||||
* Search and filtering controls in the browsable API and admin interface.
|
||||
* Improvements and public API for the admin interface.
|
||||
* Improvements and public API for our templated HTML forms and fields.
|
||||
* Nested object and list support in HTML forms.
|
||||
|
||||
Thanks once again to all our sponsors and supporters.
|
|
@ -1,60 +0,0 @@
|
|||
# Django REST framework 3.3
|
||||
|
||||
The 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding **thank you** to all our wonderful sponsors and supporters.
|
||||
|
||||
The amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned & refined large parts of the project.
|
||||
|
||||
In order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow [@_tomchristie](https://twitter.com/_tomchristie) to keep up to date with these announcements, and be among the first set of sign ups.
|
||||
|
||||
We strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished & professional product.
|
||||
|
||||
---
|
||||
|
||||
## Release notes
|
||||
|
||||
Significant new functionality in the 3.3 release includes:
|
||||
|
||||
* Filters presented as HTML controls in the browsable API.
|
||||
* A [forms API][forms-api], allowing serializers to be rendered as HTML forms.
|
||||
* Django 1.9 support.
|
||||
* A [`JSONField` serializer field][jsonfield], corresponding to Django 1.9's Postgres `JSONField` model field.
|
||||
* Browsable API support [via AJAX][ajax-form], rather than server side request overloading.
|
||||
|
||||

|
||||
|
||||
*Example of the new filter controls*
|
||||
|
||||
---
|
||||
|
||||
## Supported versions
|
||||
|
||||
This release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required.
|
||||
|
||||
This brings our supported versions into line with Django's [currently supported versions][django-supported-versions]
|
||||
|
||||
## Deprecations
|
||||
|
||||
The AJAX based support for the browsable API means that there are a number of internal cleanups in the `request` class. For the vast majority of developers this should largely remain transparent:
|
||||
|
||||
* 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 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.
|
||||
|
||||
* `view.paginate_by` - Use `paginator.page_size` instead.
|
||||
* `view.page_query_param` - Use `paginator.page_query_param` instead.
|
||||
* `view.paginate_by_param` - Use `paginator.page_size_query_param` instead.
|
||||
* `view.max_paginate_by` - Use `paginator.max_page_size` instead.
|
||||
* `settings.PAGINATE_BY` - Use `paginator.page_size` instead.
|
||||
* `settings.PAGINATE_BY_PARAM` - Use `paginator.page_size_query_param` instead.
|
||||
* `settings.MAX_PAGINATE_BY` - Use `paginator.max_page_size` instead.
|
||||
|
||||
The `ModelSerializer` and `HyperlinkedModelSerializer` classes should now include either a `fields` or `exclude` option, although the `fields = '__all__'` shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings `ModelSerializer` more closely in line with Django's `ModelForm` behavior.
|
||||
|
||||
[forms-api]: ../topics/html-and-forms.md
|
||||
[ajax-form]: https://github.com/encode/ajax-form
|
||||
[jsonfield]: ../api-guide/fields#jsonfield
|
||||
[accept-headers]: ../topics/browser-enhancements.md#url-based-accept-headers
|
||||
[method-override]: ../topics/browser-enhancements.md#http-header-based-method-overriding
|
||||
[django-supported-versions]: https://www.djangoproject.com/download/#supported-versions
|
|
@ -1,194 +0,0 @@
|
|||
<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.4
|
||||
|
||||
The 3.4 release is the first in a planned series that will be addressing schema
|
||||
generation, hypermedia support, API clients, and finally realtime support.
|
||||
|
||||
---
|
||||
|
||||
## Funding
|
||||
|
||||
The 3.4 release has been made possible a recent [Mozilla grant][moss], and by our
|
||||
[collaborative funding model][funding]. If you use REST framework commercially, and would
|
||||
like to see this work continue, we strongly encourage you to invest in its
|
||||
continued development by **[signing up for a paid plan][funding]**.
|
||||
|
||||
The initial aim is to provide a single full-time position on REST framework.
|
||||
Right now we're over 60% of the way towards achieving that.
|
||||
*Every single sign-up makes a significant impact.*
|
||||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
||||
<li><a href="https://sentry.io/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=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
</ul>
|
||||
<div style="clear: both; padding-bottom: 20px;"></div>
|
||||
|
||||
*Many thanks to all our [awesome sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), and [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf).*
|
||||
|
||||
---
|
||||
|
||||
## Schemas & client libraries
|
||||
|
||||
REST framework 3.4 brings built-in support for generating API schemas.
|
||||
|
||||
We provide this support by using [Core API][core-api], a Document Object Model
|
||||
for describing APIs.
|
||||
|
||||
Because Core API represents the API schema in an format-independent
|
||||
manner, we're able to render the Core API `Document` object into many different
|
||||
schema formats, by allowing the renderer class to determine how the internal
|
||||
representation maps onto the external schema format.
|
||||
|
||||
This approach should also open the door to a range of auto-generated API
|
||||
documentation options in the future, by rendering the `Document` object into
|
||||
HTML documentation pages.
|
||||
|
||||
Alongside the built-in schema support, we're also now providing the following:
|
||||
|
||||
* A [command line tool][command-line-client] for interacting with APIs.
|
||||
* A [Python client library][client-library] for interacting with APIs.
|
||||
|
||||
These API clients are dynamically driven, and able to interact with any API
|
||||
that exposes a supported schema format.
|
||||
|
||||
Dynamically driven clients allow you to interact with an API at an application
|
||||
layer interface, rather than a network layer interface, while still providing
|
||||
the benefits of RESTful Web API design.
|
||||
|
||||
We're expecting to expand the range of languages that we provide client libraries
|
||||
for over the coming months.
|
||||
|
||||
Further work on maturing the API schema support is also planned, including
|
||||
documentation on supporting file upload and download, and improved support for
|
||||
documentation generation and parameter annotation.
|
||||
|
||||
---
|
||||
|
||||
Current support for schema formats is as follows:
|
||||
|
||||
Name | Support | PyPI package
|
||||
---------------------------------|-------------------------------------|--------------------------------
|
||||
[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.
|
||||
[API Blueprint][api-blueprint] | Not yet available. | Not yet available.
|
||||
|
||||
---
|
||||
|
||||
You can read more about any of this new functionality in the following:
|
||||
|
||||
* New tutorial section on [schemas & client libraries][tut-7].
|
||||
* Documentation page on [schema generation][schema-generation].
|
||||
* Topic page on [API clients][api-clients].
|
||||
|
||||
It is also worth noting that Marc Gibbons is currently working towards a 2.0 release of
|
||||
the popular Django REST Swagger package, which will tie in with our new built-in support.
|
||||
|
||||
---
|
||||
|
||||
## Supported versions
|
||||
|
||||
The 3.4.0 release adds support for Django 1.10.
|
||||
|
||||
The following versions of Python and Django are now supported:
|
||||
|
||||
* Django versions 1.8, 1.9, and 1.10.
|
||||
* Python versions 2.7, 3.2(\*), 3.3(\*), 3.4, 3.5.
|
||||
|
||||
(\*) Note that Python 3.2 and 3.3 are not supported from Django 1.9 onwards.
|
||||
|
||||
---
|
||||
|
||||
## Deprecations and changes
|
||||
|
||||
The 3.4 release includes very limited deprecation or behavioral changes, and
|
||||
should present a straightforward upgrade.
|
||||
|
||||
### Use fields or exclude on serializer classes.
|
||||
|
||||
The following change in 3.3.0 is now escalated from "pending deprecation" to
|
||||
"deprecated". Its usage will continue to function but will raise warnings:
|
||||
|
||||
`ModelSerializer` and `HyperlinkedModelSerializer` should include either a `fields`
|
||||
option, or an `exclude` option. The `fields = '__all__'` shortcut may be used
|
||||
to explicitly include all fields.
|
||||
|
||||
### Microsecond precision when returning time or datetime.
|
||||
|
||||
Using the default JSON renderer and directly returning a `datetime` or `time`
|
||||
instance will now render with microsecond precision (6 digits), rather than
|
||||
millisecond precision (3 digits). This makes the output format consistent with the
|
||||
default string output of `serializers.DateTimeField` and `serializers.TimeField`.
|
||||
|
||||
This change *does not affect the default behavior when using serializers*,
|
||||
which is to serialize `datetime` and `time` instances into strings with
|
||||
microsecond precision.
|
||||
|
||||
The serializer behavior can be modified if needed, using the `DATETIME_FORMAT`
|
||||
and `TIME_FORMAT` settings.
|
||||
|
||||
The renderer behavior can be modified by setting a custom `encoder_class`
|
||||
attribute on a `JSONRenderer` subclass.
|
||||
|
||||
### Relational choices no longer displayed in OPTIONS requests.
|
||||
|
||||
Making an `OPTIONS` request to views that have a serializer choice field
|
||||
will result in a list of the available choices being returned in the response.
|
||||
|
||||
In cases where there is a relational field, the previous behavior would be
|
||||
to return a list of available instances to choose from for that relational field.
|
||||
|
||||
In order to minimise exposed information the behavior now is to *not* return
|
||||
choices information for relational fields.
|
||||
|
||||
If you want to override this new behavior you'll need to [implement a custom
|
||||
metadata class][metadata].
|
||||
|
||||
See [issue #3751][gh3751] for more information on this behavioral change.
|
||||
|
||||
---
|
||||
|
||||
## Other improvements
|
||||
|
||||
This release includes further work from a huge number of [pull requests and issues][milestone].
|
||||
|
||||
Many thanks to all our contributors who've been involved in the release, either through raising issues, giving feedback, improving the documentation, or suggesting and implementing code changes.
|
||||
|
||||
The full set of itemized release notes [are available here][release-notes].
|
||||
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[moss]: mozilla-grant.md
|
||||
[funding]: funding.md
|
||||
[core-api]: https://www.coreapi.org/
|
||||
[command-line-client]: api-clients#command-line-client
|
||||
[client-library]: api-clients#python-client-library
|
||||
[core-json]: https://www.coreapi.org/specification/encoding/#core-json-encoding
|
||||
[swagger]: https://openapis.org/specification
|
||||
[hyperschema]: https://json-schema.org/latest/json-schema-hypermedia.html
|
||||
[api-blueprint]: https://apiblueprint.org/
|
||||
[tut-7]: ../tutorial/7-schemas-and-client-libraries/
|
||||
[schema-generation]: ../api-guide/schemas/
|
||||
[api-clients]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md
|
||||
[milestone]: https://github.com/encode/django-rest-framework/milestone/35
|
||||
[release-notes]: release-notes#34
|
||||
[metadata]: ../api-guide/metadata/#custom-metadata-classes
|
||||
[gh3751]: https://github.com/encode/django-rest-framework/issues/3751
|
|
@ -1,262 +0,0 @@
|
|||
<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.5
|
||||
|
||||
The 3.5 release is the second in a planned series that is addressing schema
|
||||
generation, hypermedia support, API client libraries, and finally realtime support.
|
||||
|
||||
---
|
||||
|
||||
## Funding
|
||||
|
||||
The 3.5 release would not have been possible without our [collaborative funding model][funding].
|
||||
If you use REST framework commercially and would like to see this work continue,
|
||||
we strongly encourage you to invest in its continued development by
|
||||
**[signing up for a paid plan][funding]**.
|
||||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
||||
<li><a href="https://sentry.io/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=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
<li><a href="https://www.machinalis.com/#services" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</a></li>
|
||||
</ul>
|
||||
<div style="clear: both; padding-bottom: 20px;"></div>
|
||||
|
||||
*Many thanks to all our [sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), and [Machinalis](https://www.machinalis.com/#services).*
|
||||
|
||||
---
|
||||
|
||||
## Improved schema generation
|
||||
|
||||
Docstrings on views are now pulled through into schema definitions, allowing
|
||||
you to [use the schema definition to document your API][schema-docs].
|
||||
|
||||
There is now also a shortcut function, `get_schema_view()`, which makes it easier to
|
||||
[adding schema views][schema-view] to your API.
|
||||
|
||||
For example, to include a swagger schema to your API, you would do the following:
|
||||
|
||||
* Run `pip install django-rest-swagger`.
|
||||
|
||||
* Add `'rest_framework_swagger'` to your `INSTALLED_APPS` setting.
|
||||
|
||||
* Include the schema view in your URL conf:
|
||||
|
||||
```py
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title="Example API", renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]
|
||||
)
|
||||
|
||||
urlpatterns = [path("swagger/", schema_view), ...]
|
||||
```
|
||||
|
||||
There have been a large number of fixes to the schema generation. These should
|
||||
resolve issues for anyone using the latest version of the `django-rest-swagger`
|
||||
package.
|
||||
|
||||
Some of these changes do affect the resulting schema structure,
|
||||
so if you're already using schema generation you should make sure to review
|
||||
[the deprecation notes](#deprecations), particularly if you're currently using
|
||||
a dynamic client library to interact with your API.
|
||||
|
||||
Finally, we're also now exposing the schema generation as a
|
||||
[publicly documented API][schema-generation-api], allowing you to more easily
|
||||
override the behaviour.
|
||||
|
||||
## Requests test client
|
||||
|
||||
You can now test your project using the `requests` library.
|
||||
|
||||
This exposes exactly the same interface as if you were using a standard
|
||||
requests session instance.
|
||||
|
||||
client = RequestsClient()
|
||||
response = client.get('http://testserver/users/')
|
||||
assert response.status_code == 200
|
||||
|
||||
Rather than sending any HTTP requests to the network, this interface will
|
||||
coerce all outgoing requests into WSGI, and call into your application directly.
|
||||
|
||||
## Core API client
|
||||
|
||||
You can also now test your project by interacting with it using the `coreapi`
|
||||
client library.
|
||||
|
||||
# Fetch the API schema
|
||||
client = CoreAPIClient()
|
||||
schema = client.get('http://testserver/schema/')
|
||||
|
||||
# Create a new organisation
|
||||
params = {'name': 'MegaCorp', 'status': 'active'}
|
||||
client.action(schema, ['organisations', 'create'], params)
|
||||
|
||||
# Ensure that the organisation exists in the listing
|
||||
data = client.action(schema, ['organisations', 'list'])
|
||||
assert(len(data) == 1)
|
||||
assert(data == [{'name': 'MegaCorp', 'status': 'active'}])
|
||||
|
||||
Again, this will call directly into the application using the WSGI interface,
|
||||
rather than making actual network calls.
|
||||
|
||||
This is a good option if you are planning for clients to mainly interact with
|
||||
your API using the `coreapi` client library, or some other auto-generated client.
|
||||
|
||||
## Live tests
|
||||
|
||||
One interesting aspect of both the `requests` client and the `coreapi` client
|
||||
is that they allow you to write tests in such a way that they can also be made
|
||||
to run against a live service.
|
||||
|
||||
By switching the WSGI based client instances to actual instances of `requests.Session`
|
||||
or `coreapi.Client` you can have the test cases make actual network calls.
|
||||
|
||||
Being able to write test cases that can exercise your staging or production
|
||||
environment is a powerful tool. However in order to do this, you'll need to pay
|
||||
close attention to how you handle setup and teardown to ensure a strict isolation
|
||||
of test data from other live or staging data.
|
||||
|
||||
## RAML support
|
||||
|
||||
We now have preliminary support for [RAML documentation generation][django-rest-raml].
|
||||
|
||||
![RAML Example][raml-image]
|
||||
|
||||
Further work on the encoding and documentation generation is planned, in order to
|
||||
make features such as the 'Try it now' support available at a later date.
|
||||
|
||||
This work also now means that you can use the Core API client libraries to interact
|
||||
with APIs that expose a RAML specification. The [RAML codec][raml-codec] gives some examples of
|
||||
interacting with the Spotify API in this way.
|
||||
|
||||
## Validation codes
|
||||
|
||||
Exceptions raised by REST framework now include short code identifiers.
|
||||
When used together with our customizable error handling, this now allows you to
|
||||
modify the style of API error messages.
|
||||
|
||||
As an example, this allows for the following style of error responses:
|
||||
|
||||
{
|
||||
"message": "You do not have permission to perform this action.",
|
||||
"code": "permission_denied"
|
||||
}
|
||||
|
||||
This is particularly useful with validation errors, which use appropriate
|
||||
codes to identify differing kinds of failure...
|
||||
|
||||
{
|
||||
"name": {"message": "This field is required.", "code": "required"},
|
||||
"age": {"message": "A valid integer is required.", "code": "invalid"}
|
||||
}
|
||||
|
||||
## Client upload & download support
|
||||
|
||||
The Python `coreapi` client library and the Core API command line tool both
|
||||
now fully support file [uploads][uploads] and [downloads][downloads].
|
||||
|
||||
---
|
||||
|
||||
## Deprecations
|
||||
|
||||
### Generating schemas from Router
|
||||
|
||||
The router arguments for generating a schema view, such as `schema_title`,
|
||||
are now pending deprecation.
|
||||
|
||||
Instead of using `DefaultRouter(schema_title='Example API')`, you should use
|
||||
the `get_schema_view()` function, and include the view in your URL conf.
|
||||
|
||||
Make sure to include the view before your router urls. For example:
|
||||
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from my_project.routers import router
|
||||
|
||||
schema_view = get_schema_view(title='Example API')
|
||||
|
||||
urlpatterns = [
|
||||
path('', schema_view),
|
||||
path('', include(router.urls)),
|
||||
]
|
||||
|
||||
### Schema path representations
|
||||
|
||||
The `'pk'` identifier in schema paths is now mapped onto the actually model field
|
||||
name by default. This will typically be `'id'`.
|
||||
|
||||
This gives a better external representation for schemas, with less implementation
|
||||
detail being exposed. It also reflects the behaviour of using a ModelSerializer
|
||||
class with `fields = '__all__'`.
|
||||
|
||||
You can revert to the previous behaviour by setting `'SCHEMA_COERCE_PATH_PK': False`
|
||||
in the REST framework settings.
|
||||
|
||||
### Schema action name representations
|
||||
|
||||
The internal `retrieve()` and `destroy()` method names are now coerced to an
|
||||
external representation of `read` and `delete`.
|
||||
|
||||
You can revert to the previous behaviour by setting `'SCHEMA_COERCE_METHOD_NAMES': {}`
|
||||
in the REST framework settings.
|
||||
|
||||
### DjangoFilterBackend
|
||||
|
||||
The functionality of the built-in `DjangoFilterBackend` is now completely
|
||||
included by the `django-filter` package.
|
||||
|
||||
You should change your imports and REST framework filter settings as follows:
|
||||
|
||||
* `rest_framework.filters.DjangoFilterBackend` becomes `django_filters.rest_framework.DjangoFilterBackend`.
|
||||
* `rest_framework.filters.FilterSet` becomes `django_filters.rest_framework.FilterSet`.
|
||||
|
||||
The existing imports will continue to work but are now pending deprecation.
|
||||
|
||||
### CoreJSON media type
|
||||
|
||||
The media type for `CoreJSON` is now `application/json+coreapi`, rather than
|
||||
the previous `application/vnd.json+coreapi`. This brings it more into line with
|
||||
other custom media types, such as those used by Swagger and RAML.
|
||||
|
||||
The clients currently accept either media type. The old style-media type will
|
||||
be deprecated at a later date.
|
||||
|
||||
### ModelSerializer 'fields' and 'exclude'
|
||||
|
||||
ModelSerializer and HyperlinkedModelSerializer must include either a fields
|
||||
option, or an exclude option. The `fields = '__all__'` shortcut may be used to
|
||||
explicitly include all fields.
|
||||
|
||||
Failing to set either `fields` or `exclude` raised a pending deprecation warning
|
||||
in version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.
|
||||
|
||||
---
|
||||
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
||||
[uploads]: https://core-api.github.io/python-client/api-guide/utils/#file
|
||||
[downloads]: https://core-api.github.io/python-client/api-guide/codecs/#downloadcodec
|
||||
[schema-generation-api]: ../api-guide/schemas/#schemagenerator
|
||||
[schema-docs]: ../api-guide/schemas/#schemas-as-documentation
|
||||
[schema-view]: ../api-guide/schemas/#the-get_schema_view-shortcut
|
||||
[django-rest-raml]: https://github.com/encode/django-rest-raml
|
||||
[raml-image]: ../img/raml.png
|
||||
[raml-codec]: https://github.com/core-api/python-raml-codec
|
|
@ -1,199 +0,0 @@
|
|||
<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.6
|
||||
|
||||
The 3.6 release adds two major new features to REST framework.
|
||||
|
||||
1. Built-in interactive API documentation support.
|
||||
2. A new JavaScript client library.
|
||||
|
||||

|
||||
|
||||
*Above: The interactive API documentation.*
|
||||
|
||||
---
|
||||
|
||||
## Funding
|
||||
|
||||
The 3.6 release would not have been possible without our [backing from Mozilla](mozilla-grant.md) to the project, and our [collaborative funding model][funding].
|
||||
|
||||
If you use REST framework commercially and would like to see this work continue,
|
||||
we strongly encourage you to invest in its continued development by
|
||||
**[signing up for a paid plan][funding]**.
|
||||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
||||
<li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
<li><a href="https://machinalis.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</a></li>
|
||||
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar.png)">Rollbar</a></li>
|
||||
<li><a href="https://micropyramid.com/django-rest-framework-development-services/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/mp-text-logo.png)">MicroPyramid</a></li>
|
||||
</ul>
|
||||
<div style="clear: both; padding-bottom: 20px;"></div>
|
||||
|
||||
*Many thanks to all our [sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), [Rollbar](https://rollbar.com), and [MicroPyramid](https://micropyramid.com/django-rest-framework-development-services/).*
|
||||
|
||||
---
|
||||
|
||||
## Interactive API documentation
|
||||
|
||||
REST framework's new API documentation supports a number of features:
|
||||
|
||||
* Live API interaction.
|
||||
* Support for various authentication schemes.
|
||||
* Code snippets for the Python, JavaScript, and Command Line clients.
|
||||
|
||||
The `coreapi` library is required as a dependency for the API docs. Make sure
|
||||
to install the latest version (2.3.0 or above). The `pygments` and `markdown`
|
||||
libraries are optional but recommended.
|
||||
|
||||
To install the API documentation, you'll need to include it in your projects URLconf:
|
||||
|
||||
from rest_framework.documentation import include_docs_urls
|
||||
|
||||
API_TITLE = 'API title'
|
||||
API_DESCRIPTION = '...'
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
path('docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))
|
||||
]
|
||||
|
||||
Once installed you should see something a little like this:
|
||||
|
||||

|
||||
|
||||
We'll likely be making further refinements to the API documentation over the
|
||||
coming weeks. Keep in mind that this is a new feature, and please do give
|
||||
us feedback if you run into any issues or limitations.
|
||||
|
||||
For more information on documenting your API endpoints see the ["Documenting your API"][api-docs] section.
|
||||
|
||||
---
|
||||
|
||||
## JavaScript client library
|
||||
|
||||
The JavaScript client library allows you to load an API schema, and then interact
|
||||
with that API at an application layer interface, rather than constructing fetch
|
||||
requests explicitly.
|
||||
|
||||
Here's a brief example that demonstrates:
|
||||
|
||||
* Loading the client library and schema.
|
||||
* Instantiating an authenticated client.
|
||||
* Making an API request using the client.
|
||||
|
||||
**index.html**
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<script src="/static/rest_framework/js/coreapi-0.1.0.js"></script>
|
||||
<script src="/docs/schema.js"></script>
|
||||
<script>
|
||||
const coreapi = window.coreapi
|
||||
const schema = window.schema
|
||||
|
||||
// Instantiate a client...
|
||||
let auth = coreapi.auth.TokenAuthentication({scheme: 'JWT', token: 'xxx'})
|
||||
let client = coreapi.Client({auth: auth})
|
||||
|
||||
// Make an API request...
|
||||
client.action(schema, ['projects', 'list']).then(function(result) {
|
||||
alert(result)
|
||||
})
|
||||
</script>
|
||||
</head>
|
||||
</html>
|
||||
|
||||
The JavaScript client library supports various authentication schemes, and can be
|
||||
used by your project itself, or as an external client interacting with your API.
|
||||
|
||||
The client is not limited to usage with REST framework APIs, although it does
|
||||
currently only support loading CoreJSON API schemas. Support for Swagger and
|
||||
other API schemas is planned.
|
||||
|
||||
For more details see the [JavaScript client library documentation][js-docs].
|
||||
|
||||
## Authentication classes for the Python client library
|
||||
|
||||
Previous authentication support in the Python client library was limited to
|
||||
allowing users to provide explicit header values.
|
||||
|
||||
We now have better support for handling the details of authentication, with
|
||||
the introduction of the `BasicAuthentication`, `TokenAuthentication`, and
|
||||
`SessionAuthentication` schemes.
|
||||
|
||||
You can include the authentication scheme when instantiating a new client.
|
||||
|
||||
auth = coreapi.auth.TokenAuthentication(scheme='JWT', token='xxx-xxx-xxx')
|
||||
client = coreapi.Client(auth=auth)
|
||||
|
||||
For more information see the [Python client library documentation][py-docs].
|
||||
|
||||
---
|
||||
|
||||
## Deprecations
|
||||
|
||||
### Updating coreapi
|
||||
|
||||
If you're using REST framework's schema generation, or want to use the API docs,
|
||||
then you'll need to update to the latest version of coreapi. (2.3.0)
|
||||
|
||||
### Generating schemas from Router
|
||||
|
||||
The 3.5 "pending deprecation" of router arguments for generating a schema view, such as `schema_title`, `schema_url` and `schema_renderers`, have now been escalated to a
|
||||
"deprecated" warning.
|
||||
|
||||
Instead of using `DefaultRouter(schema_title='Example API')`, you should use the `get_schema_view()` function, and include the view explicitly in your URL conf.
|
||||
|
||||
### DjangoFilterBackend
|
||||
|
||||
The 3.5 "pending deprecation" warning of the built-in `DjangoFilterBackend` has now
|
||||
been escalated to a "deprecated" warning.
|
||||
|
||||
You should change your imports and REST framework filter settings as follows:
|
||||
|
||||
* `rest_framework.filters.DjangoFilterBackend` becomes `django_filters.rest_framework.DjangoFilterBackend`.
|
||||
* `rest_framework.filters.FilterSet` becomes `django_filters.rest_framework.FilterSet`.
|
||||
|
||||
---
|
||||
|
||||
## What's next
|
||||
|
||||
There are likely to be a number of refinements to the API documentation and
|
||||
JavaScript client library over the coming weeks, which could include some of the following:
|
||||
|
||||
* Support for private API docs, requiring login.
|
||||
* File upload and download support in the JavaScript client & API docs.
|
||||
* Comprehensive documentation for the JavaScript client library.
|
||||
* Automatically including authentication details in the API doc code snippets.
|
||||
* Adding authentication support in the command line client.
|
||||
* Support for loading Swagger and other schemas in the JavaScript client.
|
||||
* Improved support for documenting parameter schemas and response schemas.
|
||||
* Refining the API documentation interaction modal.
|
||||
|
||||
Once work on those refinements is complete, we'll be starting feature work
|
||||
on realtime support, for the 3.7 release.
|
||||
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
||||
[api-docs]: ../topics/documenting-your-api.md
|
||||
[js-docs]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md#javascript-client-library
|
||||
[py-docs]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md#python-client-library
|
|
@ -1,130 +0,0 @@
|
|||
<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.7
|
||||
|
||||
The 3.7 release focuses on improvements to schema generation and the interactive API documentation.
|
||||
|
||||
This release has been made possible by [Bayer](https://www.bayer.com/) who have sponsored the release.
|
||||
|
||||
<a href="https://www.bayer.com/"><img src="/img/bayer.png"/></a>
|
||||
|
||||
---
|
||||
|
||||
## Funding
|
||||
|
||||
If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by
|
||||
**[signing up for a paid plan][funding]**.
|
||||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
||||
<li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
<li><a href="https://machinalis.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</a></li>
|
||||
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar.png)">Rollbar</a></li>
|
||||
</ul>
|
||||
<div style="clear: both; padding-bottom: 20px;"></div>
|
||||
|
||||
*As well as our release sponsor, we'd like to say thanks in particular our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), and [Rollbar](https://rollbar.com).*
|
||||
|
||||
---
|
||||
|
||||
## Customizing API docs & schema generation.
|
||||
|
||||
The schema generation introduced in 3.5 and the related API docs generation in 3.6 are both hugely powerful features, however they've been somewhat limited in cases where the view introspection isn't able to correctly identify the schema for a particular view.
|
||||
|
||||
In order to try to address this we're now adding the ability for per-view customization of the API schema. The interface that we're adding for this allows either basic manual overrides over which fields should be included on a view, or for more complex programmatic overriding of the schema generation. We believe this release comprehensively addresses some of the existing shortcomings of the schema features.
|
||||
|
||||
Let's take a quick look at using the new functionality...
|
||||
|
||||
The `APIView` class has a `schema` attribute, that is used to control how the Schema for that particular view is generated. The default behaviour is to use the `AutoSchema` class.
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import AutoSchema
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = AutoSchema() # Included for demonstration only. This is the default behavior.
|
||||
|
||||
We can remove a view from the API schema and docs, like so:
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = None
|
||||
|
||||
If we want to mostly use the default behavior, but additionally include some additional fields on a particular view, we can now do so easily...
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = AutoSchema(manual_fields=[
|
||||
coreapi.Field('search', location='query')
|
||||
])
|
||||
|
||||
To ignore the automatic generation for a particular view, and instead specify the schema explicitly, we use the `ManualSchema` class instead...
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = ManualSchema(fields=[...])
|
||||
|
||||
For more advanced behaviors you can subclass `AutoSchema` to provide for customized schema generation, and apply that to particular views.
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = CustomizedSchemaGeneration()
|
||||
|
||||
For full details on the new functionality, please see the [Schema Documentation][schema-docs].
|
||||
|
||||
---
|
||||
|
||||
## Django 2.0 support
|
||||
|
||||
REST framework 3.7 supports Django versions 1.10, 1.11, and 2.0 alpha.
|
||||
|
||||
---
|
||||
|
||||
## Minor fixes and improvements
|
||||
|
||||
There are a large number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing.
|
||||
|
||||
The number of [open tickets against the project](https://github.com/encode/django-rest-framework/issues) currently at its lowest number in quite some time, and we're continuing to focus on reducing these to a manageable amount.
|
||||
|
||||
---
|
||||
|
||||
## Deprecations
|
||||
|
||||
### `exclude_from_schema`
|
||||
|
||||
Both `APIView.exclude_from_schema` and the `exclude_from_schema` argument to the `@api_view` decorator and now `PendingDeprecation`. They will be moved to deprecated in the 3.8 release, and removed entirely in 3.9.
|
||||
|
||||
For `APIView` you should instead set a `schema = None` attribute on the view class.
|
||||
|
||||
For function based views the `@schema` decorator can be used to exclude the view from the schema, by using `@schema(None)`.
|
||||
|
||||
### `DjangoFilterBackend`
|
||||
|
||||
The `DjangoFilterBackend` was moved to pending deprecation in 3.5, and deprecated in 3.6. It has now been removed from the core framework.
|
||||
|
||||
The functionality remains fully available, but is instead provided in the `django-filter` package.
|
||||
|
||||
---
|
||||
|
||||
## What's next
|
||||
|
||||
We're still planning to work on improving real-time support for REST framework by providing documentation on integrating with Django channels, as well adding support for more easily adding WebSocket support to existing HTTP endpoints.
|
||||
|
||||
This will likely be timed so that any REST framework development here ties in with similar work on [API Star][api-star].
|
||||
|
||||
[funding]: funding.md
|
||||
[schema-docs]: ../api-guide/schemas.md
|
||||
[api-star]: https://github.com/encode/apistar
|
|
@ -1,97 +0,0 @@
|
|||
<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.8
|
||||
|
||||
The 3.8 release is a maintenance focused release resolving a large number of previously outstanding issues and laying
|
||||
the foundations for future changes.
|
||||
|
||||
---
|
||||
|
||||
## Funding
|
||||
|
||||
If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by
|
||||
**[signing up for a paid plan][funding]**.
|
||||
|
||||
|
||||
*We'd like to say thanks in particular our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), and [Rollbar](https://rollbar.com).*
|
||||
|
||||
---
|
||||
|
||||
## Breaking Changes
|
||||
|
||||
### Altered the behaviour of `read_only` plus `default` on Field.
|
||||
|
||||
[#5886][gh5886] `read_only` fields will now **always** be excluded from writable fields.
|
||||
|
||||
Previously `read_only` fields when combined with a `default` value would use the `default` for create and update
|
||||
operations. This was counter-intuitive in some circumstances and led to difficulties supporting dotted `source`
|
||||
attributes on nullable relations.
|
||||
|
||||
In order to maintain the old behaviour you may need to pass the value of `read_only` fields when calling `save()` in
|
||||
the view:
|
||||
|
||||
def perform_create(self, serializer):
|
||||
serializer.save(owner=self.request.user)
|
||||
|
||||
Alternatively you may override `save()` or `create()` or `update()` on the serializer as appropriate.
|
||||
|
||||
---
|
||||
|
||||
## Deprecations
|
||||
|
||||
### `action` decorator replaces `list_route` and `detail_route`
|
||||
|
||||
[#5705][gh5705] `list_route` and `detail_route` have been merge into a single `action` decorator. This improves viewset action introspection, and will allow extra actions to be displayed in the Browsable API in future versions.
|
||||
|
||||
Both `list_route` and `detail_route` are now pending deprecation. They will be deprecated in 3.9 and removed entirely
|
||||
in 3.10.
|
||||
|
||||
The new `action` decorator takes a boolean `detail` argument.
|
||||
|
||||
* Replace `detail_route` uses with `@action(detail=True)`.
|
||||
* Replace `list_route` uses with `@action(detail=False)`.
|
||||
|
||||
|
||||
### `exclude_from_schema`
|
||||
|
||||
Both `APIView.exclude_from_schema` and the `exclude_from_schema` argument to the `@api_view` decorator are now deprecated. They will be removed entirely in 3.9.
|
||||
|
||||
For `APIView` you should instead set a `schema = None` attribute on the view class.
|
||||
|
||||
For function based views the `@schema` decorator can be used to exclude the view from the schema, by using `@schema(None)`.
|
||||
|
||||
---
|
||||
|
||||
## Minor fixes and improvements
|
||||
|
||||
There are a large number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page
|
||||
for a complete listing.
|
||||
|
||||
|
||||
## What's next
|
||||
|
||||
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.
|
||||
|
||||
[funding]: funding.md
|
||||
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886
|
||||
[gh5705]: https://github.com/encode/django-rest-framework/issues/5705
|
||||
[openapi]: https://www.openapis.org/
|
|
@ -1,210 +0,0 @@
|
|||
<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.9
|
||||
|
||||
The 3.9 release gives access to _extra actions_ in the Browsable API, introduces composable permissions and built-in [OpenAPI][openapi] schema support. (Formerly known as Swagger)
|
||||
|
||||
---
|
||||
|
||||
## Funding
|
||||
|
||||
If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by
|
||||
**[signing up for a paid plan][funding]**.
|
||||
|
||||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
||||
<li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
<li><a href="https://auklet.io" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/auklet-new.png)">Auklet</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://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
|
||||
<li><a href="https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/load-impact.png)">Load Impact</a></li>
|
||||
<li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless.png)">Kloudless</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, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Auklet](https://auklet.io/), [Rollbar](https://rollbar.com), [Cadre](https://cadre.com), [Load Impact](https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf), and [Kloudless](https://hubs.ly/H0f30Lf0).*
|
||||
|
||||
---
|
||||
|
||||
## Built-in OpenAPI schema support
|
||||
|
||||
REST framework now has a first-pass at directly including OpenAPI schema support. (Formerly known as Swagger)
|
||||
|
||||
Specifically:
|
||||
|
||||
* There are now `OpenAPIRenderer`, and `JSONOpenAPIRenderer` classes that deal with encoding `coreapi.Document` instances into OpenAPI YAML or OpenAPI JSON.
|
||||
* The `get_schema_view(...)` method now defaults to OpenAPI YAML, with CoreJSON as a secondary
|
||||
option if it is selected via HTTP content negotiation.
|
||||
* There is a new management command `generateschema`, which you can use to dump
|
||||
the schema into your repository.
|
||||
|
||||
Here's an example of adding an OpenAPI schema to the URL conf:
|
||||
|
||||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework.renderers import JSONOpenAPIRenderer
|
||||
from django.urls import path
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title="Server Monitoring API",
|
||||
url="https://www.example.org/api/",
|
||||
renderer_classes=[JSONOpenAPIRenderer],
|
||||
)
|
||||
|
||||
urlpatterns = [path("schema.json", schema_view), ...]
|
||||
```
|
||||
|
||||
And here's how you can use the `generateschema` management command:
|
||||
|
||||
```shell
|
||||
$ python manage.py generateschema --format openapi > schema.yml
|
||||
```
|
||||
|
||||
There's lots of different tooling that you can use for working with OpenAPI
|
||||
schemas. One option that we're working on is the [API Star](https://docs.apistar.com/)
|
||||
command line tool.
|
||||
|
||||
You can use `apistar` to validate your API schema:
|
||||
|
||||
```shell
|
||||
$ apistar validate --path schema.json --format openapi
|
||||
✓ Valid OpenAPI schema.
|
||||
```
|
||||
|
||||
Or to build API documentation:
|
||||
|
||||
```shell
|
||||
$ apistar docs --path schema.json --format openapi
|
||||
✓ Documentation built at "build/index.html".
|
||||
```
|
||||
|
||||
API Star also includes a [dynamic client library](https://docs.apistar.com/client-library/)
|
||||
that uses an API schema to automatically provide a client library interface for making requests.
|
||||
|
||||
## Composable permission classes
|
||||
|
||||
You can now compose permission classes using the and/or operators, `&` and `|`.
|
||||
|
||||
For example...
|
||||
|
||||
```python
|
||||
permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)]
|
||||
```
|
||||
|
||||
If you're using custom permission classes then make sure that you are subclassing
|
||||
from `BasePermission` in order to enable this support.
|
||||
|
||||
## ViewSet _Extra Actions_ available in the Browsable API
|
||||
|
||||
Following the introduction of the `action` decorator in v3.8, _extra actions_ defined on a ViewSet are now available
|
||||
from the Browsable API.
|
||||
|
||||

|
||||
|
||||
When defined, a dropdown of "Extra Actions", appropriately filtered to detail/non-detail actions, is displayed.
|
||||
|
||||
---
|
||||
|
||||
## Supported Versions
|
||||
|
||||
REST framework 3.9 supports Django versions 1.11, 2.0, and 2.1.
|
||||
|
||||
---
|
||||
|
||||
## Deprecations
|
||||
|
||||
### `DjangoObjectPermissionsFilter` moved to third-party package.
|
||||
|
||||
The `DjangoObjectPermissionsFilter` class is pending deprecation, will be deprecated in 3.10 and removed entirely in 3.11.
|
||||
|
||||
It has been moved to the third-party [`djangorestframework-guardian`](https://github.com/rpkilby/django-rest-framework-guardian)
|
||||
package. Please use this instead.
|
||||
|
||||
### Router argument/method renamed to use `basename` for consistency.
|
||||
|
||||
* The `Router.register` `base_name` argument has been renamed in favor of `basename`.
|
||||
* The `Router.get_default_base_name` method has been renamed in favor of `Router.get_default_basename`. [#5990][gh5990]
|
||||
|
||||
See [#5990][gh5990].
|
||||
|
||||
[gh5990]: https://github.com/encode/django-rest-framework/pull/5990
|
||||
|
||||
`base_name` and `get_default_base_name()` are pending deprecation. They will be deprecated in 3.10 and removed entirely in 3.11.
|
||||
|
||||
### `action` decorator replaces `list_route` and `detail_route`
|
||||
|
||||
Both `list_route` and `detail_route` are now deprecated in favour of the single `action` decorator.
|
||||
They will be removed entirely in 3.10.
|
||||
|
||||
The `action` decorator takes a boolean `detail` argument.
|
||||
|
||||
* Replace `detail_route` uses with `@action(detail=True)`.
|
||||
* Replace `list_route` uses with `@action(detail=False)`.
|
||||
|
||||
### `exclude_from_schema`
|
||||
|
||||
Both `APIView.exclude_from_schema` and the `exclude_from_schema` argument to the `@api_view` have now been removed.
|
||||
|
||||
For `APIView` you should instead set a `schema = None` attribute on the view class.
|
||||
|
||||
For function-based views the `@schema` decorator can be used to exclude the view from the schema, by using `@schema(None)`.
|
||||
|
||||
---
|
||||
|
||||
## Minor fixes and improvements
|
||||
|
||||
There are a large number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing.
|
||||
|
||||
|
||||
## What's next
|
||||
|
||||
We're planning to iteratively work towards OpenAPI becoming the standard schema
|
||||
representation. This will mean that the `coreapi` dependency will gradually become
|
||||
removed, and we'll instead generate the schema directly, rather than building
|
||||
a CoreAPI `Document` object.
|
||||
|
||||
OpenAPI has clearly become the standard for specifying Web APIs, so there's not
|
||||
much value any more in our schema-agnostic document model. Making this change
|
||||
will mean that we'll more easily be able to take advantage of the full set of
|
||||
OpenAPI functionality.
|
||||
|
||||
This will also make a wider range of tooling available.
|
||||
|
||||
We'll focus on continuing to develop the [API Star](https://docs.apistar.com/)
|
||||
library and client tool into a recommended option for generating API docs,
|
||||
validating API schemas, and providing a dynamic client library.
|
||||
|
||||
There's also a huge amount of ongoing work on maturing the ASGI landscape,
|
||||
with the possibility that some of this work will eventually [feed back into
|
||||
Django](https://www.aeracode.org/2018/06/04/django-async-roadmap/).
|
||||
|
||||
There will be further work on the [Uvicorn](https://www.uvicorn.org/)
|
||||
web server, as well as lots of functionality planned for the [Starlette](https://www.starlette.io/)
|
||||
web framework, which is building a foundational set of tooling for working with
|
||||
ASGI.
|
||||
|
||||
|
||||
[funding]: funding.md
|
||||
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886
|
||||
[gh5705]: https://github.com/encode/django-rest-framework/issues/5705
|
||||
[openapi]: https://www.openapis.org/
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
|
@ -1,200 +0,0 @@
|
|||
# Contributing to REST framework
|
||||
|
||||
> The world can only really be changed one piece at a time. The art is picking that piece.
|
||||
>
|
||||
> — [Tim Berners-Lee][cite]
|
||||
|
||||
!!! note
|
||||
|
||||
At this point in its lifespan we consider Django REST framework to be feature-complete. We focus on pull requests that track the continued development of Django versions, and generally do not 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.
|
||||
|
||||
If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.
|
||||
|
||||
Other really great ways you can help move the community forward include helping to answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag.
|
||||
|
||||
When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.
|
||||
|
||||
## Code of conduct
|
||||
|
||||
Please keep the tone polite & professional. For some users a discussion on the REST framework mailing list or ticket tracker may be their first engagement with the open source community. First impressions count, so let's try to make everyone feel welcome.
|
||||
|
||||
Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations.
|
||||
|
||||
The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines for participating in community forums.
|
||||
|
||||
# Issues
|
||||
|
||||
* Django REST framework is considered feature-complete. Please do not file requests to change behavior, unless it is required for security reasons or to maintain compatibility with upcoming Django or Python versions.
|
||||
* Feature requests will typically be closed with a recommendation that they be implemented outside the core REST framework library (e.g. as third-party libraries). This approach allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability and great documentation.
|
||||
|
||||
# Development
|
||||
|
||||
To start developing on Django REST framework, first create a Fork from the
|
||||
[Django REST Framework repo][repo] on GitHub.
|
||||
|
||||
Then clone your fork. The clone command will look like this, with your GitHub
|
||||
username instead of YOUR-USERNAME:
|
||||
|
||||
git clone https://github.com/YOUR-USERNAME/django-rest-framework
|
||||
|
||||
See GitHub's [_Fork a Repo_][how-to-fork] Guide for more help.
|
||||
|
||||
Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.
|
||||
You can check your contributions against these conventions each time you commit using the [pre-commit](https://pre-commit.com/) hooks, which we also run on CI.
|
||||
To set them up, first ensure you have the pre-commit tool installed, for example:
|
||||
|
||||
python -m pip install pre-commit
|
||||
|
||||
Then run:
|
||||
|
||||
pre-commit install
|
||||
|
||||
## Testing
|
||||
|
||||
To run the tests, clone the repository, and then:
|
||||
|
||||
# Setup the virtual environment
|
||||
python3 -m venv env
|
||||
source env/bin/activate
|
||||
pip install -e .
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Run the tests
|
||||
./runtests.py
|
||||
|
||||
### Test options
|
||||
|
||||
Run using a more concise output style.
|
||||
|
||||
./runtests.py -q
|
||||
|
||||
Run the tests for a given test case.
|
||||
|
||||
./runtests.py MyTestCase
|
||||
|
||||
Run the tests for a given test method.
|
||||
|
||||
./runtests.py MyTestCase.test_this_method
|
||||
|
||||
Shorter form to run the tests for a given test method.
|
||||
|
||||
./runtests.py test_this_method
|
||||
|
||||
Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
|
||||
|
||||
### Running against multiple environments
|
||||
|
||||
You can also use the excellent [tox][tox] testing tool to run the tests against all supported versions of Python and Django. Install `tox` globally, and then simply run:
|
||||
|
||||
tox
|
||||
|
||||
## Pull requests
|
||||
|
||||
It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.
|
||||
|
||||
It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests.
|
||||
|
||||
It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests.
|
||||
|
||||
GitHub's documentation for working on pull requests is [available here][pull-requests].
|
||||
|
||||
Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible on all supported versions of Python and Django.
|
||||
|
||||
Once you've made a pull request take a look at the build status in the GitHub interface and make sure the tests are running as you'd expect.
|
||||
|
||||
![Build status][build-status]
|
||||
|
||||
*Above: build notifications*
|
||||
|
||||
## Managing compatibility issues
|
||||
|
||||
Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the `compat.py` module, and should provide a single common interface that the rest of the codebase can use.
|
||||
|
||||
# Documentation
|
||||
|
||||
The documentation for REST framework is built from the [Markdown][markdown] source files in [the docs directory][docs].
|
||||
|
||||
There are many great Markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended.
|
||||
|
||||
## Building the documentation
|
||||
|
||||
To build the documentation, install MkDocs with `pip install mkdocs` and then run the following command.
|
||||
|
||||
mkdocs build
|
||||
|
||||
This will build the documentation into the `site` directory.
|
||||
|
||||
You can build the documentation and open a preview in a browser window by using the `serve` command.
|
||||
|
||||
mkdocs serve
|
||||
|
||||
## Language style
|
||||
|
||||
Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.
|
||||
|
||||
Some other tips:
|
||||
|
||||
* Keep paragraphs reasonably short.
|
||||
* Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.
|
||||
|
||||
## Markdown style
|
||||
|
||||
There are a couple of conventions you should follow when working on the documentation.
|
||||
|
||||
##### 1. Headers
|
||||
|
||||
Headers should use the hash style. For example:
|
||||
|
||||
### Some important topic
|
||||
|
||||
The underline style should not be used. **Don't do this:**
|
||||
|
||||
Some important topic
|
||||
====================
|
||||
|
||||
##### 2. Links
|
||||
|
||||
Links should always use the reference style, with the referenced hyperlinks kept at the end of the document.
|
||||
|
||||
Here is a link to [some other thing][other-thing].
|
||||
|
||||
More text...
|
||||
|
||||
[other-thing]: http://example.com/other/thing
|
||||
|
||||
This style helps keep the documentation source consistent and readable.
|
||||
|
||||
If you are hyperlinking to another REST framework document, you should use a relative link, and link to the `.md` suffix. For example:
|
||||
|
||||
[authentication]: ../api-guide/authentication.md
|
||||
|
||||
Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.
|
||||
|
||||
##### 3. Notes
|
||||
|
||||
If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:
|
||||
|
||||
---
|
||||
|
||||
**Note:** A useful documentation note.
|
||||
|
||||
---
|
||||
|
||||
|
||||
[cite]: https://www.w3.org/People/Berners-Lee/FAQ.html
|
||||
[code-of-conduct]: https://www.djangoproject.com/conduct/
|
||||
[google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[so-filter]: https://stackexchange.com/filters/66475/rest-framework
|
||||
[pep-8]: https://www.python.org/dev/peps/pep-0008/
|
||||
[build-status]: ../img/build-status.png
|
||||
[pull-requests]: https://help.github.com/articles/using-pull-requests
|
||||
[tox]: https://tox.readthedocs.io/en/latest/
|
||||
[markdown]: https://daringfireball.net/projects/markdown/basics
|
||||
[docs]: https://github.com/encode/django-rest-framework/tree/master/docs
|
||||
[mou]: http://mouapp.com/
|
||||
[repo]: https://github.com/encode/django-rest-framework
|
||||
[how-to-fork]: https://help.github.com/articles/fork-a-repo/
|
|
@ -1,388 +0,0 @@
|
|||
<script>
|
||||
// Imperfect, but easier to fit in with the existing docs build.
|
||||
// Hyperlinks should point directly to the "fund." subdomain, but this'll
|
||||
// handle the nav bar links without requiring any docs build changes for the moment.
|
||||
if (window.location.hostname == "www.django-rest-framework.org") {
|
||||
window.location.replace("https://fund.django-rest-framework.org/topics/funding/");
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
.chart {
|
||||
background-color: #e3e3e3;
|
||||
background: -webkit-linear-gradient(top, #fff 0, #e3e3e3 100%);
|
||||
border: 1px solid #E6E6E6;
|
||||
border-radius: 5px;
|
||||
box-shadow: 0px 0px 2px 0px rgba(181, 181, 181, 0.3);
|
||||
padding: 40px 0px 5px;
|
||||
position: relative;
|
||||
text-align: center;
|
||||
width: 97%;
|
||||
min-height: 255px;
|
||||
position: relative;
|
||||
top: 37px;
|
||||
margin-bottom: 20px
|
||||
}
|
||||
.quantity {
|
||||
text-align: center
|
||||
}
|
||||
.dollar {
|
||||
font-size: 19px;
|
||||
position: relative;
|
||||
top: -18px;
|
||||
}
|
||||
.price {
|
||||
font-size: 49px;
|
||||
}
|
||||
.period {
|
||||
font-size: 17px;
|
||||
position: relative;
|
||||
top: -8px;
|
||||
margin-left: 4px;
|
||||
}
|
||||
.plan-name {
|
||||
text-align: center;
|
||||
font-size: 20px;
|
||||
font-weight: 400;
|
||||
color: #777;
|
||||
border-bottom: 1px solid #d5d5d5;
|
||||
padding-bottom: 15px;
|
||||
width: 90%;
|
||||
margin: 0 auto;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.specs {
|
||||
margin-top: 20px;
|
||||
min-height: 130px;
|
||||
}
|
||||
.specs.freelancer {
|
||||
min-height: 0px;
|
||||
}
|
||||
.spec {
|
||||
font-size: 15px;
|
||||
color: #474747;
|
||||
text-align: center;
|
||||
font-weight: 300;
|
||||
margin-bottom: 13px;
|
||||
}
|
||||
.variable {
|
||||
color: #1FBEE7;
|
||||
font-weight: 400;
|
||||
}
|
||||
form.signup {
|
||||
margin-top: 35px
|
||||
}
|
||||
.clear-promo {
|
||||
padding-top: 30px
|
||||
}
|
||||
#main-content h1:first-of-type {
|
||||
margin: 0 0 50px;
|
||||
font-size: 60px;
|
||||
font-weight: 200;
|
||||
text-align: center
|
||||
}
|
||||
#main-content {
|
||||
padding-top: 10px; line-height: 23px
|
||||
}
|
||||
#main-content li {
|
||||
line-height: 23px
|
||||
}
|
||||
</style>
|
||||
|
||||
# Funding
|
||||
|
||||
If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan.
|
||||
|
||||
**We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.**
|
||||
|
||||
Signing up for a paid plan will:
|
||||
|
||||
* Directly contribute to faster releases, more features, and higher quality software.
|
||||
* Allow more time to be invested in keeping the package up to date.
|
||||
* Safeguard the future development of REST framework.
|
||||
|
||||
REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development.
|
||||
|
||||
---
|
||||
|
||||
## What funding has enabled so far
|
||||
|
||||
* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
|
||||
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
|
||||
* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
|
||||
* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/).
|
||||
* Tom Christie, the creator of Django REST framework, working on the project full-time.
|
||||
* Around 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time.
|
||||
* A community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship.
|
||||
* Contracting development time for the work on the JavaScript client library and API documentation tooling.
|
||||
|
||||
---
|
||||
|
||||
## What our sponsors and users say
|
||||
|
||||
> As a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem.
|
||||
>
|
||||
> — José Padilla, Django REST framework contributor
|
||||
|
||||
|
||||
|
||||
> 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.
|
||||
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
|
||||
|
||||
Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.
|
||||
|
||||
---
|
||||
|
||||
## Individual plan
|
||||
|
||||
This subscription is recommended for individuals with an interest in seeing REST framework continue to improve.
|
||||
|
||||
If you are using REST framework as a full-time employee, consider recommending that your company takes out a [corporate plan](#corporate-plans).
|
||||
|
||||
<div class="pricing">
|
||||
<div class="span4">
|
||||
<div class="chart first">
|
||||
<div class="quantity">
|
||||
<span class="dollar">{{ symbol }}</span>
|
||||
<span class="price">{{ rates.personal1 }}</span>
|
||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||
</div>
|
||||
<div class="plan-name">Individual</div>
|
||||
<div class="specs freelancer">
|
||||
<div class="spec">
|
||||
Support ongoing development
|
||||
</div>
|
||||
<div class="spec">
|
||||
Credited on the site
|
||||
</div>
|
||||
</div>
|
||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.personal1 }}/" method="POST">
|
||||
<script
|
||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||
data-key="{{ stripe_public }}"
|
||||
data-amount="{{ stripe_amounts.personal1 }}"
|
||||
data-name="Django REST framework"
|
||||
data-description="Individual"
|
||||
data-currency="{{ currency }}"
|
||||
data-allow-remember-me=false
|
||||
data-billing-address=true
|
||||
data-label='Sign up'
|
||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||
</script>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="clear: both; padding-top: 50px"></div>
|
||||
|
||||
*Billing is monthly and you can cancel at any time.*
|
||||
|
||||
---
|
||||
|
||||
## Corporate plans
|
||||
|
||||
These subscriptions are recommended for companies and organizations using REST framework either publicly or privately.
|
||||
|
||||
In exchange for funding you'll also receive advertising space on our site, allowing you to **promote your company or product to many tens of thousands of developers worldwide**.
|
||||
|
||||
Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.
|
||||
|
||||
<div class="pricing">
|
||||
<div class="span4">
|
||||
<div class="chart first">
|
||||
<div class="quantity">
|
||||
<span class="dollar">{{ symbol }}</span>
|
||||
<span class="price">{{ rates.corporate1 }}</span>
|
||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||
</div>
|
||||
<div class="plan-name">Basic</div>
|
||||
<div class="specs startup">
|
||||
<div class="spec">
|
||||
Support ongoing development
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Funding page</span> ad placement
|
||||
</div>
|
||||
</div>
|
||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate1 }}/" method="POST">
|
||||
<script
|
||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||
data-key="{{ stripe_public }}"
|
||||
data-amount="{{ stripe_amounts.corporate1 }}"
|
||||
data-name="Django REST framework"
|
||||
data-description="Basic"
|
||||
data-currency="{{ currency }}"
|
||||
data-allow-remember-me=false
|
||||
data-billing-address=true
|
||||
data-label='Sign up'
|
||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||
</script>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="span4">
|
||||
<div class="chart">
|
||||
<div class="quantity">
|
||||
<span class="dollar">{{ symbol }}</span>
|
||||
<span class="price">{{ rates.corporate2 }}</span>
|
||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||
</div>
|
||||
<div class="plan-name">Professional</div>
|
||||
<div class="specs">
|
||||
<div class="spec">
|
||||
Support ongoing development
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Sidebar</span> ad placement
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Priority support</span> for your engineers
|
||||
</div>
|
||||
</div>
|
||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate2 }}/" method="POST">
|
||||
<script
|
||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||
data-key="{{ stripe_public }}"
|
||||
data-amount="{{ stripe_amounts.corporate2 }}"
|
||||
data-name="Django REST framework"
|
||||
data-description="Professional"
|
||||
data-currency="{{ currency }}"
|
||||
data-allow-remember-me=false
|
||||
data-billing-address=true
|
||||
data-label='Sign up'
|
||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||
</script>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="span4">
|
||||
<div class="chart last">
|
||||
<div class="quantity">
|
||||
<span class="dollar">{{ symbol }}</span>
|
||||
<span class="price">{{ rates.corporate3 }}</span>
|
||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||
</div>
|
||||
<div class="plan-name">Premium</div>
|
||||
<div class="specs">
|
||||
<div class="spec">
|
||||
Support ongoing development
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Homepage</span> ad placement
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Sidebar</span> ad placement
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Priority support</span> for your engineers
|
||||
</div>
|
||||
</div>
|
||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate3 }}/" method="POST">
|
||||
<script
|
||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||
data-key="{{ stripe_public }}"
|
||||
data-amount="{{ stripe_amounts.corporate3 }}"
|
||||
data-name="Django REST framework"
|
||||
data-description="Premium"
|
||||
data-currency="{{ currency }}"
|
||||
data-allow-remember-me=false
|
||||
data-billing-address=true
|
||||
data-label='Sign up'
|
||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||
</script>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="clear: both; padding-top: 50px"></div>
|
||||
|
||||
*Billing is monthly and you can cancel at any time.*
|
||||
|
||||
Once you've signed up, we will contact you via email and arrange your ad placements on the site.
|
||||
|
||||
For further enquires please contact <a href=mailto:funding@django-rest-framework.org>funding@django-rest-framework.org</a>.
|
||||
|
||||
---
|
||||
|
||||
## Accountability
|
||||
|
||||
In an effort to keep the project as transparent as possible, we are releasing [monthly progress reports](https://www.encode.io/reports/march-2018/) and regularly include financial reports and cost breakdowns.
|
||||
|
||||
<!-- Begin MailChimp Signup Form -->
|
||||
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
|
||||
<style type="text/css">
|
||||
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||
</style>
|
||||
<div id="mc_embed_signup">
|
||||
<form action="//encode.us13.list-manage.com/subscribe/post?u=b6b66bb5e4c7cb484a85c8dd7&id=e382ef68ef" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||
<div id="mc_embed_signup_scroll">
|
||||
<h2>Stay up to date, with our monthly progress reports...</h2>
|
||||
<div class="mc-field-group">
|
||||
<label for="mce-EMAIL">Email Address </label>
|
||||
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
|
||||
</div>
|
||||
<div id="mce-responses" class="clear">
|
||||
<div class="response" id="mce-error-response" style="display:none"></div>
|
||||
<div class="response" id="mce-success-response" style="display:none"></div>
|
||||
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
|
||||
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_b6b66bb5e4c7cb484a85c8dd7_e382ef68ef" tabindex="-1" value=""></div>
|
||||
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
|
||||
<!--End mc_embed_signup-->
|
||||
|
||||
---
|
||||
|
||||
## Frequently asked questions
|
||||
|
||||
**Q: Can you issue monthly invoices?**
|
||||
A: Yes, we are happy to issue monthly invoices. Please just <a href=mailto:funding@django-rest-framework.org>email us</a> and let us know who to issue the invoice to (name and address) and which email address to send it to each month.
|
||||
|
||||
**Q: Does sponsorship include VAT?**
|
||||
A: Sponsorship is VAT exempt.
|
||||
|
||||
**Q: Do I have to sign up for a certain time period?**
|
||||
A: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime.
|
||||
|
||||
**Q: Can I pay yearly? Can I pay upfront fox X amount of months at a time?**
|
||||
A: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution.
|
||||
|
||||
**Q: Are you only looking for corporate sponsors?**
|
||||
A: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support.
|
||||
|
||||
---
|
||||
|
||||
## Our sponsors
|
||||
|
||||
<div id="fundingInclude"></div>
|
||||
|
||||
<script src="https://fund.django-rest-framework.org/funding_include.js"></script>
|
|
@ -1,43 +0,0 @@
|
|||
# Jobs
|
||||
|
||||
Looking for a new Django REST Framework related role? On this site we provide a list of job resources that may be helpful. It's also worth checking out if any of [our sponsors are hiring][drf-funding].
|
||||
|
||||
|
||||
## Places to look for Django REST Framework Jobs
|
||||
|
||||
* [https://www.djangoproject.com/community/jobs/][djangoproject-website]
|
||||
* [https://www.python.org/jobs/][python-org-jobs]
|
||||
* [https://django.on-remote.com][django-on-remote]
|
||||
* [https://djangogigs.com][django-gigs-com]
|
||||
* [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/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.com/remote-django-jobs][remoteok-com]
|
||||
* [https://www.remotepython.com/jobs/][remotepython-com]
|
||||
* [https://www.pyjobs.com/][pyjobs-com]
|
||||
|
||||
|
||||
Know of any other great resources for Django REST Framework jobs that are missing in our list? Please [submit a pull request][submit-pr] or [email us][anna-email].
|
||||
|
||||
Wonder how else you can help? One of the best ways you can help Django REST Framework is to ask interviewers if their company is signed up for [REST Framework sponsorship][drf-funding] yet.
|
||||
|
||||
|
||||
[djangoproject-website]: https://www.djangoproject.com/community/jobs/
|
||||
[python-org-jobs]: https://www.python.org/jobs/
|
||||
[django-on-remote]: https://django.on-remote.com/
|
||||
[django-gigs-com]: https://djangogigs.com
|
||||
[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/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-com]: https://remoteok.com/remote-django-jobs
|
||||
[remotepython-com]: https://www.remotepython.com/jobs/
|
||||
[pyjobs-com]: https://www.pyjobs.com/
|
||||
[drf-funding]: https://fund.django-rest-framework.org/topics/funding/
|
||||
[submit-pr]: https://github.com/encode/django-rest-framework
|
||||
[anna-email]: mailto:anna@django-rest-framework.org
|
|
@ -1,163 +0,0 @@
|
|||
# Kickstarting Django REST framework 3
|
||||
|
||||
---
|
||||
|
||||
<iframe style="display: block; margin: 0 auto 0 auto" width="480" height="360" src="https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3/widget/video.html" frameborder="0" scrolling="no"> </iframe>
|
||||
|
||||
---
|
||||
|
||||
In order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3.
|
||||
|
||||
## Project details
|
||||
|
||||
This new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following:
|
||||
|
||||
* Faster, simpler and easier-to-use serializers.
|
||||
* An alternative admin-style interface for the browsable API.
|
||||
* Search and filtering controls made accessible in the browsable API.
|
||||
* Alternative API pagination styles.
|
||||
* Documentation around API versioning.
|
||||
* Triage of outstanding tickets.
|
||||
* Improving the ongoing quality and maintainability of the project.
|
||||
|
||||
Full details are available now on the [project page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3).
|
||||
|
||||
If you're interested in helping make sustainable open source development a reality please [visit the Kickstarter page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) and consider funding the project.
|
||||
|
||||
I can't wait to see where this takes us!
|
||||
|
||||
Many thanks to everyone for your support so far,
|
||||
|
||||
Tom Christie :)
|
||||
|
||||
---
|
||||
|
||||
## Sponsors
|
||||
|
||||
We've now blazed way past all our goals, with a staggering £30,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.
|
||||
|
||||
---
|
||||
|
||||
### Platinum sponsors
|
||||
|
||||
Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough.
|
||||
|
||||
<ul class="sponsor diamond">
|
||||
<li><a href="https://www.eventbrite.com/" rel="nofollow" style="background-image:url(../../img/sponsors/0-eventbrite.png);">Eventbrite</a></li>
|
||||
</ul>
|
||||
|
||||
<ul class="sponsor platinum">
|
||||
<li><a href="https://www.divio.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-divio.png);">Divio</a></li>
|
||||
<li><a href="https://onlulu.com" rel="nofollow" style="background-image:url(../../img/sponsors/1-lulu.png);">Lulu</a></li>
|
||||
<li><a href="https://p.ota.to/" rel="nofollow" style="background-image:url(../../img/sponsors/1-potato.png);">Potato</a></li>
|
||||
<li><a href="http://www.wiredrive.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-wiredrive.png);">Wiredrive</a></li>
|
||||
<li><a href="http://www.cyaninc.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-cyan.png);">Cyan</a></li>
|
||||
<li><a href="https://www.runscope.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-runscope.png);">Runscope</a></li>
|
||||
<li><a href="http://simpleenergy.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-simple-energy.png);">Simple Energy</a></li>
|
||||
<li><a href="http://vokalinteractive.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-vokal_interactive.png);">VOKAL Interactive</a></li>
|
||||
<li><a href="http://www.purplebit.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-purplebit.png);">Purple Bit</a></li>
|
||||
<li><a href="http://www.kuwaitnet.net/" rel="nofollow" style="background-image:url(../../img/sponsors/1-kuwaitnet.png);">KuwaitNET</a></li>
|
||||
</ul>
|
||||
|
||||
<div style="clear: both"></div>
|
||||
|
||||
---
|
||||
|
||||
### Gold sponsors
|
||||
|
||||
Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development.
|
||||
|
||||
<ul class="sponsor gold">
|
||||
<li><a href="https://laterpay.net/" rel="nofollow" style="background-image:url(../../img/sponsors/2-laterpay.png);">LaterPay</a></li>
|
||||
<li><a href="https://www.schubergphilis.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-schuberg_philis.png);">Schuberg Philis</a></li>
|
||||
<li><a href="http://prorenata.se/" rel="nofollow" style="background-image:url(../../img/sponsors/2-prorenata.png);">ProReNata AB</a></li>
|
||||
<li><a href="https://www.sgawebsites.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-sga.png);">SGA Websites</a></li>
|
||||
<li><a href="https://www.sirono.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-sirono.png);">Sirono</a></li>
|
||||
<li><a href="https://www.vinta.com.br/" rel="nofollow" style="background-image:url(../../img/sponsors/2-vinta.png);">Vinta Software Studio</a></li>
|
||||
<li><a href="https://www.rapasso.nl/" rel="nofollow" style="background-image:url(../../img/sponsors/2-rapasso.png);">Rapasso</a></li>
|
||||
<li><a href="https://mirusresearch.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-mirus_research.png);">Mirus Research</a></li>
|
||||
<li><a href="https://hipolabs.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-hipo.png);">Hipo</a></li>
|
||||
<li><a href="https://www.byte.nl/" rel="nofollow" style="background-image:url(../../img/sponsors/2-byte.png);">Byte</a></li>
|
||||
<li><a href="https://www.lightningkite.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-lightning_kite.png);">Lightning Kite</a></li>
|
||||
<li><a href="https://opbeat.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-opbeat.png);">Opbeat</a></li>
|
||||
<li><a href="https://koordinates.com" rel="nofollow" style="background-image:url(../../img/sponsors/2-koordinates.png);">Koordinates</a></li>
|
||||
<li><a rel="nofollow" style="background-image:url(../../img/sponsors/2-pulsecode.png);">Pulsecode Inc.</a></li>
|
||||
<li><a rel="nofollow" style="background-image:url(../../img/sponsors/2-singing-horse.png);">Singing Horse Studio Ltd.</a></li>
|
||||
<li><a href="https://www.heroku.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-heroku.png);">Heroku</a></li>
|
||||
<li><a href="https://www.rheinwerk-verlag.de/" rel="nofollow" style="background-image:url(../../img/sponsors/2-rheinwerk_verlag.png);">Rheinwerk Verlag</a></li>
|
||||
<li><a href="https://www.securitycompass.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-security_compass.png);">Security Compass</a></li>
|
||||
<li><a href="https://www.djangoproject.com/foundation/" rel="nofollow" style="background-image:url(../../img/sponsors/2-django.png);">Django Software Foundation</a></li>
|
||||
<li><a href="http://www.hipflaskapp.com" rel="nofollow" style="background-image:url(../../img/sponsors/2-hipflask.png);">Hipflask</a></li>
|
||||
<li><a href="http://www.crate.io/" rel="nofollow" style="background-image:url(../../img/sponsors/2-crate.png);">Crate</a></li>
|
||||
<li><a href="http://crypticocorp.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-cryptico.png);">Cryptico Corp</a></li>
|
||||
<li><a rel="nofollow" style="background-image:url(../../img/sponsors/2-nexthub.png);">NextHub</a></li>
|
||||
<li><a href="https://www.compile.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-compile.png);">Compile</a></li>
|
||||
<li><a rel="nofollow" style="background-image:url(../../img/sponsors/2-wusawork.png);">WusaWork</a></li>
|
||||
<li><a href="http://envisionlinux.org/blog" rel="nofollow">Envision Linux</a></li>
|
||||
</ul>
|
||||
|
||||
<div style="clear: both; padding-bottom: 40px;"></div>
|
||||
|
||||
---
|
||||
|
||||
### Silver sponsors
|
||||
|
||||
The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank you to individuals who have chosen to privately support the project at this level.
|
||||
|
||||
<ul class="sponsor silver">
|
||||
<li><a href="https://www.imtapps.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-imt_computer_services.png);">IMT Computer Services</a></li>
|
||||
<li><a href="https://wildfish.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-wildfish.png);">Wildfish</a></li>
|
||||
<li><a href="https://www.thermondo.de/" rel="nofollow" style="background-image:url(../../img/sponsors/3-thermondo-gmbh.png);">Thermondo GmbH</a></li>
|
||||
<li><a href="https://providenz.fr/" rel="nofollow" style="background-image:url(../../img/sponsors/3-providenz.png);">Providenz</a></li>
|
||||
<li><a href="https://www.alwaysdata.com" rel="nofollow" style="background-image:url(../../img/sponsors/3-alwaysdata.png);">alwaysdata.com</a></li>
|
||||
<li><a href="https://www.freshrelevance.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-triggered_messaging.png);">Triggered Messaging</a></li>
|
||||
<li><a href="https://www.ipushpull.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-ipushpull.png);">PushPull Technology Ltd</a></li>
|
||||
<li><a href="http://www.transcode.de/" rel="nofollow" style="background-image:url(../../img/sponsors/3-transcode.png);">Transcode</a></li>
|
||||
<li><a href="https://garfo.io/" rel="nofollow" style="background-image:url(../../img/sponsors/3-garfo.png);">Garfo</a></li>
|
||||
<li><a href="https://goshippo.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-shippo.png);">Shippo</a></li>
|
||||
<li><a href="http://www.gizmag.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-gizmag.png);">Gizmag</a></li>
|
||||
<li><a href="https://www.tivix.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-tivix.png);">Tivix</a></li>
|
||||
<li><a href="https://www.safaribooksonline.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-safari.png);">Safari</a></li>
|
||||
<li><a href="http://brightloop.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-brightloop.png);">Bright Loop</a></li>
|
||||
<li><a href="http://www.aba-systems.com.au/" rel="nofollow" style="background-image:url(../../img/sponsors/3-aba.png);">ABA Systems</a></li>
|
||||
<li><a href="http://beefarm.ru/" rel="nofollow" style="background-image:url(../../img/sponsors/3-beefarm.png);">beefarm.ru</a></li>
|
||||
<li><a href="http://www.vzzual.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-vzzual.png);">Vzzual.com</a></li>
|
||||
<li><a href="http://infinite-code.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-infinite_code.png);">Infinite Code</a></li>
|
||||
<li><a href="https://crosswordtracker.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-crosswordtracker.png);">Crossword Tracker</a></li>
|
||||
<li><a href="https://www.pkgfarm.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-pkgfarm.png);">PkgFarm</a></li>
|
||||
<li><a href="http://life.tl/" rel="nofollow" style="background-image:url(../../img/sponsors/3-life_the_game.png);">Life. The Game.</a></li>
|
||||
<li><a href="http://blimp.io/" rel="nofollow" style="background-image:url(../../img/sponsors/3-blimp.png);">Blimp</a></li>
|
||||
<li><a href="https://www.pathwright.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-pathwright.png);">Pathwright</a></li>
|
||||
<li><a href="https://fluxility.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-fluxility.png);">Fluxility</a></li>
|
||||
<li><a href="https://teonite.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-teonite.png);">Teonite</a></li>
|
||||
<li><a href="https://trackmaven.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-trackmaven.png);">TrackMaven</a></li>
|
||||
<li><a href="https://www.phurba.net/" rel="nofollow" style="background-image:url(../../img/sponsors/3-phurba.png);">Phurba</a></li>
|
||||
<li><a href="https://www.nephila.it/it/" rel="nofollow" style="background-image:url(../../img/sponsors/3-nephila.png);">Nephila</a></li>
|
||||
<li><a href="http://www.aditium.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-aditium.png);">Aditium</a></li>
|
||||
<li><a href="https://www.eyesopen.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-openeye.png);">OpenEye Scientific Software</a></li>
|
||||
<li><a href="https://holvi.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-holvi.png);">Holvi</a></li>
|
||||
<li><a href="https://www.cantemo.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-cantemo.gif);">Cantemo</a></li>
|
||||
<li><a href="https://www.makespace.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-makespace.png);">MakeSpace</a></li>
|
||||
<li><a href="https://www.ax-semantics.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-ax_semantics.png);">AX Semantics</a></li>
|
||||
<li><a href="http://istrategylabs.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-isl.png);">ISL</a></li>
|
||||
</ul>
|
||||
|
||||
<div style="clear: both; padding-bottom: 40px;"></div>
|
||||
|
||||
**Individual backers**: Paul Hallett, <a href="http://www.paulwhippconsulting.com/">Paul Whipp</a>, Dylan Roy, Jannis Leidel, <a href="https://linovia.com/en/">Xavier Ordoquy</a>, <a href="http://spielmannsolutions.com/">Johannes Spielmann</a>, <a href="http://brooklynhacker.com/">Rob Spectre</a>, <a href="https://chrisheisel.com/">Chris Heisel</a>, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.
|
||||
|
||||
---
|
||||
|
||||
### Advocates
|
||||
|
||||
The following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you!
|
||||
|
||||
**Individual backers**: Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, Décébal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkkä, Charalampos Papaloizou, Nikolai Røed Kristiansen, Antoni Aloy López, Celia Oakley, Michał Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel.
|
||||
|
||||
**Corporate backers**: Savannah Informatics, Prism Skylabs, Musical Operating Devices.
|
||||
|
||||
---
|
||||
|
||||
### Supporters
|
||||
|
||||
There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!
|
|
@ -1,67 +0,0 @@
|
|||
# Mozilla Grant
|
||||
|
||||
We have recently been [awarded a Mozilla grant](https://blog.mozilla.org/blog/2016/04/13/mozilla-open-source-support-moss-update-q1-2016/), in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with.
|
||||
|
||||
Additionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications.
|
||||
|
||||
The [Core API](https://www.coreapi.org/) project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with *any* API that exposes a supported schema or hypermedia format.
|
||||
|
||||
Specifically, the work includes:
|
||||
|
||||
## Client libraries
|
||||
|
||||
This work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation.
|
||||
|
||||
* Client library support in REST framework.
|
||||
* Schema & hypermedia support for REST framework APIs.
|
||||
* A test client, allowing you to write tests that emulate a client library interacting with your API.
|
||||
* New tutorial sections on using client libraries to interact with REST framework APIs.
|
||||
* Python client library.
|
||||
* JavaScript client library.
|
||||
* Command line client.
|
||||
|
||||
## Realtime APIs
|
||||
|
||||
The next goal is to build on the realtime support offered by Django Channels, adding support & documentation for building realtime API endpoints.
|
||||
|
||||
* Support for API subscription endpoints, using REST framework and Django Channels.
|
||||
* New tutorial section on building realtime API endpoints with REST framework.
|
||||
* Realtime support in the Python & Javascript client libraries.
|
||||
|
||||
## Accountability
|
||||
|
||||
In order to ensure that I can be fully focused on trying to secure a sustainable
|
||||
& well-funded open source business I will be leaving my current role at [DabApps](https://www.dabapps.com/)
|
||||
at the end of May 2016.
|
||||
|
||||
I have formed a UK limited company, [Encode](https://www.encode.io/), which will
|
||||
act as the business entity behind REST framework. I will be issuing monthly reports
|
||||
from Encode on progress both towards the Mozilla grant, and for development time
|
||||
funded via the [REST framework paid plans](funding.md).
|
||||
|
||||
<!-- Begin MailChimp Signup Form -->
|
||||
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
|
||||
<style type="text/css">
|
||||
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||
</style>
|
||||
<div id="mc_embed_signup">
|
||||
<form action="//encode.us13.list-manage.com/subscribe/post?u=b6b66bb5e4c7cb484a85c8dd7&id=e382ef68ef" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||
<div id="mc_embed_signup_scroll">
|
||||
<h2>Stay up to date, with our monthly progress reports...</h2>
|
||||
<div class="mc-field-group">
|
||||
<label for="mce-EMAIL">Email Address </label>
|
||||
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
|
||||
</div>
|
||||
<div id="mce-responses" class="clear">
|
||||
<div class="response" id="mce-error-response" style="display:none"></div>
|
||||
<div class="response" id="mce-success-response" style="display:none"></div>
|
||||
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
|
||||
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_b6b66bb5e4c7cb484a85c8dd7_e382ef68ef" tabindex="-1" value=""></div>
|
||||
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
|
||||
<!--End mc_embed_signup-->
|
|
@ -1,162 +0,0 @@
|
|||
# Project management
|
||||
|
||||
> "No one can whistle a symphony; it takes a whole orchestra to play it"
|
||||
>
|
||||
> — Halford E. Luccock
|
||||
|
||||
This document outlines our project management processes for REST framework.
|
||||
|
||||
The aim is to ensure that the project has a high
|
||||
["bus factor"][bus-factor], and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome.
|
||||
|
||||
---
|
||||
|
||||
## Maintenance team
|
||||
|
||||
[Participating actively in the REST framework project](contributing.md) **does not require being part of the maintenance team**. Almost every important part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.
|
||||
|
||||
#### Composition
|
||||
|
||||
The composition of the maintenance team is handled by [@tomchristie](https://github.com/encode/). Team members will be added as collaborators to the repository.
|
||||
|
||||
#### Responsibilities
|
||||
|
||||
Team members have the following responsibilities.
|
||||
|
||||
* Close invalid or resolved tickets.
|
||||
* Add triage labels and milestones to tickets.
|
||||
* Merge finalized pull requests.
|
||||
* Build and deploy the documentation, using `mkdocs gh-deploy`.
|
||||
* Build and update the included translation packs.
|
||||
|
||||
Further notes for maintainers:
|
||||
|
||||
* Code changes should come in the form of a pull request - do not push directly to master.
|
||||
* Maintainers should typically not merge their own pull requests.
|
||||
* Each issue/pull request should have exactly one label once triaged.
|
||||
|
||||
---
|
||||
|
||||
## Release process
|
||||
|
||||
* The release manager is selected by `@tomchristie`.
|
||||
* The release manager will then have the maintainer role added to PyPI package.
|
||||
* The previous manager will then have the maintainer role removed from the PyPI package.
|
||||
|
||||
Our PyPI releases will be handled by either the current release manager, or by `@tomchristie`. Every release should have an open issue tagged with the `Release` label and marked against the appropriate milestone.
|
||||
|
||||
The following template should be used for the description of the issue, and serves as a release checklist.
|
||||
|
||||
Release manager is @***.
|
||||
Pull request is #***.
|
||||
|
||||
During development cycle:
|
||||
|
||||
- [ ] Upload the new content to be translated to [transifex](https://www.django-rest-framework.org/topics/project-management/#translations).
|
||||
|
||||
|
||||
Checklist:
|
||||
|
||||
- [ ] Create pull request for [release notes](https://github.com/encode/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/encode/django-rest-framework/milestones/***).
|
||||
- [ ] Update supported versions:
|
||||
- [ ] `setup.py` `python_requires` list
|
||||
- [ ] `setup.py` Python & Django version trove classifiers
|
||||
- [ ] `README` Python & Django versions
|
||||
- [ ] `docs` Python & Django versions
|
||||
- [ ] Update the translations from [transifex](https://www.django-rest-framework.org/topics/project-management/#translations).
|
||||
- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/__init__.py).
|
||||
- [ ] Ensure documentation validates
|
||||
- Build and serve docs `mkdocs serve`
|
||||
- Validate links `pylinkvalidate.py -P http://127.0.0.1:8000`
|
||||
- [ ] Confirm with @tomchristie that release is finalized and ready to go.
|
||||
- [ ] Ensure that release date is included in pull request.
|
||||
- [ ] Merge the release pull request.
|
||||
- [ ] Push the package to PyPI with `./setup.py publish`.
|
||||
- [ ] Tag the release, with `git tag -a *.*.* -m 'version *.*.*'; git push --tags`.
|
||||
- [ ] Deploy the documentation with `mkdocs gh-deploy`.
|
||||
- [ ] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).
|
||||
- [ ] Make a release announcement on twitter.
|
||||
- [ ] Close the milestone on GitHub.
|
||||
|
||||
To modify this process for future releases make a pull request to the [project management](https://www.django-rest-framework.org/topics/project-management/) documentation.
|
||||
|
||||
When pushing the release to PyPI ensure that your environment has been installed from our development `requirement.txt`, so that documentation and PyPI installs are consistently being built against a pinned set of packages.
|
||||
|
||||
---
|
||||
|
||||
## Translations
|
||||
|
||||
The maintenance team are responsible for managing the translation packs include in REST framework. Translating the source strings into multiple languages is managed through the [transifex service][transifex-project].
|
||||
|
||||
### Managing Transifex
|
||||
|
||||
The [official Transifex client][transifex-client] is used to upload and download translations to Transifex. The client is installed using pip:
|
||||
|
||||
pip install transifex-client
|
||||
|
||||
To use it you'll need a login to Transifex which has a password, and you'll need to have administrative access to the Transifex project. You'll need to create a `~/.transifexrc` file which contains your credentials.
|
||||
|
||||
[https://www.transifex.com]
|
||||
username = ***
|
||||
token = ***
|
||||
password = ***
|
||||
hostname = https://www.transifex.com
|
||||
|
||||
### Upload new source files
|
||||
|
||||
When any user visible strings are changed, they should be uploaded to Transifex so that the translators can start to translate them. To do this, just run:
|
||||
|
||||
# 1. Update the source django.po file, which is the US English version.
|
||||
cd rest_framework
|
||||
django-admin makemessages -l en_US
|
||||
# 2. Push the source django.po file to Transifex.
|
||||
cd ..
|
||||
tx push -s
|
||||
|
||||
When pushing source files, Transifex will update the source strings of a resource to match those from the new source file.
|
||||
|
||||
Here's how differences between the old and new source files will be handled:
|
||||
|
||||
* New strings will be added.
|
||||
* Modified strings will be added as well.
|
||||
* Strings which do not exist in the new source file will be removed from the database, along with their translations. If that source strings gets re-added later then [Transifex Translation Memory][translation-memory] will automatically include the translation string.
|
||||
|
||||
### Download translations
|
||||
|
||||
When a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run:
|
||||
|
||||
# 3. Pull the translated django.po files from Transifex.
|
||||
tx pull -a --minimum-perc 10
|
||||
cd rest_framework
|
||||
# 4. Compile the binary .mo files for all supported languages.
|
||||
django-admin compilemessages
|
||||
|
||||
---
|
||||
|
||||
## Project requirements
|
||||
|
||||
All our test requirements are pinned to exact versions, in order to ensure that our test runs are reproducible. We maintain the requirements in the `requirements` directory. The requirements files are referenced from the `tox.ini` configuration file, ensuring we have a single source of truth for package versions used in testing.
|
||||
|
||||
Package upgrades should generally be treated as isolated pull requests. You can check if there are any packages available at a newer version, by using the `pip list --outdated`.
|
||||
|
||||
---
|
||||
|
||||
## Project ownership
|
||||
|
||||
The PyPI package is owned by `@tomchristie`. As a backup `@j4mie` also has ownership of the package.
|
||||
|
||||
If `@tomchristie` ceases to participate in the project then `@j4mie` has responsibility for handing over ownership duties.
|
||||
|
||||
#### Outstanding management & ownership issues
|
||||
|
||||
The following issues still need to be addressed:
|
||||
|
||||
* Ensure `@j4mie` has back-up access to the `django-rest-framework.org` domain setup and admin.
|
||||
* Document ownership of the [mailing list][mailing-list] and IRC channel.
|
||||
* Document ownership and management of the security mailing list.
|
||||
|
||||
[bus-factor]: https://en.wikipedia.org/wiki/Bus_factor
|
||||
[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/
|
||||
[transifex-client]: https://pypi.org/project/transifex-client/
|
||||
[translation-memory]: http://docs.transifex.com/guides/tm#let-tm-automatically-populate-translations
|
||||
[mailing-list]: https://groups.google.com/forum/#!forum/django-rest-framework
|
|
@ -1,261 +0,0 @@
|
|||
# Third Party Packages
|
||||
|
||||
> Software ecosystems […] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.
|
||||
>
|
||||
> — [Jan Bosch][cite].
|
||||
|
||||
## About Third Party Packages
|
||||
|
||||
Third Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.
|
||||
|
||||
We **support**, **encourage** and **strongly favor** the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.
|
||||
|
||||
We aim to make creating third party packages as easy as possible, whilst keeping a **simple** and **well maintained** core API. By promoting third party packages we ensure that the responsibility for a package remains with its author. If a package proves suitably popular it can always be considered for inclusion into the core REST framework.
|
||||
|
||||
If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the [Mailing List][discussion-group].
|
||||
|
||||
## Creating a Third Party Package
|
||||
|
||||
### Version compatibility
|
||||
|
||||
Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a `compat.py` module, and should provide a single common interface that the rest of the codebase can use.
|
||||
|
||||
Check out Django REST framework's [compat.py][drf-compat] for an example.
|
||||
|
||||
### Once your package is available
|
||||
|
||||
Once your package is decently documented and available on PyPI, you might want share it with others that might find it useful.
|
||||
|
||||
#### Adding to the Django REST framework grid
|
||||
|
||||
We suggest adding your package to the [REST Framework][rest-framework-grid] grid on Django Packages.
|
||||
|
||||
#### Adding to the Django REST framework docs
|
||||
|
||||
Create a [Pull Request][drf-create-pr] on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under **Third party packages** of the API Guide section that best applies, like [Authentication][authentication] or [Permissions][permissions]. You can also link your package under the [Third Party Packages][third-party-packages] section.
|
||||
|
||||
#### Announce on the discussion group.
|
||||
|
||||
You can also let others know about your package through the [discussion group][discussion-group].
|
||||
|
||||
## Existing Third Party Packages
|
||||
|
||||
Django REST Framework has a growing community of developers, packages, and resources.
|
||||
|
||||
Check out a grid detailing all the packages and ecosystem around Django REST Framework at [Django Packages][rest-framework-grid].
|
||||
|
||||
To submit new content, [create a pull request][drf-create-pr].
|
||||
|
||||
## Async Support
|
||||
|
||||
* [adrf](https://github.com/em1208/adrf) - Async support, provides async Views, ViewSets, and Serializers.
|
||||
|
||||
### Authentication
|
||||
|
||||
* [djangorestframework-digestauth][djangorestframework-digestauth] - Provides Digest Access Authentication support.
|
||||
* [django-oauth-toolkit][django-oauth-toolkit] - Provides OAuth 2.0 support.
|
||||
* [djangorestframework-simplejwt][djangorestframework-simplejwt] - Provides JSON Web Token Authentication support.
|
||||
* [hawkrest][hawkrest] - Provides Hawk HTTP Authorization.
|
||||
* [djangorestframework-httpsignature][djangorestframework-httpsignature] - Provides an easy to use HTTP Signature Authentication mechanism.
|
||||
* [djoser][djoser] - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.
|
||||
* [dj-rest-auth][dj-rest-auth] - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.
|
||||
* [drf-oidc-auth][drf-oidc-auth] - Implements OpenID Connect token authentication for DRF.
|
||||
* [drfpasswordless][drfpasswordless] - Adds (Medium, Square Cash inspired) passwordless logins and signups via email and mobile numbers.
|
||||
* [django-rest-authemail][django-rest-authemail] - Provides a RESTful API for user signup and authentication using email addresses.
|
||||
* [dango-pyoidc][django-pyoidc] adds support for OpenID Connect (OIDC) authentication.
|
||||
|
||||
### Permissions
|
||||
|
||||
* [drf-any-permissions][drf-any-permissions] - Provides alternative permission handling.
|
||||
* [djangorestframework-composed-permissions][djangorestframework-composed-permissions] - Provides a simple way to define complex permissions.
|
||||
* [rest_condition][rest-condition] - Another extension for building complex permissions in a simple and convenient way.
|
||||
* [dry-rest-permissions][dry-rest-permissions] - Provides a simple way to define permissions for individual api actions.
|
||||
* [drf-access-policy][drf-access-policy] - Declarative and flexible permissions inspired by AWS' IAM policies.
|
||||
* [drf-psq][drf-psq] - An extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.
|
||||
|
||||
### Serializers
|
||||
|
||||
* [django-rest-framework-mongoengine][django-rest-framework-mongoengine] - Serializer class that supports using MongoDB as the storage layer for Django REST framework.
|
||||
* [djangorestframework-gis][djangorestframework-gis] - Geographic add-ons
|
||||
* [djangorestframework-hstore][djangorestframework-hstore] - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.
|
||||
* [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
|
||||
* [html-json-forms][html-json-forms] - Provides an algorithm and serializer to process HTML JSON Form submissions per the (inactive) spec.
|
||||
* [django-rest-framework-serializer-extensions][drf-serializer-extensions] -
|
||||
Enables black/whitelisting fields, and conditionally expanding child serializers on a per-view/request basis.
|
||||
* [djangorestframework-queryfields][djangorestframework-queryfields] - Serializer mixin allowing clients to control which fields will be sent in the API response.
|
||||
* [drf-flex-fields][drf-flex-fields] - Serializer providing dynamic field expansion and sparse field sets via URL parameters.
|
||||
* [drf-action-serializer][drf-action-serializer] - Serializer providing per-action fields config for use with ViewSets to prevent having to write multiple serializers.
|
||||
* [djangorestframework-dataclasses][djangorestframework-dataclasses] - Serializer providing automatic field generation for Python dataclasses, like the built-in ModelSerializer does for models.
|
||||
* [django-restql][django-restql] - Turn your REST API into a GraphQL like API(It allows clients to control which fields will be sent in a response, uses GraphQL like syntax, supports read and write on both flat and nested fields).
|
||||
* [graphwrap][graphwrap] - Transform your REST API into a fully compliant GraphQL API with just two lines of code. Leverages [Graphene-Django](https://docs.graphene-python.org/projects/django/en/latest/) to dynamically build, at runtime, a GraphQL ObjectType for each view in your API.
|
||||
|
||||
### Serializer fields
|
||||
|
||||
* [drf-compound-fields][drf-compound-fields] - Provides "compound" serializer fields, such as lists of simple values.
|
||||
* [drf-extra-fields][drf-extra-fields] - Provides extra serializer fields.
|
||||
* [django-versatileimagefield][django-versatileimagefield] - Provides a drop-in replacement for Django's stock `ImageField` that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, [click here][django-versatileimagefield-drf-docs].
|
||||
|
||||
### Views
|
||||
|
||||
* [django-rest-multiple-models][django-rest-multiple-models] - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
|
||||
* [drf-typed-views][drf-typed-views] - Use Python type annotations to validate/deserialize request parameters. Inspired by API Star, Hug and FastAPI.
|
||||
* [rest-framework-actions][rest-framework-actions] - Provides control over each action in ViewSets. Serializers per action, method.
|
||||
|
||||
### Routers
|
||||
|
||||
* [drf-nested-routers][drf-nested-routers] - Provides routers and relationship fields for working with nested resources.
|
||||
* [wq.db.rest][wq.db.rest] - Provides an admin-style model registration API with reasonable default URLs and viewsets.
|
||||
|
||||
### Parsers
|
||||
|
||||
* [djangorestframework-msgpack][djangorestframework-msgpack] - Provides MessagePack renderer and parser support.
|
||||
* [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
|
||||
* [djangorestframework-camel-case][djangorestframework-camel-case] - Provides camel case JSON renderers and parsers.
|
||||
* [nested-multipart-parser][nested-multipart-parser] - Provides nested parser for http multipart request
|
||||
|
||||
### Renderers
|
||||
|
||||
* [djangorestframework-csv][djangorestframework-csv] - Provides CSV renderer support.
|
||||
* [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
|
||||
* [drf_ujson2][drf_ujson2] - Implements JSON rendering using the UJSON package.
|
||||
* [rest-pandas][rest-pandas] - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.
|
||||
* [djangorestframework-rapidjson][djangorestframework-rapidjson] - Provides rapidjson support with parser and renderer.
|
||||
|
||||
### Filtering
|
||||
|
||||
* [djangorestframework-chain][djangorestframework-chain] - Allows arbitrary chaining of both relations and lookup filters.
|
||||
* [django-url-filter][django-url-filter] - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.
|
||||
* [drf-url-filter][drf-url-filter] is a simple Django app to apply filters on drf `ModelViewSet`'s `Queryset` in a clean, simple and configurable way. It also supports validations on incoming query params and their values.
|
||||
* [django-rest-framework-guardian][django-rest-framework-guardian] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF.
|
||||
|
||||
### Misc
|
||||
|
||||
* [drf-sendables][drf-sendables] - User messages for Django REST Framework
|
||||
* [cookiecutter-django-rest][cookiecutter-django-rest] - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome.
|
||||
* [djangorestrelationalhyperlink][djangorestrelationalhyperlink] - A hyperlinked serializer that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.
|
||||
* [django-rest-framework-proxy][django-rest-framework-proxy] - Proxy to redirect incoming request to another API server.
|
||||
* [gaiarestframework][gaiarestframework] - Utils for django-rest-framework
|
||||
* [drf-extensions][drf-extensions] - A collection of custom extensions
|
||||
* [ember-django-adapter][ember-django-adapter] - An adapter for working with Ember.js
|
||||
* [django-versatileimagefield][django-versatileimagefield] - Provides a drop-in replacement for Django's stock `ImageField` that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, [click here][django-versatileimagefield-drf-docs].
|
||||
* [drf-tracking][drf-tracking] - Utilities to track requests to DRF API views.
|
||||
* [drf_tweaks][drf_tweaks] - Serializers with one-step validation (and more), pagination without counts and other tweaks.
|
||||
* [django-rest-framework-braces][django-rest-framework-braces] - Collection of utilities for working with Django Rest Framework. The most notable ones are [FormSerializer](https://django-rest-framework-braces.readthedocs.io/en/latest/overview.html#formserializer) and [SerializerForm](https://django-rest-framework-braces.readthedocs.io/en/latest/overview.html#serializerform), which are adapters between DRF serializers and Django forms.
|
||||
* [drf-haystack][drf-haystack] - Haystack search for Django Rest Framework
|
||||
* [django-rest-framework-version-transforms][django-rest-framework-version-transforms] - Enables the use of delta transformations for versioning of DRF resource representations.
|
||||
* [django-rest-messaging][django-rest-messaging], [django-rest-messaging-centrifugo][django-rest-messaging-centrifugo] and [django-rest-messaging-js][django-rest-messaging-js] - A real-time pluggable messaging service using DRM.
|
||||
* [djangorest-alchemy][djangorest-alchemy] - SQLAlchemy support for REST framework.
|
||||
* [djangorestframework-datatables][djangorestframework-datatables] - Seamless integration between Django REST framework and [Datatables](https://datatables.net).
|
||||
* [django-rest-framework-condition][django-rest-framework-condition] - Decorators for managing HTTP cache headers for Django REST framework (ETag and Last-modified).
|
||||
* [django-rest-witchcraft][django-rest-witchcraft] - Provides DRF integration with SQLAlchemy with SQLAlchemy model serializers/viewsets and a bunch of other goodies
|
||||
* [djangorestframework-mvt][djangorestframework-mvt] - An extension for creating views that serve Postgres data as Map Box Vector Tiles.
|
||||
* [drf-viewset-profiler][drf-viewset-profiler] - Lib to profile all methods from a viewset line by line.
|
||||
* [djangorestframework-features][djangorestframework-features] - Advanced schema generation and more based on named features.
|
||||
* [django-elasticsearch-dsl-drf][django-elasticsearch-dsl-drf] - Integrate Elasticsearch DSL with Django REST framework. Package provides views, serializers, filter backends, pagination and other handy add-ons.
|
||||
* [django-api-client][django-api-client] - DRF client that groups the Endpoint response, for use in CBVs and FBV as if you were working with Django's Native Models..
|
||||
* [fast-drf] - A model based library for making API development faster and easier.
|
||||
* [django-requestlogs] - Providing middleware and other helpers for audit logging for REST framework.
|
||||
* [drf-standardized-errors][drf-standardized-errors] - DRF exception handler to standardize error responses for all API endpoints.
|
||||
* [drf-api-action][drf-api-action] - uses the power of DRF also as a library functions
|
||||
|
||||
### Customization
|
||||
|
||||
* [drf-restwind][drf-restwind] - a modern re-imagining of the Django REST Framework utilizes TailwindCSS and DaisyUI to provide flexible and customizable UI solutions with minimal coding effort.
|
||||
* [drf-redesign][drf-redesign] - A project that gives a fresh look to the browse-able API using Bootstrap 5.
|
||||
* [drf-material][drf-material] - A project that gives a sleek and elegant look to the browsable API using Material Design.
|
||||
|
||||
[drf-sendables]: https://github.com/amikrop/drf-sendables
|
||||
[cite]: http://www.software-ecosystems.com/Software_Ecosystems/Ecosystems.html
|
||||
[cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework
|
||||
[new-repo]: https://github.com/new
|
||||
[create-a-repo]: https://help.github.com/articles/create-a-repo/
|
||||
[pypi-register]: https://pypi.org/account/register/
|
||||
[semver]: https://semver.org/
|
||||
[tox-docs]: https://tox.readthedocs.io/en/latest/
|
||||
[drf-compat]: https://github.com/encode/django-rest-framework/blob/master/rest_framework/compat.py
|
||||
[rest-framework-grid]: https://www.djangopackages.com/grids/g/django-rest-framework/
|
||||
[drf-create-pr]: https://github.com/encode/django-rest-framework/compare
|
||||
[authentication]: ../api-guide/authentication.md
|
||||
[permissions]: ../api-guide/permissions.md
|
||||
[third-party-packages]: ../topics/third-party-packages/#existing-third-party-packages
|
||||
[discussion-group]: https://groups.google.com/forum/#!forum/django-rest-framework
|
||||
[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
|
||||
[django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
|
||||
[djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt
|
||||
[djangorestframework-simplejwt]: https://github.com/davesque/django-rest-framework-simplejwt
|
||||
[hawkrest]: https://github.com/kumar303/hawkrest
|
||||
[djangorestframework-httpsignature]: https://github.com/etoccalino/django-rest-framework-httpsignature
|
||||
[djoser]: https://github.com/sunscrapers/djoser
|
||||
[drf-any-permissions]: https://github.com/kevin-brown/drf-any-permissions
|
||||
[djangorestframework-composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions
|
||||
[rest-condition]: https://github.com/caxap/rest_condition
|
||||
[django-rest-framework-mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine
|
||||
[djangorestframework-gis]: https://github.com/djangonauts/django-rest-framework-gis
|
||||
[djangorestframework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore
|
||||
[drf-compound-fields]: https://github.com/estebistec/drf-compound-fields
|
||||
[drf-extra-fields]: https://github.com/Hipo/drf-extra-fields
|
||||
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
|
||||
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
|
||||
[wq.db.rest]: https://wq.io/docs/about-rest
|
||||
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
|
||||
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
|
||||
[nested-multipart-parser]: https://github.com/remigermain/nested-multipart-parser
|
||||
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
|
||||
[drf_ujson2]: https://github.com/Amertz08/drf_ujson2
|
||||
[rest-pandas]: https://github.com/wq/django-rest-pandas
|
||||
[djangorestframework-rapidjson]: https://github.com/allisson/django-rest-framework-rapidjson
|
||||
[djangorestframework-chain]: https://github.com/philipn/django-rest-framework-chain
|
||||
[djangorestrelationalhyperlink]: https://github.com/fredkingham/django_rest_model_hyperlink_serializers_project
|
||||
[django-rest-framework-proxy]: https://github.com/eofs/django-rest-framework-proxy
|
||||
[gaiarestframework]: https://github.com/AppsFuel/gaiarestframework
|
||||
[drf-extensions]: https://github.com/chibisov/drf-extensions
|
||||
[ember-django-adapter]: https://github.com/dustinfarris/ember-django-adapter
|
||||
[dj-rest-auth]: https://github.com/iMerica/dj-rest-auth
|
||||
[django-versatileimagefield]: https://github.com/WGBH/django-versatileimagefield
|
||||
[django-versatileimagefield-drf-docs]:https://django-versatileimagefield.readthedocs.io/en/latest/drf_integration.html
|
||||
[drf-tracking]: https://github.com/aschn/drf-tracking
|
||||
[django-rest-framework-braces]: https://github.com/dealertrack/django-rest-framework-braces
|
||||
[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
|
||||
[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
|
||||
[html-json-forms]: https://github.com/wq/html-json-forms
|
||||
[django-rest-messaging]: https://github.com/raphaelgyory/django-rest-messaging
|
||||
[django-rest-messaging-centrifugo]: https://github.com/raphaelgyory/django-rest-messaging-centrifugo
|
||||
[django-rest-messaging-js]: https://github.com/raphaelgyory/django-rest-messaging-js
|
||||
[drf_tweaks]: https://github.com/ArabellaTech/drf_tweaks
|
||||
[drf-oidc-auth]: https://github.com/ByteInternet/drf-oidc-auth
|
||||
[drf-serializer-extensions]: https://github.com/evenicoulddoit/django-rest-framework-serializer-extensions
|
||||
[djangorestframework-queryfields]: https://github.com/wimglenn/djangorestframework-queryfields
|
||||
[drfpasswordless]: https://github.com/aaronn/django-rest-framework-passwordless
|
||||
[djangorest-alchemy]: https://github.com/dealertrack/djangorest-alchemy
|
||||
[djangorestframework-datatables]: https://github.com/izimobil/django-rest-framework-datatables
|
||||
[django-rest-framework-condition]: https://github.com/jozo/django-rest-framework-condition
|
||||
[django-rest-witchcraft]: https://github.com/shosca/django-rest-witchcraft
|
||||
[drf-access-policy]: https://github.com/rsinger86/drf-access-policy
|
||||
[drf-flex-fields]: https://github.com/rsinger86/drf-flex-fields
|
||||
[drf-typed-views]: https://github.com/rsinger86/drf-typed-views
|
||||
[drf-action-serializer]: https://github.com/gregschmit/drf-action-serializer
|
||||
[djangorestframework-dataclasses]: https://github.com/oxan/djangorestframework-dataclasses
|
||||
[django-restql]: https://github.com/yezyilomo/django-restql
|
||||
[djangorestframework-mvt]: https://github.com/corteva/djangorestframework-mvt
|
||||
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
|
||||
[drf-viewset-profiler]: https://github.com/fvlima/drf-viewset-profiler
|
||||
[djangorestframework-features]: https://github.com/cloudcode-hungary/django-rest-framework-features/
|
||||
[django-elasticsearch-dsl-drf]: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf
|
||||
[django-api-client]: https://github.com/rhenter/django-api-client
|
||||
[drf-psq]: https://github.com/drf-psq/drf-psq
|
||||
[django-rest-authemail]: https://github.com/celiao/django-rest-authemail
|
||||
[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
|
||||
[drf-api-action]: https://github.com/Ori-Roza/drf-api-action
|
||||
[drf-restwind]: https://github.com/youzarsiph/drf-restwind
|
||||
[drf-redesign]: https://github.com/youzarsiph/drf-redesign
|
||||
[drf-material]: https://github.com/youzarsiph/drf-material
|
||||
[django-pyoidc]: https://github.com/makinacorpus/django_pyoidc
|
|
@ -1,140 +0,0 @@
|
|||
# Tutorials and Resources
|
||||
|
||||
There are a wide range of resources available for learning and using Django REST framework. We try to keep a comprehensive list available here.
|
||||
|
||||
## Books
|
||||
|
||||
<div class="book-covers">
|
||||
<a class="book-cover" href="https://hellowebapp.com/order/">
|
||||
<img src="../../img/books/hwa-cover.png"/>
|
||||
</a>
|
||||
<a class="book-cover" href="https://www.twoscoopspress.com/products/two-scoops-of-django-1-11">
|
||||
<img src="../../img/books/tsd-cover.png"/>
|
||||
</a>
|
||||
<a class="book-cover" href="https://djangoforapis.com">
|
||||
<img src="../../img/books/dfa-40-cover.jpg"/>
|
||||
</a>
|
||||
<a class="book-cover" href="https://books.agiliq.com/projects/django-api-polls-tutorial/en/latest/">
|
||||
<img src="../../img/books/bda-cover.png"/>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Courses
|
||||
|
||||
* [Developing RESTful APIs with Django REST Framework][developing-restful-apis-with-django-rest-framework]
|
||||
|
||||
## Tutorials
|
||||
|
||||
* [Beginner's Guide to the Django REST Framework][beginners-guide-to-the-django-rest-framework]
|
||||
* [Django REST Framework - An Introduction][drf-an-intro]
|
||||
* [Django REST Framework Tutorial][drf-tutorial]
|
||||
* [Building a RESTful API with Django REST Framework][building-a-restful-api-with-drf]
|
||||
* [Getting Started with Django REST Framework and AngularJS][getting-started-with-django-rest-framework-and-angularjs]
|
||||
* [End to End Web App with Django REST Framework & AngularJS][end-to-end-web-app-with-django-rest-framework-angularjs]
|
||||
* [Start Your API - Django REST Framework Part 1][start-your-api-django-rest-framework-part-1]
|
||||
* [Permissions & Authentication - Django REST Framework Part 2][permissions-authentication-django-rest-framework-part-2]
|
||||
* [ViewSets and Routers - Django REST Framework Part 3][viewsets-and-routers-django-rest-framework-part-3]
|
||||
* [Django REST Framework User Endpoint][django-rest-framework-user-endpoint]
|
||||
* [Check Credentials Using Django REST Framework][check-credentials-using-django-rest-framework]
|
||||
* [Creating a Production Ready API with Python and Django REST Framework – Part 1][creating-a-production-ready-api-with-python-and-drf-part1]
|
||||
* [Creating a Production Ready API with Python and Django REST Framework – Part 2][creating-a-production-ready-api-with-python-and-drf-part2]
|
||||
* [Creating a Production Ready API with Python and Django REST Framework – Part 3][creating-a-production-ready-api-with-python-and-drf-part3]
|
||||
* [Creating a Production Ready API with Python and Django REST Framework – Part 4][creating-a-production-ready-api-with-python-and-drf-part4]
|
||||
* [Django Polls Tutorial API][django-polls-api]
|
||||
* [Django REST Framework Tutorial: Todo API][django-rest-framework-todo-api]
|
||||
* [Tutorial: Django REST with React (Django 2.0)][django-rest-react-valentinog]
|
||||
|
||||
|
||||
## Videos
|
||||
|
||||
### Talks
|
||||
|
||||
* [Level Up! Rethinking the Web API Framework][pycon-us-2017]
|
||||
* [How to Make a Full Fledged REST API with Django OAuth Toolkit][full-fledged-rest-api-with-django-oauth-toolkit]
|
||||
* [Django REST API - So Easy You Can Learn It in 25 Minutes][django-rest-api-so-easy]
|
||||
* [Tom Christie about Django Rest Framework at Django: Under The Hood][django-under-hood-2014]
|
||||
* [Django REST Framework: Schemas, Hypermedia & Client Libraries][pycon-uk-2016]
|
||||
* [Finally Understand Authentication in Django REST Framework][django-con-2018]
|
||||
|
||||
### Tutorials
|
||||
|
||||
|
||||
* [Django REST Framework Part 1][django-rest-framework-part-1-video]
|
||||
* [Django REST Framework in Your PJ's!][drf-in-your-pjs]
|
||||
* [Building a REST API Using Django & Django REST Framework][building-a-rest-api-using-django-and-drf]
|
||||
* [Blog API with Django REST Framework][blog-api-with-drf]
|
||||
* [Ember and Django Part 1][ember-and-django-part 1-video]
|
||||
* [Django REST Framework Image Upload Tutorial (with AngularJS)][drf-image-upload-tutorial-with-angularjs]
|
||||
* [Django REST Framework Tutorials][drf-tutorials]
|
||||
|
||||
|
||||
## Articles
|
||||
|
||||
* [Web API performance: Profiling Django REST Framework][web-api-performance-profiling-django-rest-framework]
|
||||
* [API Development with Django and Django REST Framework][api-development-with-django-and-django-rest-framework]
|
||||
* [Integrating Pandas, Django REST Framework and Bokeh][integrating-pandas-drf-and-bokeh]
|
||||
* [Controlling Uncertainty on Web Applications and APIs][controlling-uncertainty-on-web-apps-and-apis]
|
||||
* [Full Text Search in Django REST Framework with Database Backends][full-text-search-in-drf]
|
||||
* [OAuth2 Authentication with Django REST Framework and Custom Third-Party OAuth2 Backends][oauth2-authentication-with-drf]
|
||||
* [Nested Resources with Django REST Framework][nested-resources-with-drf]
|
||||
* [Image Fields with Django REST Framework][image-fields-with-drf]
|
||||
* [Chatbot Using Django REST Framework + api.ai + Slack — Part 1/3][chatbot-using-drf-part1]
|
||||
* [New Django Admin with DRF and EmberJS... What are the News?][new-django-admin-with-drf-and-emberjs]
|
||||
* [Blog posts about Django REST Framework][medium-django-rest-framework]
|
||||
* [Implementing Rest APIs With Embedded Privacy][doordash-implementing-rest-apis]
|
||||
|
||||
### Documentations
|
||||
* [Classy Django REST Framework][cdrf.co]
|
||||
* [DRF-schema-adapter][drf-schema]
|
||||
|
||||
Want your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please [submit a pull request][submit-pr] or [email us][anna-email]!
|
||||
|
||||
|
||||
[beginners-guide-to-the-django-rest-framework]: https://code.tutsplus.com/tutorials/beginners-guide-to-the-django-rest-framework--cms-19786
|
||||
[getting-started-with-django-rest-framework-and-angularjs]: https://blog.kevinastone.com/django-rest-framework-and-angular-js
|
||||
[end-to-end-web-app-with-django-rest-framework-angularjs]: https://mourafiq.com/2013/07/01/end-to-end-web-app-with-django-angular-1.html
|
||||
[start-your-api-django-rest-framework-part-1]: https://www.youtube.com/watch?v=hqo2kk91WpE
|
||||
[permissions-authentication-django-rest-framework-part-2]: https://www.youtube.com/watch?v=R3xvUDUZxGU
|
||||
[viewsets-and-routers-django-rest-framework-part-3]: https://www.youtube.com/watch?v=2d6w4DGQ4OU
|
||||
[django-rest-framework-user-endpoint]: https://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/
|
||||
[check-credentials-using-django-rest-framework]: https://richardtier.com/2014/03/06/110/
|
||||
[ember-and-django-part 1-video]: http://www.neckbeardrepublic.com/screencasts/ember-and-django-part-1
|
||||
[django-rest-framework-part-1-video]: http://www.neckbeardrepublic.com/screencasts/django-rest-framework-part-1
|
||||
[web-api-performance-profiling-django-rest-framework]: https://www.dabapps.com/blog/api-performance-profiling-django-rest-framework/
|
||||
[api-development-with-django-and-django-rest-framework]: https://bnotions.com/news-and-insights/api-development-with-django-and-django-rest-framework/
|
||||
[cdrf.co]:http://www.cdrf.co
|
||||
[medium-django-rest-framework]: https://medium.com/django-rest-framework
|
||||
[pycon-uk-2016]: https://www.youtube.com/watch?v=FjmiGh7OqVg
|
||||
[django-under-hood-2014]: https://www.youtube.com/watch?v=3cSsbe-tA0E
|
||||
[integrating-pandas-drf-and-bokeh]: https://web.archive.org/web/20180104205117/http://machinalis.com/blog/pandas-django-rest-framework-bokeh/
|
||||
[controlling-uncertainty-on-web-apps-and-apis]: https://web.archive.org/web/20180104205043/https://machinalis.com/blog/controlling-uncertainty-on-web-applications-and-apis/
|
||||
[full-text-search-in-drf]: https://web.archive.org/web/20180104205059/http://machinalis.com/blog/full-text-search-on-django-rest-framework/
|
||||
[oauth2-authentication-with-drf]: https://web.archive.org/web/20180104205054/http://machinalis.com/blog/oauth2-authentication/
|
||||
[nested-resources-with-drf]: https://web.archive.org/web/20180104205109/http://machinalis.com/blog/nested-resources-with-django/
|
||||
[image-fields-with-drf]: https://web.archive.org/web/20180104205048/http://machinalis.com/blog/image-fields-with-django-rest-framework/
|
||||
[chatbot-using-drf-part1]: https://chatbotslife.com/chatbot-using-django-rest-framework-api-ai-slack-part-1-3-69c7e38b7b1e#.g2aceuncf
|
||||
[new-django-admin-with-drf-and-emberjs]: https://blog.levit.be/new-django-admin-with-emberjs-what-are-the-news/
|
||||
[drf-schema]: https://drf-schema-adapter.readthedocs.io/en/latest/
|
||||
[creating-a-production-ready-api-with-python-and-drf-part1]: https://www.andreagrandi.it/posts/creating-production-ready-api-python-django-rest-framework-part-1/
|
||||
[creating-a-production-ready-api-with-python-and-drf-part2]: https://www.andreagrandi.it/posts/creating-a-production-ready-api-with-python-and-django-rest-framework-part-2/
|
||||
[creating-a-production-ready-api-with-python-and-drf-part3]: https://www.andreagrandi.it/posts/creating-a-production-ready-api-with-python-and-django-rest-framework-part-3/
|
||||
[creating-a-production-ready-api-with-python-and-drf-part4]: https://www.andreagrandi.it/posts/creating-a-production-ready-api-with-python-and-django-rest-framework-part-4/
|
||||
[django-polls-api]: https://learndjango.com/tutorials/django-polls-tutorial-api
|
||||
[django-rest-framework-todo-api]: https://learndjango.com/tutorials/django-rest-framework-tutorial-todo-api
|
||||
[django-rest-api-so-easy]: https://www.youtube.com/watch?v=cqP758k1BaQ
|
||||
[full-fledged-rest-api-with-django-oauth-toolkit]: https://www.youtube.com/watch?v=M6Ud3qC2tTk
|
||||
[drf-in-your-pjs]: https://www.youtube.com/watch?v=xMtHsWa72Ww
|
||||
[building-a-rest-api-using-django-and-drf]: https://www.youtube.com/watch?v=PwssEec3IRw
|
||||
[drf-tutorials]: https://www.youtube.com/watch?v=axRCBgbOJp8&list=PLJtp8Jm8EDzjgVg9vVyIUMoGyqtegj7FH
|
||||
[drf-image-upload-tutorial-with-angularjs]: https://www.youtube.com/watch?v=hMiNTCIY7dw&list=PLUe5s-xycYk_X0vDjYBmKuIya2a2myF8O
|
||||
[blog-api-with-drf]: https://www.youtube.com/watch?v=XMu0T6L2KRQ&list=PLEsfXFp6DpzTOcOVdZF-th7BS_GYGguAS
|
||||
[drf-an-intro]: https://realpython.com/blog/python/django-rest-framework-quick-start/
|
||||
[drf-tutorial]: https://tests4geeks.com/django-rest-framework-tutorial/
|
||||
[building-a-restful-api-with-drf]: https://agiliq.com/blog/2014/12/building-a-restful-api-with-django-rest-framework/
|
||||
[submit-pr]: https://github.com/encode/django-rest-framework
|
||||
[anna-email]: mailto:anna@django-rest-framework.org
|
||||
[pycon-us-2017]: https://www.youtube.com/watch?v=Rk6MHZdust4
|
||||
[django-rest-react-valentinog]: https://www.valentinog.com/blog/tutorial-api-django-rest-react/
|
||||
[doordash-implementing-rest-apis]: https://doordash.engineering/2013/10/07/implementing-rest-apis-with-embedded-privacy/
|
||||
[developing-restful-apis-with-django-rest-framework]: https://testdriven.io/courses/django-rest-framework/
|
||||
[django-con-2018]: https://youtu.be/pY-oje5b5Qk?si=AOU6tLi0IL1_pVzq
|
2
docs_theme/css/bootstrap-responsive.css → docs/css/bootstrap-responsive.css
vendored
Normal file → Executable file
|
@ -3,7 +3,7 @@
|
|||
*
|
||||
* Copyright 2012 Twitter, Inc
|
||||
* Licensed under the Apache License v2.0
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Designed and built with all the love in the world @twitter by @mdo and @fat.
|
||||
*/
|
2
docs_theme/css/bootstrap.css → docs/css/bootstrap.css
vendored
Normal file → Executable file
|
@ -3,7 +3,7 @@
|
|||
*
|
||||
* Copyright 2012 Twitter, Inc
|
||||
* Licensed under the Apache License v2.0
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Designed and built with all the love in the world @twitter by @mdo and @fat.
|
||||
*/
|
|
@ -5,12 +5,11 @@ pre {
|
|||
}
|
||||
|
||||
.dropdown .dropdown-menu {
|
||||
display: none;
|
||||
overflow-y: auto;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.dropdown.open .dropdown-menu {
|
||||
display: block;
|
||||
display: block;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
|
@ -26,22 +25,18 @@ pre {
|
|||
margin-top: 9px;
|
||||
}
|
||||
|
||||
body.index-page #main-content p.badges {
|
||||
padding-bottom: 1px;
|
||||
}
|
||||
|
||||
/* GitHub 'Star' badge */
|
||||
body.index-page #main-content iframe.github-star-button {
|
||||
body.index-page #main-content iframe {
|
||||
float: right;
|
||||
margin-top: -12px;
|
||||
margin-right: -15px;
|
||||
}
|
||||
|
||||
/* CI and PyPI badge */
|
||||
body.index-page #main-content img.status-badge {
|
||||
/* Travis CI badge */
|
||||
body.index-page #main-content p:first-of-type {
|
||||
float: right;
|
||||
margin-right: 8px;
|
||||
margin-top: -11px;
|
||||
margin-top: -14px;
|
||||
margin-bottom: 0px;
|
||||
}
|
||||
|
||||
|
@ -74,12 +69,6 @@ pre {
|
|||
white-space: pre;
|
||||
}
|
||||
|
||||
code, pre {
|
||||
font-family: Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,sans-serif;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
|
||||
/* Preserve the spacing of the navbar across different screen sizes. */
|
||||
.navbar-inner {
|
||||
/*padding: 5px 0;*/
|
||||
|
@ -103,10 +92,6 @@ code, pre {
|
|||
overflow: hidden;
|
||||
}
|
||||
|
||||
.nav-list > li > a {
|
||||
padding: 2px 15px 3px;
|
||||
}
|
||||
|
||||
/* Set the table of contents to static so it flows back into the content when
|
||||
viewed on tablets and smaller. */
|
||||
@media (max-width: 767px) {
|
||||
|
@ -166,40 +151,11 @@ body, .navbar .navbar-inner .container-fluid{
|
|||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* Replacement for `body { background-attachment: fixed; }`, which
|
||||
has performance issues when scrolling on large displays. */
|
||||
body::before {
|
||||
content: ' ';
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
top: 0;
|
||||
left: 0;
|
||||
background-color: #f8f8f8;
|
||||
background: url(../img/grid.png) repeat-x;
|
||||
will-change: transform;
|
||||
z-index: -1;
|
||||
body{
|
||||
background: url("../img/grid.png") repeat-x;
|
||||
background-attachment: fixed;
|
||||
}
|
||||
|
||||
|
||||
#main-content h1:first-of-type {
|
||||
margin-top: 0
|
||||
}
|
||||
|
||||
#main-content h1, #main-content h2 {
|
||||
font-weight: 300;
|
||||
margin-top: 20px
|
||||
}
|
||||
|
||||
#main-content h3, #main-content h4, #main-content h5 {
|
||||
font-weight: 300;
|
||||
margin-top: 15px
|
||||
}
|
||||
|
||||
#main-content img {
|
||||
display: block;
|
||||
margin: 40px auto;
|
||||
}
|
||||
/* custom navigation styles */
|
||||
|
||||
.navbar .navbar-inner{
|
||||
|
@ -210,7 +166,7 @@ body::before {
|
|||
}
|
||||
|
||||
.navbar .navbar-inner .nav li, .navbar .navbar-inner .nav li a, .navbar .navbar-inner .brand{
|
||||
color: white;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.nav-list > .active > a, .navbar .navbar-inner .nav li a:hover {
|
||||
|
@ -219,20 +175,8 @@ body::before {
|
|||
}
|
||||
|
||||
.navbar .navbar-inner .dropdown-menu li a, .navbar .navbar-inner .dropdown-menu li{
|
||||
color: #A30000;
|
||||
color: #A30000;
|
||||
}
|
||||
|
||||
.dropdown-menu .active > a,
|
||||
.dropdown-menu .active > a:hover {
|
||||
background-image: none;
|
||||
}
|
||||
|
||||
.navbar-inverse .nav .dropdown .active > a,
|
||||
.navbar-inverse .nav .dropdown .active > a:hover,
|
||||
.navbar-inverse .nav .dropdown .active > a:focus {
|
||||
background-color: #eeeeee;
|
||||
}
|
||||
|
||||
.navbar .navbar-inner .dropdown-menu li a:hover{
|
||||
background: #eeeeee;
|
||||
color: #c20000;
|
||||
|
@ -268,10 +212,6 @@ body a:hover{
|
|||
}
|
||||
}
|
||||
|
||||
h1 code, h2 code, h3 code, h4 code, h5 code {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
/* sticky footer and footer */
|
||||
html, body {
|
||||
height: 100%;
|
||||
|
@ -326,130 +266,3 @@ footer a {
|
|||
footer a:hover {
|
||||
color: gray;
|
||||
}
|
||||
|
||||
.btn-inverse {
|
||||
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#606060), to(#404040)) !important;
|
||||
background-image: -webkit-linear-gradient(top, #606060, #404040) !important;
|
||||
}
|
||||
|
||||
.modal-open .modal,.btn:focus{outline:none;}
|
||||
|
||||
@media (max-width: 650px) {
|
||||
.repo-link.btn-inverse {display: none;}
|
||||
}
|
||||
|
||||
td, th {
|
||||
padding: 0.25em;
|
||||
background-color: #f7f7f9;
|
||||
border-color: #e1e1e8;
|
||||
}
|
||||
|
||||
table {
|
||||
border-color: white;
|
||||
margin-bottom: 0.6em;
|
||||
}
|
||||
|
||||
.side-nav {
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
|
||||
ul.sponsor.diamond li a {
|
||||
float: left;
|
||||
width: 600px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 70px;
|
||||
padding: 300px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 600px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 200%;
|
||||
}
|
||||
|
||||
@media (max-width: 1000px) {
|
||||
ul.sponsor.diamond li a {
|
||||
float: left;
|
||||
width: 300px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 40px;
|
||||
padding: 300px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 280px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 150%;
|
||||
}
|
||||
}
|
||||
|
||||
ul.sponsor.platinum li a {
|
||||
float: left;
|
||||
width: 300px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 40px;
|
||||
padding: 300px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 280px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 150%;
|
||||
}
|
||||
|
||||
ul.sponsor.gold 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%;
|
||||
}
|
||||
|
||||
ul.sponsor.silver 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%;
|
||||
}
|
||||
|
||||
ul.sponsor {
|
||||
list-style: none;
|
||||
display: block;
|
||||
}
|
||||
|
||||
#mkdocs_search_modal article p{
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
.toclink {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.book-cover img {
|
||||
margin: 0 !important;
|
||||
display: inline-block !important;
|
||||
}
|
||||
|
||||
/* admonition */
|
||||
.admonition {
|
||||
border: .075rem solid #448aff;
|
||||
border-radius: .2rem;
|
||||
margin: 1.5625em 0;
|
||||
padding: 0 .6rem;
|
||||
}
|
||||
.admonition-title {
|
||||
background: #448aff1a;
|
||||
font-weight: 700;
|
||||
margin: 0 -.6rem 1em;
|
||||
padding: 0.4rem 0.6rem;
|
||||
}
|
||||
|
Before Width: | Height: | Size: 55 KiB |
Before Width: | Height: | Size: 5.4 MiB |
Before Width: | Height: | Size: 158 KiB |
Before Width: | Height: | Size: 42 KiB |
Before Width: | Height: | Size: 46 KiB |
Before Width: | Height: | Size: 755 KiB |
Before Width: | Height: | Size: 49 KiB |
Before Width: | Height: | Size: 30 KiB |
Before Width: | Height: | Size: 116 KiB |
Before Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 61 KiB |
Before Width: | Height: | Size: 20 KiB |
Before Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 81 KiB |
Before Width: | Height: | Size: 121 KiB |
Before Width: | Height: | Size: 123 KiB |
Before Width: | Height: | Size: 82 KiB |
Before Width: | Height: | Size: 118 KiB |
Before Width: | Height: | Size: 127 KiB |
Before Width: | Height: | Size: 76 KiB |
Before Width: | Height: | Size: 99 KiB |
Before Width: | Height: | Size: 100 KiB |
Before Width: | Height: | Size: 58 KiB |
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 2.2 KiB |
Before Width: | Height: | Size: 47 KiB |