pull form master
|
@ -1,7 +0,0 @@
|
|||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
1
.github/FUNDING.yml
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
custom: https://fund.django-rest-framework.org/topics/funding/
|
1
.gitignore
vendored
|
@ -13,7 +13,6 @@
|
|||
MANIFEST
|
||||
coverage.*
|
||||
|
||||
!.editorconfig
|
||||
!.gitignore
|
||||
!.travis.yml
|
||||
!.isort.cfg
|
||||
|
|
|
@ -1,7 +0,0 @@
|
|||
[settings]
|
||||
skip=.tox
|
||||
atomic=true
|
||||
multi_line_output=5
|
||||
known_standard_library=types
|
||||
known_third_party=pytest,_pytest,django
|
||||
known_first_party=rest_framework
|
56
.travis.yml
|
@ -1,41 +1,45 @@
|
|||
language: python
|
||||
cache: pip
|
||||
|
||||
python:
|
||||
- "2.7"
|
||||
- "3.4"
|
||||
- "3.5"
|
||||
|
||||
sudo: false
|
||||
|
||||
env:
|
||||
- DJANGO=1.10
|
||||
- DJANGO=1.11
|
||||
- DJANGO=2.0
|
||||
- DJANGO=master
|
||||
|
||||
dist: xenial
|
||||
matrix:
|
||||
fast_finish: true
|
||||
include:
|
||||
- { python: "3.6", env: DJANGO=master }
|
||||
|
||||
- { python: "3.5", env: DJANGO=1.11 }
|
||||
- { python: "3.5", env: DJANGO=2.0 }
|
||||
- { python: "3.5", env: DJANGO=2.1 }
|
||||
- { python: "3.5", env: DJANGO=2.2 }
|
||||
|
||||
- { python: "3.6", env: DJANGO=1.11 }
|
||||
- { python: "3.6", env: DJANGO=2.0 }
|
||||
- { python: "2.7", env: TOXENV=lint }
|
||||
- { python: "2.7", env: TOXENV=docs }
|
||||
- python: "2.7"
|
||||
env: TOXENV=readme
|
||||
addons:
|
||||
apt_packages: pandoc
|
||||
exclude:
|
||||
- { python: "2.7", env: DJANGO=master }
|
||||
- { python: "2.7", env: DJANGO=2.0 }
|
||||
- { python: "3.4", env: DJANGO=master }
|
||||
- { python: "3.6", env: DJANGO=2.1 }
|
||||
- { python: "3.6", env: DJANGO=2.2 }
|
||||
- { python: "3.6", env: DJANGO=master }
|
||||
|
||||
- { python: "3.7", env: DJANGO=2.0 }
|
||||
- { python: "3.7", env: DJANGO=2.1 }
|
||||
- { python: "3.7", env: DJANGO=2.2 }
|
||||
- { python: "3.7", env: DJANGO=master }
|
||||
|
||||
- { python: "3.8", env: DJANGO=master }
|
||||
|
||||
- { python: "3.8", env: TOXENV=base }
|
||||
- { python: "3.8", env: TOXENV=lint }
|
||||
- { python: "3.8", env: TOXENV=docs }
|
||||
|
||||
- python: "3.8"
|
||||
env: TOXENV=dist
|
||||
script:
|
||||
- python setup.py bdist_wheel
|
||||
- rm -r djangorestframework.egg-info # see #6139
|
||||
- tox --installpkg ./dist/djangorestframework-*.whl
|
||||
- tox # test sdist
|
||||
|
||||
allow_failures:
|
||||
- env: DJANGO=master
|
||||
|
||||
install:
|
||||
- pip install tox tox-travis
|
||||
- pip install tox tox-venv tox-travis
|
||||
|
||||
script:
|
||||
- tox
|
||||
|
|
|
@ -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
|
|
@ -20,7 +20,7 @@ When answering questions make sure to help future contributors find their way ar
|
|||
|
||||
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.
|
||||
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. (e.g. 'Hey folks,')
|
||||
|
||||
The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines for participating in community forums.
|
||||
|
||||
|
@ -50,7 +50,7 @@ Getting involved in triaging incoming issues is a good way to start contributing
|
|||
|
||||
To start developing on Django REST framework, clone the repo:
|
||||
|
||||
git clone git@github.com:encode/django-rest-framework.git
|
||||
git clone https://github.com/encode/django-rest-framework
|
||||
|
||||
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.
|
||||
|
||||
|
@ -59,7 +59,7 @@ Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recom
|
|||
To run the tests, clone the repository, and then:
|
||||
|
||||
# Setup the virtual environment
|
||||
virtualenv env
|
||||
python3 -m venv env
|
||||
source env/bin/activate
|
||||
pip install django
|
||||
pip install -r requirements.txt
|
||||
|
@ -115,7 +115,7 @@ It's also useful to remember that if you have an outstanding pull request then p
|
|||
|
||||
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 with both Python 2 and Python 3, and that they run properly on all supported versions of Django.
|
||||
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 Travis build status in the GitHub interface and make sure the tests are running as you'd expect.
|
||||
|
||||
|
@ -194,14 +194,14 @@ If you want to draw attention to a note or warning, use a pair of enclosing line
|
|||
---
|
||||
|
||||
|
||||
[cite]: http://www.w3.org/People/Berners-Lee/FAQ.html
|
||||
[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]: http://stackexchange.com/filters/66475/rest-framework
|
||||
[so-filter]: https://stackexchange.com/filters/66475/rest-framework
|
||||
[issues]: https://github.com/encode/django-rest-framework/issues?state=open
|
||||
[pep-8]: http://www.python.org/dev/peps/pep-0008/
|
||||
[pep-8]: https://www.python.org/dev/peps/pep-0008/
|
||||
[pull-requests]: https://help.github.com/articles/using-pull-requests
|
||||
[tox]: https://tox.readthedocs.io/en/latest/
|
||||
[markdown]: http://daringfireball.net/projects/markdown/basics
|
||||
[markdown]: https://daringfireball.net/projects/markdown/basics
|
||||
[docs]: https://github.com/encode/django-rest-framework/tree/master/docs
|
||||
[mou]: http://mouapp.com/
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
- [ ] I have verified that that issue exists against the `master` branch of Django REST framework.
|
||||
- [ ] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
|
||||
- [ ] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
|
||||
- [ ] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
|
||||
- [ ] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
|
||||
- [ ] I have reduced the issue to the simplest possible case.
|
||||
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
|
||||
|
||||
|
|
15
LICENSE.md
|
@ -1,16 +1,21 @@
|
|||
# License
|
||||
|
||||
Copyright (c) 2011-2017, Tom Christie
|
||||
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
|
||||
* 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.
|
||||
|
||||
* 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
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
include README.md
|
||||
include LICENSE.md
|
||||
recursive-include rest_framework/static *.js *.css *.png *.eot *.svg *.ttf *.woff
|
||||
recursive-include rest_framework/static *.js *.css *.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]
|
||||
|
|
89
README.md
|
@ -3,11 +3,10 @@
|
|||
[![build-status-image]][travis]
|
||||
[![coverage-status-image]][codecov]
|
||||
[![pypi-version]][pypi]
|
||||
[](https://gitter.im/tomchristie/django-rest-framework?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
||||
|
||||
**Awesome web-browsable Web APIs.**
|
||||
|
||||
Full documentation for the project is available at [http://www.django-rest-framework.org][docs].
|
||||
Full documentation for the project is available at [https://www.django-rest-framework.org/][docs].
|
||||
|
||||
---
|
||||
|
||||
|
@ -20,13 +19,16 @@ 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.*
|
||||
|
||||
[![][rover-img]][rover-url]
|
||||
[![][sentry-img]][sentry-url]
|
||||
[![][stream-img]][stream-url]
|
||||
[![][machinalis-img]][machinalis-url]
|
||||
[![][rollbar-img]][rollbar-url]
|
||||
[![][cadre-img]][cadre-url]
|
||||
[![][kloudless-img]][kloudless-url]
|
||||
[![][esg-img]][esg-url]
|
||||
[![][lightson-img]][lightson-url]
|
||||
[![][retool-img]][retool-url]
|
||||
|
||||
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Rover][rover-url], [Sentry][sentry-url], [Stream][stream-url], [Machinalis][machinalis-url], and [Rollbar][rollbar-url].
|
||||
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Rollbar][rollbar-url], [Cadre][cadre-url], [Kloudless][kloudless-url], [ESG][esg-url], [Lights On Software][lightson-url], and [Retool][retool-url].
|
||||
|
||||
---
|
||||
|
||||
|
@ -52,8 +54,11 @@ There is a live example API for testing purposes, [available here][sandbox].
|
|||
|
||||
# Requirements
|
||||
|
||||
* Python (2.7, 3.4, 3.5, 3.6)
|
||||
* Django (1.10, 1.11, 2.0rc1)
|
||||
* Python (3.5, 3.6, 3.7)
|
||||
* Django (1.11, 2.0, 2.1, 2.2)
|
||||
|
||||
We **highly recommend** and only officially support the latest patch release of
|
||||
each Python and Django series.
|
||||
|
||||
# Installation
|
||||
|
||||
|
@ -63,10 +68,10 @@ Install using `pip`...
|
|||
|
||||
Add `'rest_framework'` to your `INSTALLED_APPS` setting.
|
||||
|
||||
INSTALLED_APPS = (
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
)
|
||||
]
|
||||
|
||||
# Example
|
||||
|
||||
|
@ -76,7 +81,7 @@ Startup up a new project like so...
|
|||
|
||||
pip install django
|
||||
pip install djangorestframework
|
||||
django-admin.py startproject example .
|
||||
django-admin startproject example .
|
||||
./manage.py migrate
|
||||
./manage.py createsuperuser
|
||||
|
||||
|
@ -92,7 +97,7 @@ from rest_framework import serializers, viewsets, routers
|
|||
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ('url', 'username', 'email', 'is_staff')
|
||||
fields = ['url', 'username', 'email', 'is_staff']
|
||||
|
||||
|
||||
# ViewSets define the view behavior.
|
||||
|
@ -119,10 +124,10 @@ We'd also like to configure a couple of settings for our API.
|
|||
Add the following to your `settings.py` module:
|
||||
|
||||
```python
|
||||
INSTALLED_APPS = (
|
||||
INSTALLED_APPS = [
|
||||
... # Make sure to include the default installed apps here.
|
||||
'rest_framework',
|
||||
)
|
||||
]
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
# Use Django's standard `django.contrib.auth` permissions,
|
||||
|
@ -139,7 +144,7 @@ That's it, we're done!
|
|||
|
||||
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.
|
||||
|
||||
You can also interact with the API using command line tools such as [`curl`](http://curl.haxx.se/). For example, to list the users endpoint:
|
||||
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:
|
||||
|
||||
$ curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
|
||||
[
|
||||
|
@ -163,7 +168,7 @@ Or to create a new user:
|
|||
|
||||
# Documentation & Support
|
||||
|
||||
Full documentation for the project is available at [http://www.django-rest-framework.org][docs].
|
||||
Full documentation for the project is available at [https://www.django-rest-framework.org/][docs].
|
||||
|
||||
For questions and support, use the [REST framework discussion group][group], or `#restframework` on freenode IRC.
|
||||
|
||||
|
@ -171,19 +176,17 @@ You may also want to [follow the author on Twitter][twitter].
|
|||
|
||||
# Security
|
||||
|
||||
If you believe you've found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**.
|
||||
|
||||
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
Please see the [security policy][security-policy].
|
||||
|
||||
[build-status-image]: https://secure.travis-ci.org/encode/django-rest-framework.svg?branch=master
|
||||
[travis]: http://travis-ci.org/encode/django-rest-framework?branch=master
|
||||
[travis]: https://travis-ci.org/encode/django-rest-framework?branch=master
|
||||
[coverage-status-image]: https://img.shields.io/codecov/c/github/encode/django-rest-framework/master.svg
|
||||
[codecov]: http://codecov.io/github/encode/django-rest-framework?branch=master
|
||||
[codecov]: https://codecov.io/github/encode/django-rest-framework?branch=master
|
||||
[pypi-version]: https://img.shields.io/pypi/v/djangorestframework.svg
|
||||
[pypi]: https://pypi.python.org/pypi/djangorestframework
|
||||
[pypi]: https://pypi.org/project/djangorestframework/
|
||||
[twitter]: https://twitter.com/_tomchristie
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[sandbox]: http://restframework.herokuapp.com/
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
|
||||
[funding]: https://fund.django-rest-framework.org/topics/funding/
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
|
@ -191,26 +194,34 @@ Send a description of the issue via email to [rest-framework-security@googlegrou
|
|||
[rover-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/rover-readme.png
|
||||
[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
|
||||
[machinalis-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/machinalis-readme.png
|
||||
[rollbar-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/rollbar-readme.png
|
||||
[cadre-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cadre-readme.png
|
||||
[load-impact-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/load-impact-readme.png
|
||||
[kloudless-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/kloudless-readme.png
|
||||
[esg-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/esg-readme.png
|
||||
[lightson-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/lightson-readme.png
|
||||
[retool-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/retool-readme.png
|
||||
|
||||
[rover-url]: http://jobs.rover.com/
|
||||
[sentry-url]: https://getsentry.com/welcome/
|
||||
[stream-url]: https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf
|
||||
[machinalis-url]: https://hello.machinalis.co.uk/
|
||||
[rollbar-url]: https://rollbar.com/
|
||||
[rollbar-url]: https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial
|
||||
[cadre-url]: https://cadre.com/
|
||||
[kloudless-url]: https://hubs.ly/H0f30Lf0
|
||||
[esg-url]: https://software.esg-usa.com/
|
||||
[lightson-url]: https://lightsonsoftware.com
|
||||
[retool-url]: https://retool.com/?utm_source=djangorest&utm_medium=sponsorship
|
||||
|
||||
[oauth1-section]: http://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth
|
||||
[oauth2-section]: http://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit
|
||||
[serializer-section]: http://www.django-rest-framework.org/api-guide/serializers/#serializers
|
||||
[modelserializer-section]: http://www.django-rest-framework.org/api-guide/serializers/#modelserializer
|
||||
[functionview-section]: http://www.django-rest-framework.org/api-guide/views/#function-based-views
|
||||
[generic-views]: http://www.django-rest-framework.org/api-guide/generic-views/
|
||||
[viewsets]: http://www.django-rest-framework.org/api-guide/viewsets/
|
||||
[routers]: http://www.django-rest-framework.org/api-guide/routers/
|
||||
[serializers]: http://www.django-rest-framework.org/api-guide/serializers/
|
||||
[authentication]: http://www.django-rest-framework.org/api-guide/authentication/
|
||||
[image]: http://www.django-rest-framework.org/img/quickstart.png
|
||||
[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]: http://www.django-rest-framework.org/
|
||||
[security-mail]: mailto:rest-framework-security@googlegroups.com
|
||||
[docs]: https://www.django-rest-framework.org/
|
||||
[security-policy]: https://github.com/encode/django-rest-framework/security/policy
|
||||
|
|
9
SECURITY.md
Normal file
|
@ -0,0 +1,9 @@
|
|||
# Security Policy
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you believe you've found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**.
|
||||
|
||||
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
|
||||
[security-mail]: mailto:rest-framework-security@googlegroups.com
|
10
codecov.yml
|
@ -1,7 +1,11 @@
|
|||
coverage:
|
||||
precision: 2
|
||||
round: down
|
||||
range: "80...100"
|
||||
|
||||
status:
|
||||
project: false
|
||||
patch: false
|
||||
changes: false
|
||||
project: yes
|
||||
patch: no
|
||||
changes: no
|
||||
|
||||
comment: off
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: authentication.py
|
||||
---
|
||||
source:
|
||||
- authentication.py
|
||||
---
|
||||
|
||||
# Authentication
|
||||
|
||||
|
@ -37,10 +40,10 @@ The value of `request.user` and `request.auth` for unauthenticated requests can
|
|||
The default authentication schemes 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,
|
||||
|
@ -52,8 +55,8 @@ using the `APIView` class-based views.
|
|||
from rest_framework.views import APIView
|
||||
|
||||
class ExampleView(APIView):
|
||||
authentication_classes = (SessionAuthentication, BasicAuthentication)
|
||||
permission_classes = (IsAuthenticated,)
|
||||
authentication_classes = [SessionAuthentication, BasicAuthentication]
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
|
@ -65,8 +68,8 @@ using the `APIView` class-based views.
|
|||
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])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def example_view(request, format=None):
|
||||
content = {
|
||||
'user': unicode(request.user), # `django.contrib.auth.User` instance.
|
||||
|
@ -121,10 +124,10 @@ This authentication scheme uses a simple token-based HTTP Authentication scheme.
|
|||
|
||||
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 = (
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework.authtoken'
|
||||
)
|
||||
]
|
||||
|
||||
---
|
||||
|
||||
|
@ -137,7 +140,7 @@ 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:
|
||||
|
||||
|
@ -205,11 +208,39 @@ 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. If you need a customized version of the `obtain_auth_token` view, you can do so by overriding the `ObtainAuthToken` view class, and using that in your url conf instead.
|
||||
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.
|
||||
|
||||
By default there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
|
||||
and include them using the `throttle_classes` attribute.
|
||||
|
||||
If you need a customized version of the `obtain_auth_token` view, you can do so by subclassing the `ObtainAuthToken` view class, and using that in your url conf instead.
|
||||
|
||||
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 += [
|
||||
url(r'^api-token-auth/', CustomAuthToken.as_view())
|
||||
]
|
||||
|
||||
|
||||
##### With Django admin
|
||||
|
||||
|
@ -219,7 +250,7 @@ It is also possible to create Tokens manually through admin interface. In case y
|
|||
|
||||
from rest_framework.authtoken.admin import TokenAdmin
|
||||
|
||||
TokenAdmin.raw_id_fields = ('user',)
|
||||
TokenAdmin.raw_id_fields = ['user']
|
||||
|
||||
|
||||
#### Using Django manage.py command
|
||||
|
@ -293,13 +324,13 @@ If the `.authenticate_header()` method is not overridden, the authentication sch
|
|||
|
||||
---
|
||||
|
||||
**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` orginates from your custom authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. These errors should be fixed or otherwise handled by your authenticator.
|
||||
**Note:** When your custom authenticator is invoked by the request object's `.user` or `.auth` properties, you may see an `AttributeError` re-raised as a `WrappedAttributeError`. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from your custom authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. These errors should be fixed or otherwise handled by your authenticator.
|
||||
|
||||
---
|
||||
|
||||
## Example
|
||||
|
||||
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.
|
||||
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
|
||||
|
@ -307,7 +338,7 @@ The following example will authenticate any incoming request as the user given b
|
|||
|
||||
class ExampleAuthentication(authentication.BaseAuthentication):
|
||||
def authenticate(self, request):
|
||||
username = request.META.get('X_USERNAME')
|
||||
username = request.META.get('HTTP_X_USERNAME')
|
||||
if not username:
|
||||
return None
|
||||
|
||||
|
@ -326,7 +357,7 @@ The following third party packages are also available.
|
|||
|
||||
## Django OAuth Toolkit
|
||||
|
||||
The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by [Evonove][evonove] 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**.
|
||||
The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by [Evonove][evonove] 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
|
||||
|
||||
|
@ -336,15 +367,15 @@ Install using `pip`.
|
|||
|
||||
Add the package to your `INSTALLED_APPS` and modify your REST framework settings.
|
||||
|
||||
INSTALLED_APPS = (
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'oauth2_provider',
|
||||
)
|
||||
]
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': (
|
||||
'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.
|
||||
|
@ -363,17 +394,9 @@ Install the package using `pip`.
|
|||
|
||||
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].
|
||||
|
||||
## Digest Authentication
|
||||
|
||||
HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. [Juan Riaza][juanriaza] maintains the [djangorestframework-digestauth][djangorestframework-digestauth] package which provides HTTP digest authentication support for REST framework.
|
||||
|
||||
## Django OAuth2 Consumer
|
||||
|
||||
The [Django OAuth2 Consumer][doac] library from [Rediker Software][rediker] is another package that provides [OAuth 2.0 support for REST framework][doac-rest-framework]. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.
|
||||
|
||||
## 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. [Blimp][blimp] maintains the [djangorestframework-jwt][djangorestframework-jwt] package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password. An alternative package for JWT authentication is [djangorestframework-simplejwt][djangorestframework-simplejwt] which provides different features as well as a pluggable token blacklist app.
|
||||
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
|
||||
|
||||
|
@ -381,7 +404,7 @@ The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let y
|
|||
|
||||
## 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] package which provides an easy to use HTTP Signature Authentication mechanism.
|
||||
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
|
||||
|
||||
|
@ -403,43 +426,34 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
|
|||
|
||||
[drfpasswordless][drfpasswordless] adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's own TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.
|
||||
|
||||
[cite]: http://jacobian.org/writing/rest-worst-practices/
|
||||
[http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
|
||||
[http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4
|
||||
[basicauth]: http://tools.ietf.org/html/rfc2617
|
||||
[oauth]: http://oauth.net/2/
|
||||
[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
|
||||
[permission]: permissions.md
|
||||
[throttling]: throttling.md
|
||||
[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax
|
||||
[mod_wsgi_official]: http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization
|
||||
[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]: http://jpadilla.github.io/django-rest-framework-oauth/
|
||||
[django-rest-framework-oauth-authentication]: http://jpadilla.github.io/django-rest-framework-oauth/authentication/
|
||||
[django-rest-framework-oauth-permissions]: http://jpadilla.github.io/django-rest-framework-oauth/permissions/
|
||||
[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]: http://oauth.net/core/1.0a
|
||||
[django-oauth-plus]: http://code.larlet.fr/django-oauth-plus
|
||||
[django-oauth2-provider]: https://github.com/caffeinehit/django-oauth2-provider
|
||||
[django-oauth2-provider-docs]: https://django-oauth2-provider.readthedocs.io/en/latest/
|
||||
[rfc6749]: http://tools.ietf.org/html/rfc6749
|
||||
[oauth-1.0a]: https://oauth.net/core/1.0a/
|
||||
[django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
|
||||
[evonove]: https://github.com/evonove/
|
||||
[oauthlib]: https://github.com/idan/oauthlib
|
||||
[doac]: https://github.com/Rediker-Software/doac
|
||||
[rediker]: https://github.com/Rediker-Software
|
||||
[doac-rest-framework]: https://github.com/Rediker-Software/doac/blob/master/docs/integrations.md#
|
||||
[blimp]: https://github.com/GetBlimp
|
||||
[djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt
|
||||
[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
|
||||
[amazon-http-signature]: http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
|
||||
[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]: http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05
|
||||
[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
|
||||
[django-rest-framework-social-oauth2]: https://github.com/PhilipGarnero/django-rest-framework-social-oauth2
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
# Caching
|
||||
|
||||
> A certain woman had a very sharp conciousness but almost no
|
||||
> A certain woman had a very sharp consciousness but almost no
|
||||
> memory ... She remembered enough to work, and she worked hard.
|
||||
> - Lydia Davis
|
||||
|
||||
|
@ -13,15 +13,20 @@ provided in Django.
|
|||
|
||||
Django provides a [`method_decorator`][decorator] to use
|
||||
decorators with class based views. This can be used with
|
||||
with other cache decorators such as [`cache_page`][page] and
|
||||
other cache decorators such as [`cache_page`][page] and
|
||||
[`vary_on_cookie`][cookie].
|
||||
|
||||
```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
|
||||
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework import viewsets
|
||||
|
||||
class UserViewSet(viewsets.Viewset):
|
||||
|
||||
class UserViewSet(viewsets.ViewSet):
|
||||
|
||||
# Cache requested url for each user for 2 hours
|
||||
@method_decorator(cache_page(60*60*2))
|
||||
|
@ -32,6 +37,7 @@ class UserViewSet(viewsets.Viewset):
|
|||
}
|
||||
return Response(content)
|
||||
|
||||
|
||||
class PostView(APIView):
|
||||
|
||||
# Cache page for the requested url
|
||||
|
@ -47,8 +53,6 @@ class PostView(APIView):
|
|||
**NOTE:** The [`cache_page`][page] decorator only caches the
|
||||
`GET` and `HEAD` responses with status 200.
|
||||
|
||||
|
||||
[django]: https://docs.djangoproject.com/en/dev/topics/cache/
|
||||
[page]: https://docs.djangoproject.com/en/dev/topics/cache/#the-per-view-cache
|
||||
[cookie]: https://docs.djangoproject.com/en/dev/topics/http/decorators/#django.views.decorators.vary.vary_on_cookie
|
||||
[decorator]: https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-the-class
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: negotiation.py
|
||||
---
|
||||
source:
|
||||
- negotiation.py
|
||||
---
|
||||
|
||||
# Content negotiation
|
||||
|
||||
|
@ -6,7 +9,7 @@ source: negotiation.py
|
|||
>
|
||||
> — [RFC 2616][cite], Fielding et al.
|
||||
|
||||
[cite]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html
|
||||
[cite]: https://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.
|
||||
|
||||
|
@ -94,4 +97,4 @@ You can also set the content negotiation used for an individual view, or viewset
|
|||
'accepted media type': request.accepted_renderer.media_type
|
||||
})
|
||||
|
||||
[accept-header]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
|
||||
[accept-header]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: exceptions.py
|
||||
---
|
||||
source:
|
||||
- exceptions.py
|
||||
---
|
||||
|
||||
# Exceptions
|
||||
|
||||
|
@ -230,5 +233,33 @@ The generic views use the `raise_exception=True` flag, which means that you can
|
|||
|
||||
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'
|
||||
|
||||
[cite]: https://doughellmann.com/blog/2009/06/19/python-exception-handling-techniques/
|
||||
[authentication]: authentication.md
|
||||
[django-custom-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: fields.py
|
||||
---
|
||||
source:
|
||||
- fields.py
|
||||
---
|
||||
|
||||
# Serializer fields
|
||||
|
||||
|
@ -41,14 +44,6 @@ Setting this to `False` also allows the object attribute or dictionary key to be
|
|||
|
||||
Defaults to `True`.
|
||||
|
||||
### `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 setting this argument to `True` will imply a default value of `null` for serialization output, but does imply a default for input deserialization.
|
||||
|
||||
Defaults to `False`
|
||||
|
||||
### `default`
|
||||
|
||||
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
|
||||
|
@ -57,10 +52,18 @@ The `default` is not applied during partial update operations. In the partial up
|
|||
|
||||
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 `set_context` method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for [validators](validators.md#using-set_context).
|
||||
|
||||
When serializing the instance, default will be used if the the object attribute or dictionary key is not present in the instance.
|
||||
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.
|
||||
|
@ -124,6 +127,15 @@ 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 behaviour manually,
|
||||
explicitly declare the `BooleanField` on the serializer class, or use the
|
||||
`extra_kwargs` option to set the `required` flag.
|
||||
|
||||
Corresponds to `django.db.models.fields.BooleanField`.
|
||||
|
||||
**Signature:** `BooleanField()`
|
||||
|
@ -200,7 +212,7 @@ A field that ensures the input is a valid UUID string. The `to_internal_value` m
|
|||
**Signature:** `UUIDField(format='hex_verbose')`
|
||||
|
||||
- `format`: Determines the representation format of the uuid value
|
||||
- `'hex_verbose'` - The cannoncical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
- `'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"`
|
||||
|
@ -297,10 +309,11 @@ A date and time representation.
|
|||
|
||||
Corresponds to `django.db.models.fields.DateTimeField`.
|
||||
|
||||
**Signature:** `DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)`
|
||||
**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 `pytz.timezone` 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.
|
||||
|
||||
|
@ -358,7 +371,10 @@ 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()`
|
||||
**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.
|
||||
|
||||
---
|
||||
|
||||
|
@ -435,9 +451,10 @@ Requires either the `Pillow` package or `PIL` package. The `Pillow` package is
|
|||
|
||||
A field class that validates a list of objects.
|
||||
|
||||
**Signature**: `ListField(child=<A_FIELD_INSTANCE>, min_length=None, max_length=None)`
|
||||
**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.
|
||||
|
||||
|
@ -458,9 +475,10 @@ We can now reuse our custom `StringListField` class throughout our application,
|
|||
|
||||
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>)`
|
||||
**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:
|
||||
|
||||
|
@ -471,13 +489,25 @@ 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)`
|
||||
**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`.
|
||||
|
||||
---
|
||||
|
||||
|
@ -496,7 +526,7 @@ For example, if `has_expired` was a property on the `Account` model, then the fo
|
|||
class AccountSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ('id', 'account_name', 'has_expired')
|
||||
fields = ['id', 'account_name', 'has_expired']
|
||||
|
||||
## HiddenField
|
||||
|
||||
|
@ -559,6 +589,8 @@ Note that the `WritableField` class that was present in version 2.x no longer ex
|
|||
|
||||
## Examples
|
||||
|
||||
### A Basic Custom Field
|
||||
|
||||
Let's look at an example of serializing a class that represents an RGB color value:
|
||||
|
||||
class Color(object):
|
||||
|
@ -574,8 +606,8 @@ Let's look at an example of serializing a class that represents an RGB color val
|
|||
"""
|
||||
Color objects are serialized into 'rgb(#, #, #)' notation.
|
||||
"""
|
||||
def to_representation(self, obj):
|
||||
return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue)
|
||||
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(')')
|
||||
|
@ -587,24 +619,24 @@ By default field values are treated as mapping to an attribute on the object. I
|
|||
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, obj):
|
||||
def get_attribute(self, instance):
|
||||
# We pass the object instance onto `to_representation`,
|
||||
# not just the field attribute.
|
||||
return obj
|
||||
return instance
|
||||
|
||||
def to_representation(self, obj):
|
||||
def to_representation(self, value):
|
||||
"""
|
||||
Serialize the object's class name.
|
||||
Serialize the value's class name.
|
||||
"""
|
||||
return obj.__class__.__name__
|
||||
return value.__class__.__name__
|
||||
|
||||
#### Raising validation errors
|
||||
### 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, six.text_type):
|
||||
if not isinstance(data, str):
|
||||
msg = 'Incorrect type. Expected a string, but got %s'
|
||||
raise ValidationError(msg % type(data).__name__)
|
||||
|
||||
|
@ -628,7 +660,7 @@ The `.fail()` method is a shortcut for raising `ValidationError` that takes a me
|
|||
}
|
||||
|
||||
def to_internal_value(self, data):
|
||||
if not isinstance(data, six.text_type):
|
||||
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):
|
||||
|
@ -644,6 +676,137 @@ The `.fail()` method is a shortcut for raising `ValidationError` that takes a me
|
|||
|
||||
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 behaviour 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.
|
||||
|
@ -656,7 +819,7 @@ The [drf-compound-fields][drf-compound-fields] package provides "compound" seria
|
|||
|
||||
The [drf-extra-fields][drf-extra-fields] package provides extra serializer fields for REST framework, including `Base64ImageField` and `PointField` classes.
|
||||
|
||||
## djangrestframework-recursive
|
||||
## djangorestframework-recursive
|
||||
|
||||
the [djangorestframework-recursive][djangorestframework-recursive] package provides a `RecursiveField` for serializing and deserializing recursive structures
|
||||
|
||||
|
@ -671,10 +834,8 @@ The [django-rest-framework-hstore][django-rest-framework-hstore] package provide
|
|||
[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
|
||||
[ecma262]: http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
|
||||
[strftime]: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
|
||||
[django-widgets]: https://docs.djangoproject.com/en/stable/ref/forms/widgets/
|
||||
[iso8601]: http://www.w3.org/TR/NOTE-datetime
|
||||
[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
|
||||
|
@ -682,3 +843,4 @@ The [django-rest-framework-hstore][django-rest-framework-hstore] package provide
|
|||
[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
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: filters.py
|
||||
---
|
||||
source:
|
||||
- filters.py
|
||||
---
|
||||
|
||||
# Filtering
|
||||
|
||||
|
@ -92,7 +95,7 @@ Generic filters can also present themselves as HTML controls in the browsable AP
|
|||
The default filter backends may be set globally, using the `DEFAULT_FILTER_BACKENDS` setting. For example.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
|
||||
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
|
||||
}
|
||||
|
||||
You can also set the filter backends on a per-view, or per-viewset basis,
|
||||
|
@ -106,7 +109,7 @@ using the `GenericAPIView` class-based views.
|
|||
class UserListView(generics.ListAPIView):
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
|
||||
filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
|
||||
|
||||
## Filtering and object lookups
|
||||
|
||||
|
@ -127,7 +130,7 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering
|
|||
"""
|
||||
model = Product
|
||||
serializer_class = ProductSerializer
|
||||
filter_class = ProductFilter
|
||||
filterset_class = ProductFilter
|
||||
|
||||
def get_queryset(self):
|
||||
user = self.request.user
|
||||
|
@ -139,7 +142,7 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering
|
|||
|
||||
## DjangoFilterBackend
|
||||
|
||||
The `django-filter` library includes a `DjangoFilterBackend` class which
|
||||
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`. Then add `django_filters` to Django's `INSTALLED_APPS`
|
||||
|
@ -149,7 +152,7 @@ To use `DjangoFilterBackend`, first install `django-filter`. Then add `django_fi
|
|||
You should now either add the filter backend to your settings:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
|
||||
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
|
||||
}
|
||||
|
||||
Or add the filter backend to an individual View or ViewSet.
|
||||
|
@ -158,15 +161,15 @@ Or add the filter backend to an individual View or ViewSet.
|
|||
|
||||
class UserListView(generics.ListAPIView):
|
||||
...
|
||||
filter_backends = (DjangoFilterBackend,)
|
||||
filter_backends = [DjangoFilterBackend]
|
||||
|
||||
If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against.
|
||||
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,)
|
||||
filter_fields = ('category', 'in_stock')
|
||||
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:
|
||||
|
||||
|
@ -187,11 +190,13 @@ 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')
|
||||
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:
|
||||
|
||||
|
@ -199,7 +204,7 @@ This will allow the client to filter the items in the list by making queries suc
|
|||
|
||||
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')
|
||||
search_fields = ['username', 'email', 'profile__profession']
|
||||
|
||||
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.
|
||||
|
||||
|
@ -212,9 +217,19 @@ The search behavior may be restricted by prepending various characters to the `s
|
|||
|
||||
For example:
|
||||
|
||||
search_fields = ('=username', '=email')
|
||||
search_fields = ['=username', '=email']
|
||||
|
||||
By default, the search parameter is named `'search`', but this may be overridden with the `SEARCH_PARAM` setting.
|
||||
By default, the search parameter is named `'search'`, but this may be overridden with the `SEARCH_PARAM` setting.
|
||||
|
||||
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(CustomSearchFilter, self).get_search_fields(view, request)
|
||||
|
||||
For more details, see the [Django documentation][search-django-admin].
|
||||
|
||||
|
@ -247,8 +262,8 @@ It's recommended that you explicitly specify which fields the API should allowin
|
|||
class UserListView(generics.ListAPIView):
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
filter_backends = (filters.OrderingFilter,)
|
||||
ordering_fields = ('username', 'email')
|
||||
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.
|
||||
|
||||
|
@ -259,7 +274,7 @@ If you are confident that the queryset being used by the view doesn't contain an
|
|||
class BookingsListView(generics.ListAPIView):
|
||||
queryset = Booking.objects.all()
|
||||
serializer_class = BookingSerializer
|
||||
filter_backends = (filters.OrderingFilter,)
|
||||
filter_backends = [filters.OrderingFilter]
|
||||
ordering_fields = '__all__'
|
||||
|
||||
### Specifying a default ordering
|
||||
|
@ -271,55 +286,14 @@ Typically you'd instead control this by setting `order_by` on the initial querys
|
|||
class UserListView(generics.ListAPIView):
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
filter_backends = (filters.OrderingFilter,)
|
||||
ordering_fields = ('username', 'email')
|
||||
ordering = ('username',)
|
||||
filter_backends = [filters.OrderingFilter]
|
||||
ordering_fields = ['username', 'email']
|
||||
ordering = ['username']
|
||||
|
||||
The `ordering` attribute may be either a string or a list/tuple of strings.
|
||||
|
||||
---
|
||||
|
||||
## DjangoObjectPermissionsFilter
|
||||
|
||||
The `DjangoObjectPermissionsFilter` is intended to be used together with the [`django-guardian`][guardian] package, with custom `'view'` permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.
|
||||
|
||||
If you're using `DjangoObjectPermissionsFilter`, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass `DjangoObjectPermissions` and add `'view'` permissions to the `perms_map` attribute.
|
||||
|
||||
A complete example using both `DjangoObjectPermissionsFilter` and `DjangoObjectPermissions` might look something like this.
|
||||
|
||||
**permissions.py**:
|
||||
|
||||
class CustomObjectPermissions(permissions.DjangoObjectPermissions):
|
||||
"""
|
||||
Similar to `DjangoObjectPermissions`, but adding 'view' permissions.
|
||||
"""
|
||||
perms_map = {
|
||||
'GET': ['%(app_label)s.view_%(model_name)s'],
|
||||
'OPTIONS': ['%(app_label)s.view_%(model_name)s'],
|
||||
'HEAD': ['%(app_label)s.view_%(model_name)s'],
|
||||
'POST': ['%(app_label)s.add_%(model_name)s'],
|
||||
'PUT': ['%(app_label)s.change_%(model_name)s'],
|
||||
'PATCH': ['%(app_label)s.change_%(model_name)s'],
|
||||
'DELETE': ['%(app_label)s.delete_%(model_name)s'],
|
||||
}
|
||||
|
||||
**views.py**:
|
||||
|
||||
class EventViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
Viewset that only lists events if user has 'view' permissions, and only
|
||||
allows operations on individual events if user has appropriate 'view', 'add',
|
||||
'change' or 'delete' permissions.
|
||||
"""
|
||||
queryset = Event.objects.all()
|
||||
serializer_class = EventSerializer
|
||||
filter_backends = (filters.DjangoObjectPermissionsFilter,)
|
||||
permission_classes = (myapp.permissions.CustomObjectPermissions,)
|
||||
|
||||
For more information on adding `'view'` permissions for models, see the [relevant section][view-permissions] of the `django-guardian` documentation, and [this blogpost][view-permissions-blogpost].
|
||||
|
||||
---
|
||||
|
||||
# Custom generic filtering
|
||||
|
||||
You can also provide your own generic filtering backend, or write an installable app for other developers to use.
|
||||
|
@ -379,13 +353,8 @@ The [djangorestframework-word-filter][django-rest-framework-word-search-filter]
|
|||
[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]: https://github.com/alex/django-filter
|
||||
[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
|
||||
[guardian]: https://django-guardian.readthedocs.io/
|
||||
[view-permissions]: https://django-guardian.readthedocs.io/en/latest/userguide/assign.html
|
||||
[view-permissions-blogpost]: http://blog.nyaruka.com/adding-a-view-permission-to-django-models
|
||||
[nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py
|
||||
[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
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: urlpatterns.py
|
||||
---
|
||||
source:
|
||||
- urlpatterns.py
|
||||
---
|
||||
|
||||
# Format suffixes
|
||||
|
||||
|
@ -38,7 +41,7 @@ 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'))
|
||||
@api_view(['GET', 'POST'])
|
||||
def comment_list(request, format=None):
|
||||
# do stuff...
|
||||
|
||||
|
@ -90,4 +93,4 @@ It is actually a misconception. For example, take the following quote from Roy
|
|||
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]: http://tech.groups.yahoo.com/group/rest-discuss/message/14844
|
||||
[cite2]: https://groups.yahoo.com/neo/groups/rest-discuss/conversations/topics/14844
|
||||
|
|
|
@ -1,5 +1,8 @@
|
|||
source: mixins.py
|
||||
generics.py
|
||||
---
|
||||
source:
|
||||
- mixins.py
|
||||
- generics.py
|
||||
---
|
||||
|
||||
# Generic views
|
||||
|
||||
|
@ -25,14 +28,14 @@ Typically when using the generic views, you'll override the view, and set severa
|
|||
class UserList(generics.ListCreateAPIView):
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = (IsAdminUser,)
|
||||
permission_classes = [IsAdminUser]
|
||||
|
||||
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()
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = (IsAdminUser,)
|
||||
permission_classes = [IsAdminUser]
|
||||
|
||||
def list(self, request):
|
||||
# Note the use of `get_queryset()` instead of `self.queryset`
|
||||
|
@ -120,12 +123,12 @@ Given a queryset, filter it with whichever filter backends are in use, returning
|
|||
For example:
|
||||
|
||||
def filter_queryset(self, queryset):
|
||||
filter_backends = (CategoryFilter,)
|
||||
filter_backends = [CategoryFilter]
|
||||
|
||||
if 'geo_route' in self.request.query_params:
|
||||
filter_backends = (GeoRouteFilter, CategoryFilter)
|
||||
filter_backends = [GeoRouteFilter, CategoryFilter]
|
||||
elif 'geo_point' in self.request.query_params:
|
||||
filter_backends = (GeoPointFilter, CategoryFilter)
|
||||
filter_backends = [GeoPointFilter, CategoryFilter]
|
||||
|
||||
for backend in list(filter_backends):
|
||||
queryset = backend().filter_queryset(self.request, queryset, view=self)
|
||||
|
@ -339,7 +342,7 @@ You can then simply apply this mixin to a view or viewset anytime you need to ap
|
|||
class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
lookup_fields = ('account', 'username')
|
||||
lookup_fields = ['account', 'username']
|
||||
|
||||
Using custom mixins is a good option if you have custom behavior that needs to be used.
|
||||
|
||||
|
@ -375,10 +378,6 @@ If you need to generic PUT-as-create behavior you may want to include something
|
|||
|
||||
The following third party packages provide additional generic view implementations.
|
||||
|
||||
## Django REST Framework bulk
|
||||
|
||||
The [django-rest-framework-bulk package][django-rest-framework-bulk] implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.
|
||||
|
||||
## Django Rest Multiple Models
|
||||
|
||||
[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.
|
||||
|
@ -391,5 +390,4 @@ The [django-rest-framework-bulk package][django-rest-framework-bulk] implements
|
|||
[RetrieveModelMixin]: #retrievemodelmixin
|
||||
[UpdateModelMixin]: #updatemodelmixin
|
||||
[DestroyModelMixin]: #destroymodelmixin
|
||||
[django-rest-framework-bulk]: https://github.com/miki725/django-rest-framework-bulk
|
||||
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: metadata.py
|
||||
---
|
||||
source:
|
||||
- metadata.py
|
||||
---
|
||||
|
||||
# Metadata
|
||||
|
||||
|
@ -67,7 +70,7 @@ If you have specific requirements for creating schema endpoints that are accesse
|
|||
|
||||
For example, the following additional route could be used on a viewset to provide a linkable schema endpoint.
|
||||
|
||||
@list_route(methods=['GET'])
|
||||
@action(methods=['GET'], detail=False)
|
||||
def schema(self, request):
|
||||
meta = self.metadata_class()
|
||||
data = meta.determine_metadata(request, self)
|
||||
|
@ -115,7 +118,7 @@ The following third party packages provide additional metadata implementations.
|
|||
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]: http://tools.ietf.org/html/rfc7231#section-4.3.7
|
||||
[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]: http://json-schema.org/
|
||||
[json-schema]: https://json-schema.org/
|
||||
[drf-schema-adapter]: https://github.com/drf-forms/drf-schema-adapter
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: pagination.py
|
||||
---
|
||||
source:
|
||||
- pagination.py
|
||||
---
|
||||
|
||||
# Pagination
|
||||
|
||||
|
@ -46,7 +49,7 @@ If you want to modify particular aspects of the pagination style, you'll want to
|
|||
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:
|
||||
You can then apply your new style to a view using the `pagination_class` attribute:
|
||||
|
||||
class BillingRecordsView(generics.ListAPIView):
|
||||
queryset = Billing.objects.all()
|
||||
|
@ -257,6 +260,10 @@ To have your custom pagination class be used by default, use the `DEFAULT_PAGINA
|
|||
|
||||
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'*
|
||||
|
||||
## Pagination & schemas
|
||||
|
||||
You can also make the pagination controls available to the schema autogeneration
|
||||
|
@ -268,12 +275,6 @@ The method should return a list of `coreapi.Field` instances.
|
|||
|
||||
---
|
||||
|
||||
![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.
|
||||
|
@ -311,14 +312,13 @@ The [`drf-proxy-pagination` package][drf-proxy-pagination] includes a `ProxyPagi
|
|||
|
||||
## 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 desribed in [Github's developer documentation](github-link-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's developer documentation](github-link-pagination).
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/topics/pagination/
|
||||
[github-link-pagination]: https://developer.github.com/guides/traversing-with-pagination/
|
||||
[link-header]: ../img/link-header-pagination.png
|
||||
[drf-extensions]: http://chibisov.github.io/drf-extensions/docs/
|
||||
[paginate-by-max-mixin]: http://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin
|
||||
[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]: http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api
|
||||
[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
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: parsers.py
|
||||
---
|
||||
source:
|
||||
- parsers.py
|
||||
---
|
||||
|
||||
# Parsers
|
||||
|
||||
|
@ -29,9 +32,9 @@ As an example, if you are sending `json` encoded data using jQuery with the [.aj
|
|||
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.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PARSER_CLASSES': (
|
||||
'DEFAULT_PARSER_CLASSES': [
|
||||
'rest_framework.parsers.JSONParser',
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
You can also set the parsers used for an individual view, or viewset,
|
||||
|
@ -45,7 +48,7 @@ using the `APIView` class-based views.
|
|||
"""
|
||||
A view that can accept POST requests with JSON content.
|
||||
"""
|
||||
parser_classes = (JSONParser,)
|
||||
parser_classes = [JSONParser]
|
||||
|
||||
def post(self, request, format=None):
|
||||
return Response({'received data': request.data})
|
||||
|
@ -57,7 +60,7 @@ Or, if you're using the `@api_view` decorator with function based views.
|
|||
from rest_framework.parsers import JSONParser
|
||||
|
||||
@api_view(['POST'])
|
||||
@parser_classes((JSONParser,))
|
||||
@parser_classes([JSONParser])
|
||||
def example_view(request, format=None):
|
||||
"""
|
||||
A view that can accept POST requests with JSON content.
|
||||
|
@ -102,7 +105,7 @@ If it is called without a `filename` URL keyword argument, then the client must
|
|||
|
||||
##### 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` parser instead.
|
||||
* 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.
|
||||
|
||||
|
@ -110,7 +113,7 @@ If it is called without a `filename` URL keyword argument, then the client must
|
|||
|
||||
# views.py
|
||||
class FileUploadView(views.APIView):
|
||||
parser_classes = (FileUploadParser,)
|
||||
parser_classes = [FileUploadParser]
|
||||
|
||||
def put(self, request, filename, format=None):
|
||||
file_obj = request.data['file']
|
||||
|
@ -186,12 +189,12 @@ Install using pip.
|
|||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PARSER_CLASSES': (
|
||||
'DEFAULT_PARSER_CLASSES': [
|
||||
'rest_framework_yaml.parsers.YAMLParser',
|
||||
),
|
||||
'DEFAULT_RENDERER_CLASSES': (
|
||||
],
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework_yaml.renderers.YAMLRenderer',
|
||||
),
|
||||
],
|
||||
}
|
||||
|
||||
## XML
|
||||
|
@ -207,12 +210,12 @@ Install using pip.
|
|||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PARSER_CLASSES': (
|
||||
'DEFAULT_PARSER_CLASSES': [
|
||||
'rest_framework_xml.parsers.XMLParser',
|
||||
),
|
||||
'DEFAULT_RENDERER_CLASSES': (
|
||||
],
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework_xml.renderers.XMLRenderer',
|
||||
),
|
||||
],
|
||||
}
|
||||
|
||||
## MessagePack
|
||||
|
@ -223,11 +226,11 @@ Modify your REST framework settings.
|
|||
|
||||
[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]: http://api.jquery.com/jQuery.ajax/
|
||||
[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]: http://jpadilla.github.io/django-rest-framework-yaml/
|
||||
[rest-framework-xml]: http://jpadilla.github.io/django-rest-framework-xml/
|
||||
[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
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: permissions.py
|
||||
---
|
||||
source:
|
||||
- permissions.py
|
||||
---
|
||||
|
||||
# Permissions
|
||||
|
||||
|
@ -10,9 +13,9 @@ 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 different classes of users to different parts of the API.
|
||||
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 the `IsAuthenticated` class in REST framework.
|
||||
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.
|
||||
|
||||
|
@ -48,6 +51,19 @@ For example:
|
|||
self.check_object_permissions(self.request, obj)
|
||||
return obj
|
||||
|
||||
---
|
||||
|
||||
**Note**: With the exception of `DjangoObjectPermissions`, the provided
|
||||
permission classes in `rest_framework.permissions` **do not** implement the
|
||||
methods necessary to check object permissions.
|
||||
|
||||
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.
|
||||
|
@ -59,16 +75,16 @@ Often when you're using object level permissions you'll also want to [filter the
|
|||
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.
|
||||
|
@ -78,7 +94,7 @@ using the `APIView` class-based views.
|
|||
from rest_framework.views import APIView
|
||||
|
||||
class ExampleView(APIView):
|
||||
permission_classes = (IsAuthenticated,)
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
|
@ -93,7 +109,7 @@ Or, if you're using the `@api_view` decorator with function based views.
|
|||
from rest_framework.response import Response
|
||||
|
||||
@api_view(['GET'])
|
||||
@permission_classes((IsAuthenticated, ))
|
||||
@permission_classes([IsAuthenticated])
|
||||
def example_view(request, format=None):
|
||||
content = {
|
||||
'status': 'request was permitted'
|
||||
|
@ -102,6 +118,27 @@ Or, if you're using the `@api_view` decorator with function based views.
|
|||
|
||||
__Note:__ when you set new permission classes through class attribute or decorators you're telling the view to ignore the default list set over 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
|
||||
|
@ -168,9 +205,7 @@ As with `DjangoModelPermissions` you can use custom model permissions by overrid
|
|||
|
||||
---
|
||||
|
||||
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests, you'll want to consider also adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions.
|
||||
|
||||
---
|
||||
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian` package][django-rest-framework-guardian]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.
|
||||
|
||||
---
|
||||
|
||||
|
@ -192,7 +227,7 @@ If you need to test if a request is a read operation or a write operation, you s
|
|||
|
||||
---
|
||||
|
||||
**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.
|
||||
**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.)
|
||||
|
||||
---
|
||||
|
||||
|
@ -249,6 +284,10 @@ Also note that the generic views will only check the object-level permissions fo
|
|||
|
||||
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.
|
||||
|
@ -265,9 +304,13 @@ The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to
|
|||
|
||||
The [Django Rest Framework Roles][django-rest-framework-roles] package makes it easier to parameterize your API over multiple types of users.
|
||||
|
||||
## Django Rest Framework API Key
|
||||
## Django REST Framework API Key
|
||||
|
||||
The [Django Rest Framework API Key][django-rest-framework-api-key] package allows you to ensure that every request made to the server requires an API key header. You can generate one from the django admin interface.
|
||||
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.
|
||||
|
||||
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
|
||||
[authentication]: authentication.md
|
||||
|
@ -276,12 +319,12 @@ The [Django Rest Framework API Key][django-rest-framework-api-key] package allow
|
|||
[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
|
||||
[guardian]: https://github.com/lukaszb/django-guardian
|
||||
[get_objects_for_user]: http://pythonhosted.org/django-guardian/api/guardian.shortcuts.html#get-objects-for-user
|
||||
[2.2-announcement]: ../topics/2.2-announcement.md
|
||||
[filtering]: filtering.md
|
||||
[drf-any-permissions]: https://github.com/kevin-brown/drf-any-permissions
|
||||
[composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions
|
||||
[rest-condition]: https://github.com/caxap/rest_condition
|
||||
[dry-rest-permissions]: https://github.com/Helioscene/dry-rest-permissions
|
||||
[django-rest-framework-roles]: https://github.com/computer-lab/django-rest-framework-roles
|
||||
[django-rest-framework-api-key]: https://github.com/manosim/django-rest-framework-api-key
|
||||
[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
|
||||
|
|
|
@ -1,12 +1,13 @@
|
|||
source: relations.py
|
||||
---
|
||||
source:
|
||||
- relations.py
|
||||
---
|
||||
|
||||
# Serializer relations
|
||||
|
||||
> Bad programmers worry about the code.
|
||||
> Good programmers worry about data structures and their relationships.
|
||||
> Data structures, not algorithms, are central to programming.
|
||||
>
|
||||
> — [Linus Torvalds][cite]
|
||||
|
||||
> — [Rob Pike][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`.
|
||||
|
||||
|
@ -24,7 +25,7 @@ To do so, open the Django shell, using `python manage.py shell`, then import the
|
|||
|
||||
>>> from myapp.serializers import AccountSerializer
|
||||
>>> serializer = AccountSerializer()
|
||||
>>> print repr(serializer) # Or `print(repr(serializer))` in Python 3.x.
|
||||
>>> print(repr(serializer))
|
||||
AccountSerializer():
|
||||
id = IntegerField(label='ID', read_only=True)
|
||||
name = CharField(allow_blank=True, max_length=100, required=False)
|
||||
|
@ -45,15 +46,15 @@ In order to explain the various types of relational fields, we'll use a couple o
|
|||
duration = models.IntegerField()
|
||||
|
||||
class Meta:
|
||||
unique_together = ('album', 'order')
|
||||
unique_together = ['album', 'order']
|
||||
ordering = ['order']
|
||||
|
||||
def __unicode__(self):
|
||||
def __str__(self):
|
||||
return '%d: %s' % (self.order, self.title)
|
||||
|
||||
## StringRelatedField
|
||||
|
||||
`StringRelatedField` may be used to represent the target of the relationship using its `__unicode__` method.
|
||||
`StringRelatedField` may be used to represent the target of the relationship using its `__str__` method.
|
||||
|
||||
For example, the following serializer.
|
||||
|
||||
|
@ -62,7 +63,7 @@ For example, the following serializer.
|
|||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ('album_name', 'artist', 'tracks')
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
Would serialize to the following representation.
|
||||
|
||||
|
@ -94,7 +95,7 @@ For example, the following serializer:
|
|||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ('album_name', 'artist', 'tracks')
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
Would serialize to a representation like this:
|
||||
|
||||
|
@ -134,7 +135,7 @@ For example, the following serializer:
|
|||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ('album_name', 'artist', 'tracks')
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
Would serialize to a representation like this:
|
||||
|
||||
|
@ -186,7 +187,7 @@ For example, the following serializer:
|
|||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ('album_name', 'artist', 'tracks')
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
Would serialize to a representation like this:
|
||||
|
||||
|
@ -221,7 +222,7 @@ This field can be applied as an identity relationship, such as the `'url'` field
|
|||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ('album_name', 'artist', 'track_listing')
|
||||
fields = ['album_name', 'artist', 'track_listing']
|
||||
|
||||
Would serialize to a representation like this:
|
||||
|
||||
|
@ -255,14 +256,14 @@ For example, the following serializer:
|
|||
class TrackSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Track
|
||||
fields = ('order', 'title', 'duration')
|
||||
fields = ['order', 'title', 'duration']
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = TrackSerializer(many=True, read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ('album_name', 'artist', 'tracks')
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
Would serialize to a nested representation like this:
|
||||
|
||||
|
@ -293,14 +294,14 @@ By default nested serializers are read-only. If you want to support write-operat
|
|||
class TrackSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Track
|
||||
fields = ('order', 'title', 'duration')
|
||||
fields = ['order', 'title', 'duration']
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = TrackSerializer(many=True)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ('album_name', 'artist', 'tracks')
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
def create(self, validated_data):
|
||||
tracks_data = validated_data.pop('tracks')
|
||||
|
@ -354,7 +355,7 @@ For example, we could define a relational field to serialize a track to a custom
|
|||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ('album_name', 'artist', 'tracks')
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
This custom field would then serialize to the following representation.
|
||||
|
||||
|
@ -384,7 +385,7 @@ The `get_url` method is used to map the object instance to its URL representatio
|
|||
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
|
||||
attributes are not configured to correctly match the URL conf.
|
||||
|
||||
**get_object(self, queryset, view_name, view_args, view_kwargs)**
|
||||
**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.
|
||||
|
||||
|
@ -479,7 +480,7 @@ Note that reverse relationships are not automatically included by the `ModelSeri
|
|||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
fields = ('tracks', ...)
|
||||
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:
|
||||
|
||||
|
@ -491,7 +492,7 @@ If you have not set a related name for the reverse relationship, you'll need to
|
|||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
fields = ('track_set', ...)
|
||||
fields = ['track_set', ...]
|
||||
|
||||
See the Django documentation on [reverse relationships][reverse-relationships] for more details.
|
||||
|
||||
|
@ -512,7 +513,7 @@ For example, given the following model for a tag, which has a generic relationsh
|
|||
object_id = models.PositiveIntegerField()
|
||||
tagged_object = GenericForeignKey('content_type', 'object_id')
|
||||
|
||||
def __unicode__(self):
|
||||
def __str__(self):
|
||||
return self.tag_name
|
||||
|
||||
And the following two models, which may have associated tags:
|
||||
|
@ -578,6 +579,8 @@ If you explicitly specify a relational field pointing to a
|
|||
``ManyToManyField`` with a through model, be sure to set ``read_only``
|
||||
to ``True``.
|
||||
|
||||
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].
|
||||
|
||||
---
|
||||
|
||||
# Third Party Packages
|
||||
|
@ -592,10 +595,11 @@ The [drf-nested-routers package][drf-nested-routers] provides routers and relati
|
|||
|
||||
The [rest-framework-generic-relations][drf-nested-relations] library provides read/write serialization for generic foreign keys.
|
||||
|
||||
[cite]: http://lwn.net/Articles/193245/
|
||||
[cite]: http://users.ece.utexas.edu/~adnan/pike.html
|
||||
[reverse-relationships]: https://docs.djangoproject.com/en/stable/topics/db/queries/#following-relationships-backward
|
||||
[routers]: http://www.django-rest-framework.org/api-guide/routers#defaultrouter
|
||||
[routers]: https://www.django-rest-framework.org/api-guide/routers#defaultrouter
|
||||
[generic-relations]: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/#id1
|
||||
[2.2-announcement]: ../topics/2.2-announcement.md
|
||||
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
|
||||
[drf-nested-relations]: https://github.com/Ian-Foote/rest-framework-generic-relations
|
||||
[django-intermediary-manytomany]: https://docs.djangoproject.com/en/2.2/topics/db/models/#intermediary-manytomany
|
||||
[dealing-with-nested-objects]: https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: renderers.py
|
||||
---
|
||||
source:
|
||||
- renderers.py
|
||||
---
|
||||
|
||||
# Renderers
|
||||
|
||||
|
@ -21,10 +24,10 @@ For more information see the documentation on [content negotiation][conneg].
|
|||
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.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_RENDERER_CLASSES': (
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
You can also set the renderers used for an individual view, or viewset,
|
||||
|
@ -39,7 +42,7 @@ using the `APIView` class-based views.
|
|||
"""
|
||||
A view that returns the count of active users in JSON.
|
||||
"""
|
||||
renderer_classes = (JSONRenderer, )
|
||||
renderer_classes = [JSONRenderer]
|
||||
|
||||
def get(self, request, format=None):
|
||||
user_count = User.objects.filter(active=True).count()
|
||||
|
@ -49,7 +52,7 @@ 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])
|
||||
def user_count_view(request, format=None):
|
||||
"""
|
||||
A view that returns the count of active users in JSON.
|
||||
|
@ -89,7 +92,7 @@ The default JSON encoding style can be altered using the `UNICODE_JSON` and `COM
|
|||
|
||||
**.media_type**: `application/json`
|
||||
|
||||
**.format**: `'.json'`
|
||||
**.format**: `'json'`
|
||||
|
||||
**.charset**: `None`
|
||||
|
||||
|
@ -113,7 +116,7 @@ An example of a view that uses `TemplateHTMLRenderer`:
|
|||
A view that returns a templated HTML representation of a given user.
|
||||
"""
|
||||
queryset = User.objects.all()
|
||||
renderer_classes = (TemplateHTMLRenderer,)
|
||||
renderer_classes = [TemplateHTMLRenderer]
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
self.object = self.get_object()
|
||||
|
@ -127,7 +130,7 @@ See the [_HTML & Forms_ Topic Page][html-and-forms] for further examples of `Tem
|
|||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'.html'`
|
||||
**.format**: `'html'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
|
||||
|
@ -139,8 +142,8 @@ A simple renderer that simply returns pre-rendered HTML. Unlike other renderers
|
|||
|
||||
An example of a view that uses `StaticHTMLRenderer`:
|
||||
|
||||
@api_view(('GET',))
|
||||
@renderer_classes((StaticHTMLRenderer,))
|
||||
@api_view(['GET'])
|
||||
@renderer_classes([StaticHTMLRenderer])
|
||||
def simple_html_view(request):
|
||||
data = '<html><body><h1>Hello, world</h1></body></html>'
|
||||
return Response(data)
|
||||
|
@ -149,7 +152,7 @@ You can use `StaticHTMLRenderer` either to return regular HTML pages using REST
|
|||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'.html'`
|
||||
**.format**: `'html'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
|
||||
|
@ -165,7 +168,7 @@ This renderer will determine which other renderer would have been given highest
|
|||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'.api'`
|
||||
**.format**: `'api'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
|
||||
|
@ -200,7 +203,7 @@ Note that views that have nested or list serializers for their input won't work
|
|||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'.admin'`
|
||||
**.format**: `'admin'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
|
||||
|
@ -224,7 +227,7 @@ For more information see the [HTML & Forms][html-and-forms] documentation.
|
|||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'.form'`
|
||||
**.format**: `'form'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
|
||||
|
@ -236,7 +239,7 @@ This renderer is used for rendering HTML multipart form data. **It is not suita
|
|||
|
||||
**.media_type**: `multipart/form-data; boundary=BoUnDaRyStRiNg`
|
||||
|
||||
**.format**: `'.multipart'`
|
||||
**.format**: `'multipart'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
|
||||
|
@ -325,8 +328,8 @@ In some cases you might want your view to use different serialization styles dep
|
|||
|
||||
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
|
||||
|
@ -398,12 +401,12 @@ Install using pip.
|
|||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PARSER_CLASSES': (
|
||||
'DEFAULT_PARSER_CLASSES': [
|
||||
'rest_framework_yaml.parsers.YAMLParser',
|
||||
),
|
||||
'DEFAULT_RENDERER_CLASSES': (
|
||||
],
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework_yaml.renderers.YAMLRenderer',
|
||||
),
|
||||
],
|
||||
}
|
||||
|
||||
## XML
|
||||
|
@ -419,12 +422,12 @@ Install using pip.
|
|||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PARSER_CLASSES': (
|
||||
'DEFAULT_PARSER_CLASSES': [
|
||||
'rest_framework_xml.parsers.XMLParser',
|
||||
),
|
||||
'DEFAULT_RENDERER_CLASSES': (
|
||||
],
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework_xml.renderers.XMLRenderer',
|
||||
),
|
||||
],
|
||||
}
|
||||
|
||||
## JSONP
|
||||
|
@ -448,15 +451,52 @@ Install using pip.
|
|||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_RENDERER_CLASSES': (
|
||||
'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.
|
||||
|
||||
## XLSX (Binary Spreadsheet Endpoints)
|
||||
|
||||
XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-renderer-xlsx][drf-renderer-xlsx], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
|
||||
|
||||
#### Installation & configuration
|
||||
|
||||
Install using pip.
|
||||
|
||||
$ pip install drf-renderer-xlsx
|
||||
|
||||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
...
|
||||
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
'drf_renderer_xlsx.renderers.XLSXRenderer',
|
||||
],
|
||||
}
|
||||
|
||||
To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the `Content-Disposition` header. If no filename is provided, it will default to `export.xlsx`. For example:
|
||||
|
||||
from rest_framework.viewsets import ReadOnlyModelViewSet
|
||||
from drf_renderer_xlsx.mixins import XLSXFileMixin
|
||||
from drf_renderer_xlsx.renderers import XLSXRenderer
|
||||
|
||||
from .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.
|
||||
|
@ -484,22 +524,25 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
|||
[browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
|
||||
[testing]: testing.md
|
||||
[HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas
|
||||
[quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
|
||||
[application/vnd.github+json]: http://developer.github.com/v3/media/
|
||||
[quote]: https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
|
||||
[application/vnd.github+json]: https://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]: http://jpadilla.github.io/django-rest-framework-jsonp/
|
||||
[cors]: http://www.w3.org/TR/cors/
|
||||
[cors-docs]: http://www.django-rest-framework.org/topics/ajax-csrf-cors/
|
||||
[jsonp-security]: http://stackoverflow.com/questions/613962/is-jsonp-safe-to-use
|
||||
[rest-framework-yaml]: http://jpadilla.github.io/django-rest-framework-yaml/
|
||||
[rest-framework-xml]: http://jpadilla.github.io/django-rest-framework-xml/
|
||||
[messagepack]: http://msgpack.org/
|
||||
[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-renderer-xlsx]: https://github.com/wharton/drf-renderer-xlsx
|
||||
[vbabiy]: https://github.com/vbabiy
|
||||
[rest-framework-yaml]: http://jpadilla.github.io/django-rest-framework-yaml/
|
||||
[rest-framework-xml]: http://jpadilla.github.io/django-rest-framework-xml/
|
||||
[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
|
||||
|
@ -508,7 +551,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
|||
[drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer
|
||||
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
|
||||
[Django REST Pandas]: https://github.com/wq/django-rest-pandas
|
||||
[Pandas]: http://pandas.pydata.org/
|
||||
[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
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: request.py
|
||||
---
|
||||
source:
|
||||
- request.py
|
||||
---
|
||||
|
||||
# Requests
|
||||
|
||||
|
@ -46,11 +49,11 @@ If a client sends a request with a content-type that cannot be parsed then a `Un
|
|||
|
||||
# Content negotiation
|
||||
|
||||
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialisation schemes for different media types.
|
||||
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialization schemes for different media types.
|
||||
|
||||
## .accepted_renderer
|
||||
|
||||
The renderer instance what was selected by the content negotiation stage.
|
||||
The renderer instance that was selected by the content negotiation stage.
|
||||
|
||||
## .accepted_media_type
|
||||
|
||||
|
@ -90,7 +93,7 @@ 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` orginates from the authenticator and will instaed assume that the request object does not have a `.user` or `.auth` property. The authenticator will need to be fixed.
|
||||
**Note:** You may see a `WrappedAttributeError` raised when calling the `.user` or `.auth` properties. These errors originate from an authenticator as a standard `AttributeError`, however it's necessary that they be re-raised as a different exception type in order to prevent them from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from the authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. The authenticator will need to be fixed.
|
||||
|
||||
---
|
||||
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: response.py
|
||||
---
|
||||
source:
|
||||
- response.py
|
||||
---
|
||||
|
||||
# Responses
|
||||
|
||||
|
@ -91,5 +94,5 @@ As with any other `TemplateResponse`, this method is called to render the serial
|
|||
|
||||
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/stable/template-response/
|
||||
[cite]: https://docs.djangoproject.com/en/stable/ref/template-response/
|
||||
[statuscodes]: status-codes.md
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: reverse.py
|
||||
---
|
||||
source:
|
||||
- reverse.py
|
||||
---
|
||||
|
||||
# Returning URLs
|
||||
|
||||
|
@ -50,6 +53,6 @@ As with the `reverse` function, you should **include the request as a keyword ar
|
|||
|
||||
api_root = reverse_lazy('api-root', request=request)
|
||||
|
||||
[cite]: http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5
|
||||
[cite]: https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5
|
||||
[reverse]: https://docs.djangoproject.com/en/stable/topics/http/urls/#reverse
|
||||
[reverse-lazy]: https://docs.djangoproject.com/en/stable/topics/http/urls/#reverse-lazy
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: routers.py
|
||||
---
|
||||
source:
|
||||
- routers.py
|
||||
---
|
||||
|
||||
# Routers
|
||||
|
||||
|
@ -28,7 +31,7 @@ There are two mandatory arguments to the `register()` method:
|
|||
|
||||
Optionally, you may also specify an additional argument:
|
||||
|
||||
* `base_name` - 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 `base_name` when registering the viewset.
|
||||
* `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:
|
||||
|
||||
|
@ -39,13 +42,13 @@ The example above would generate the following URL patterns:
|
|||
|
||||
---
|
||||
|
||||
**Note**: The `base_name` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part.
|
||||
**Note**: The `basename` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part.
|
||||
|
||||
Typically you won't *need* to specify the `base_name` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this:
|
||||
Typically you won't *need* to specify the `basename` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this:
|
||||
|
||||
'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
|
||||
'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
|
||||
|
||||
This means you'll need to explicitly set the `base_name` argument when registering the viewset, as it could not be automatically determined from the model name.
|
||||
This means you'll need to explicitly set the `basename` argument when registering the viewset, as it could not be automatically determined from the model name.
|
||||
|
||||
---
|
||||
|
||||
|
@ -53,7 +56,7 @@ This means you'll need to explicitly set the `base_name` argument when registeri
|
|||
|
||||
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…
|
||||
For example, you can append `router.urls` to a list of existing views...
|
||||
|
||||
router = routers.SimpleRouter()
|
||||
router.register(r'users', UserViewSet)
|
||||
|
@ -65,97 +68,96 @@ For example, you can append `router.urls` to a list of existing views…
|
|||
|
||||
urlpatterns += router.urls
|
||||
|
||||
Alternatively you can use Django's `include` function, like so…
|
||||
Alternatively you can use Django's `include` function, like so...
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
|
||||
url(r'^', include(router.urls)),
|
||||
]
|
||||
|
||||
Router URL patterns can also be namespaces.
|
||||
You may use `include` with an application namespace:
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
|
||||
url(r'^api/', include(router.urls, namespace='api')),
|
||||
url(r'^api/', include((router.urls, 'app_name'))),
|
||||
]
|
||||
|
||||
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 example above you'd need to include a parameter such as `view_name='api:user-detail'` for serializer fields hyperlinked to the user detail view.
|
||||
Or both an application and instance namespace:
|
||||
|
||||
### Extra link and actions
|
||||
urlpatterns = [
|
||||
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
|
||||
url(r'^api/', include((router.urls, 'app_name'), namespace='instance_name')),
|
||||
]
|
||||
|
||||
Any methods on the viewset decorated with `@detail_route` or `@list_route` will also be routed.
|
||||
For example, given a method like this on the `UserViewSet` class:
|
||||
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 detail_route
|
||||
from rest_framework.decorators import action
|
||||
|
||||
class UserViewSet(ModelViewSet):
|
||||
...
|
||||
|
||||
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])
|
||||
@action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])
|
||||
def set_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
The following URL pattern would additionally be generated:
|
||||
The following route would be generated:
|
||||
|
||||
* URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'`
|
||||
* URL pattern: `^users/{pk}/set_password/$`
|
||||
* URL name: `'user-set-password'`
|
||||
|
||||
If you do not want to use the default URL generated for your custom action, you can instead use the url_path parameter to customize it.
|
||||
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 detail_route
|
||||
from rest_framework.decorators import action
|
||||
|
||||
class UserViewSet(ModelViewSet):
|
||||
...
|
||||
|
||||
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf], url_path='change-password')
|
||||
@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 pattern: `^users/{pk}/change-password/$` Name: `'user-change-password'`
|
||||
|
||||
In the case you do not want to use the default name generated for your custom action, you can use the url_name parameter to customize it.
|
||||
|
||||
For example, if you want to change the name of our custom action to `'user-change-password'`, you could write:
|
||||
|
||||
from myapp.permissions import IsAdminOrIsSelf
|
||||
from rest_framework.decorators import detail_route
|
||||
|
||||
class UserViewSet(ModelViewSet):
|
||||
...
|
||||
|
||||
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf], url_name='change-password')
|
||||
def set_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
The above example would now generate the following URL pattern:
|
||||
|
||||
* URL pattern: `^users/{pk}/set_password/$` Name: `'user-change-password'`
|
||||
|
||||
You can also use url_path and url_name parameters together to obtain extra control on URL generation for custom views.
|
||||
|
||||
For more information see the viewset documentation on [marking extra actions for routing][route-decorators].
|
||||
* URL path: `^users/{pk}/change-password/$`
|
||||
* URL name: `'user-change_password'`
|
||||
|
||||
# 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 `@detail_route` or `@list_route` decorators.
|
||||
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}/{methodname}/</td><td>GET, or as specified by `methods` argument</td><td>`@list_route` decorated method</td><td>{basename}-{methodname}</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}/{methodname}/</td><td>GET, or as specified by `methods` argument</td><td>`@detail_route` decorated method</td><td>{basename}-{methodname}</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.
|
||||
|
@ -180,12 +182,12 @@ This router is similar to `SimpleRouter` as above, but additionally includes a d
|
|||
<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}/{methodname}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@list_route` decorated method</td><td>{basename}-{methodname}</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}/{methodname}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@detail_route` decorated method</td><td>{basename}-{methodname}</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.
|
||||
|
@ -212,18 +214,18 @@ The arguments to the `Route` named tuple are:
|
|||
|
||||
* `{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 `suffix` argument is reserved for identifying the viewset type, used when generating the view name and breadcrumb links.
|
||||
**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 `@list_route` and `@detail_route` decorators are routed.
|
||||
To route either or both of these decorators, include a `DynamicListRoute` and/or `DynamicDetailRoute` named tuple in the `.routes` list.
|
||||
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:
|
||||
|
||||
The arguments to `DynamicListRoute` and `DynamicDetailRoute` 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.
|
||||
|
||||
**url**: A string representing the URL to be routed. May include the same format strings as `Route`, and additionally accepts the `{methodname}` and `{methodnamehyphen}` format strings.
|
||||
**name**: The name of the URL as used in `reverse` calls. May include the following format strings:
|
||||
|
||||
**name**: The name of the URL as used in `reverse` calls. May include the following format strings: `{basename}`, `{methodname}` and `{methodnamehyphen}`.
|
||||
* `{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.
|
||||
|
||||
|
@ -231,7 +233,7 @@ The arguments to `DynamicListRoute` and `DynamicDetailRoute` are:
|
|||
|
||||
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, DynamicDetailRoute, SimpleRouter
|
||||
from rest_framework.routers import Route, DynamicRoute, SimpleRouter
|
||||
|
||||
class CustomReadOnlyRouter(SimpleRouter):
|
||||
"""
|
||||
|
@ -242,17 +244,20 @@ The following example will only route to the `list` and `retrieve` actions, and
|
|||
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'}
|
||||
),
|
||||
DynamicDetailRoute(
|
||||
url=r'^{prefix}/{lookup}/{methodnamehyphen}$',
|
||||
name='{basename}-{methodnamehyphen}',
|
||||
DynamicRoute(
|
||||
url=r'^{prefix}/{lookup}/{url_path}$',
|
||||
name='{basename}-{url_name}',
|
||||
detail=True,
|
||||
initkwargs={}
|
||||
)
|
||||
]
|
||||
|
@ -269,7 +274,7 @@ Let's take a look at the routes our `CustomReadOnlyRouter` would generate for a
|
|||
serializer_class = UserSerializer
|
||||
lookup_field = 'username'
|
||||
|
||||
@detail_route()
|
||||
@action(detail=True)
|
||||
def group_names(self, request, pk=None):
|
||||
"""
|
||||
Returns a list of all the group names that the given
|
||||
|
@ -291,7 +296,7 @@ The following mappings would be generated...
|
|||
<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>
|
||||
<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.
|
||||
|
@ -300,7 +305,7 @@ For another example of setting the `.routes` attribute, see the source code for
|
|||
|
||||
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_base_name(self, viewset)` method, or else always explicitly set the `base_name` argument when registering your viewsets with the router.
|
||||
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
|
||||
|
||||
|
@ -323,13 +328,15 @@ The [wq.db package][wq.db] provides an advanced [ModelRouter][wq.db-router] clas
|
|||
|
||||
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]: http://guides.rubyonrails.org/routing.html
|
||||
[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]: http://wq.io/wq.db
|
||||
[wq.db-router]: http://wq.io/docs/router
|
||||
[drf-extensions]: http://chibisov.github.io/drf-extensions/docs/
|
||||
[drf-extensions-routers]: http://chibisov.github.io/drf-extensions/docs/#routers
|
||||
[drf-extensions-nested-viewsets]: http://chibisov.github.io/drf-extensions/docs/#nested-routes
|
||||
[drf-extensions-collection-level-controllers]: http://chibisov.github.io/drf-extensions/docs/#collection-level-controllers
|
||||
[drf-extensions-customizable-endpoint-names]: http://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name
|
||||
[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/1.11/topics/http/urls/#url-namespaces
|
||||
[include-api-reference]: https://docs.djangoproject.com/en/2.0/ref/urls/#include
|
||||
|
|
|
@ -1,6 +1,9 @@
|
|||
source: schemas.py
|
||||
---
|
||||
source:
|
||||
- schemas
|
||||
---
|
||||
|
||||
# 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.
|
||||
>
|
||||
|
@ -10,301 +13,77 @@ 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.
|
||||
|
||||
## Install Core API
|
||||
Django REST Framework provides support for automatic generation of
|
||||
[OpenAPI][openapi] schemas.
|
||||
|
||||
You'll need to install the `coreapi` package in order to add schema support
|
||||
for REST framework.
|
||||
## Generating an OpenAPI Schema
|
||||
|
||||
pip install coreapi
|
||||
### Install `pyyaml`
|
||||
|
||||
## Internal schema representation
|
||||
You'll need to install `pyyaml`, so that you can render your generated schema
|
||||
into the commonly used YAML-based OpenAPI format.
|
||||
|
||||
REST framework uses [Core API][coreapi] in order to model schema information in
|
||||
a format-independent representation. This information can then be rendered
|
||||
into various different schema formats, or used to generate API documentation.
|
||||
pip install pyyaml
|
||||
|
||||
When using Core API, a schema is represented as a `Document` which is the
|
||||
top-level container object for information about the API. Available API
|
||||
interactions are represented using `Link` objects. Each link includes a URL,
|
||||
HTTP method, and may include a list of `Field` instances, which describe any
|
||||
parameters that may be accepted by the API endpoint. The `Link` and `Field`
|
||||
instances may also include descriptions, that allow an API schema to be
|
||||
rendered into user documentation.
|
||||
### Generating a static schema with the `generateschema` management command
|
||||
|
||||
Here's an example of an API description that includes a single `search`
|
||||
endpoint:
|
||||
If your schema is static, you can use the `generateschema` management command:
|
||||
|
||||
coreapi.Document(
|
||||
title='Flight Search API',
|
||||
url='https://api.example.org/',
|
||||
content={
|
||||
'search': coreapi.Link(
|
||||
url='/search/',
|
||||
action='get',
|
||||
fields=[
|
||||
coreapi.Field(
|
||||
name='from',
|
||||
required=True,
|
||||
location='query',
|
||||
description='City name or airport code.'
|
||||
),
|
||||
coreapi.Field(
|
||||
name='to',
|
||||
required=True,
|
||||
location='query',
|
||||
description='City name or airport code.'
|
||||
),
|
||||
coreapi.Field(
|
||||
name='date',
|
||||
required=True,
|
||||
location='query',
|
||||
description='Flight date in "YYYY-MM-DD" format.'
|
||||
)
|
||||
],
|
||||
description='Return flight availability and prices.'
|
||||
)
|
||||
}
|
||||
)
|
||||
```bash
|
||||
./manage.py generateschema > openapi-schema.yml
|
||||
```
|
||||
|
||||
## Schema output formats
|
||||
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.
|
||||
|
||||
In order to be presented in an HTTP response, the internal representation
|
||||
has to be rendered into the actual bytes that are used in the response.
|
||||
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.
|
||||
|
||||
[Core JSON][corejson] is designed as a canonical format for use with Core API.
|
||||
REST framework includes a renderer class for handling this media type, which
|
||||
is available as `renderers.CoreJSONRenderer`.
|
||||
### Generating a dynamic schema with `SchemaView`
|
||||
|
||||
### Alternate schema formats
|
||||
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.
|
||||
|
||||
Other schema formats such as [Open API][open-api] ("Swagger"),
|
||||
[JSON HyperSchema][json-hyperschema], or [API Blueprint][api-blueprint] can also
|
||||
be supported by implementing a custom renderer class that handles converting a
|
||||
`Document` instance into a bytestring representation.
|
||||
To route a `SchemaView`, use the `get_schema_view()` helper.
|
||||
|
||||
If there is a Core API codec package that supports encoding into the format you
|
||||
want to use then implementing the renderer class can be done by using the codec.
|
||||
|
||||
#### Example
|
||||
|
||||
For example, the `openapi_codec` package provides support for encoding or decoding
|
||||
to the Open API ("Swagger") format:
|
||||
|
||||
from rest_framework import renderers
|
||||
from openapi_codec import OpenAPICodec
|
||||
|
||||
class SwaggerRenderer(renderers.BaseRenderer):
|
||||
media_type = 'application/openapi+json'
|
||||
format = 'swagger'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
codec = OpenAPICodec()
|
||||
return codec.dump(data)
|
||||
|
||||
|
||||
|
||||
|
||||
## Schemas vs Hypermedia
|
||||
|
||||
It's worth pointing out here that Core API can also be used to model hypermedia
|
||||
responses, which present an alternative interaction style to API schemas.
|
||||
|
||||
With an API schema, the entire available interface is presented up-front
|
||||
as a single endpoint. Responses to individual API endpoints are then typically
|
||||
presented as plain data, without any further interactions contained in each
|
||||
response.
|
||||
|
||||
With Hypermedia, the client is instead presented with a document containing
|
||||
both data and available interactions. Each interaction results in a new
|
||||
document, detailing both the current state and the available interactions.
|
||||
|
||||
Further information and support on building Hypermedia APIs with REST framework
|
||||
is planned for a future version.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Creating a schema
|
||||
|
||||
REST framework includes functionality for auto-generating a schema,
|
||||
or allows you to specify one explicitly.
|
||||
|
||||
## Manual Schema Specification
|
||||
|
||||
To manually specify a schema you create a Core API `Document`, similar to the
|
||||
example above.
|
||||
|
||||
schema = coreapi.Document(
|
||||
title='Flight Search API',
|
||||
content={
|
||||
...
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
## Automatic Schema Generation
|
||||
|
||||
Automatic schema generation is provided by the `SchemaGenerator` class.
|
||||
|
||||
`SchemaGenerator` processes a list of routed URL pattterns and compiles the
|
||||
appropriately structured Core API Document.
|
||||
|
||||
Basic usage is just to provide the title for your schema and call
|
||||
`get_schema()`:
|
||||
|
||||
generator = schemas.SchemaGenerator(title='Flight Search API')
|
||||
schema = generator.get_schema()
|
||||
|
||||
## Per-View Schema Customisation
|
||||
|
||||
By default, view introspection is performed by an `AutoSchema` instance
|
||||
accessible via the `schema` attribute on `APIView`. This provides the
|
||||
appropriate Core API `Link` object for the view, request method and path:
|
||||
|
||||
auto_schema = view.schema
|
||||
coreapi_link = auto_schema.get_link(...)
|
||||
|
||||
(In compiling the schema, `SchemaGenerator` calls `view.schema.get_link()` for
|
||||
each view, allowed method and path.)
|
||||
|
||||
---
|
||||
|
||||
**Note**: For basic `APIView` subclasses, default introspection is essentially
|
||||
limited to the URL kwarg path parameters. For `GenericAPIView`
|
||||
subclasses, which includes all the provided class based views, `AutoSchema` will
|
||||
attempt to introspect serialiser, pagination and filter fields, as well as
|
||||
provide richer path field descriptions. (The key hooks here are the relevant
|
||||
`GenericAPIView` attributes and methods: `get_serializer`, `pagination_class`,
|
||||
`filter_backends` and so on.)
|
||||
|
||||
---
|
||||
|
||||
To customise the `Link` generation you may:
|
||||
|
||||
* Instantiate `AutoSchema` on your view with the `manual_fields` kwarg:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import AutoSchema
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = AutoSchema(
|
||||
manual_fields=[
|
||||
coreapi.Field("extra_field", ...),
|
||||
]
|
||||
)
|
||||
|
||||
This allows extension for the most common case without subclassing.
|
||||
|
||||
* Provide an `AutoSchema` subclass with more complex customisation:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import AutoSchema
|
||||
|
||||
class CustomSchema(AutoSchema):
|
||||
def get_link(...):
|
||||
# Implement custom introspection here (or in other sub-methods)
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = CustomSchema()
|
||||
|
||||
This provides complete control over view introspection.
|
||||
|
||||
* Instantiate `ManualSchema` on your view, providing the Core API `Fields` for
|
||||
the view explicitly:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import ManualSchema
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = ManualSchema(fields=[
|
||||
coreapi.Field(
|
||||
"first_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
coreapi.Field(
|
||||
"second_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
])
|
||||
|
||||
This allows manually specifying the schema for some views whilst maintaining
|
||||
automatic generation elsewhere.
|
||||
|
||||
You may disable schema generation for a view by setting `schema` to `None`:
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = None # Will not appear in schema
|
||||
|
||||
---
|
||||
|
||||
**Note**: For full details on `SchemaGenerator` plus the `AutoSchema` and
|
||||
`ManualSchema` descriptors see the [API Reference below](#api-reference).
|
||||
|
||||
---
|
||||
|
||||
# Adding a schema view
|
||||
|
||||
There are a few different ways to add a schema view to your API, depending on
|
||||
exactly what you need.
|
||||
|
||||
## The get_schema_view shortcut
|
||||
|
||||
The simplest way to include a schema in your project is to use the
|
||||
`get_schema_view()` function.
|
||||
In `urls.py`:
|
||||
|
||||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
|
||||
schema_view = get_schema_view(title="Server Monitoring API")
|
||||
|
||||
urlpatterns = [
|
||||
url('^$', schema_view),
|
||||
...
|
||||
# ...
|
||||
# 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'),
|
||||
# ...
|
||||
]
|
||||
```
|
||||
|
||||
Once the view has been added, you'll be able to make API requests to retrieve
|
||||
the auto-generated schema definition.
|
||||
#### `get_schema_view()`
|
||||
|
||||
$ http http://127.0.0.1:8000/ Accept:application/coreapi+json
|
||||
HTTP/1.0 200 OK
|
||||
Allow: GET, HEAD, OPTIONS
|
||||
Content-Type: application/vnd.coreapi+json
|
||||
The `get_schema_view()` helper takes the following keyword arguments:
|
||||
|
||||
{
|
||||
"_meta": {
|
||||
"title": "Server Monitoring API"
|
||||
},
|
||||
"_type": "document",
|
||||
...
|
||||
}
|
||||
|
||||
The arguments to `get_schema_view()` are:
|
||||
|
||||
#### `title`
|
||||
|
||||
May be used to provide a descriptive title for the schema definition.
|
||||
|
||||
#### `url`
|
||||
|
||||
May be used to pass a canonical URL for the schema.
|
||||
* `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
|
||||
* `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.
|
||||
`ROOT_URLCONF` setting.
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
|
@ -312,24 +91,8 @@ ROOT_URLCONF setting.
|
|||
urlconf='myproject.urls'
|
||||
)
|
||||
|
||||
#### `renderer_classes`
|
||||
|
||||
May be used to pass the set of renderer classes that can be used to render the API root endpoint.
|
||||
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework.renderers import CoreJSONRenderer
|
||||
from my_custom_package import APIBlueprintRenderer
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
renderer_classes=[CoreJSONRenderer, APIBlueprintRenderer]
|
||||
)
|
||||
|
||||
#### `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:
|
||||
* `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 = [
|
||||
url(r'^api/', include('myproject.api.urls')),
|
||||
|
@ -341,483 +104,117 @@ to be exposed in the schema:
|
|||
patterns=schema_url_patterns,
|
||||
)
|
||||
|
||||
#### `generator_class`
|
||||
* `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.
|
||||
|
||||
May be used to specify a `SchemaGenerator` subclass to be passed to the
|
||||
`SchemaView`.
|
||||
## Customizing Schema Generation
|
||||
|
||||
#### `authentication_classes`
|
||||
You may customize schema generation at the level of the schema as a whole, or
|
||||
on a per-view basis.
|
||||
|
||||
May be used to specify the list of authentication classes that will apply to the schema endpoint.
|
||||
Defaults to `settings.DEFAULT_AUTHENTICATION_CLASSES`
|
||||
### Schema Level Customization
|
||||
|
||||
#### `permission_classes`
|
||||
In order to customize the top-level schema sublass
|
||||
`rest_framework.schemas.openapi.SchemaGenerator` and provide it as an argument
|
||||
to the `generateschema` command or `get_schema_view()` helper function.
|
||||
|
||||
May be used to specify the list of permission classes that will apply to the schema endpoint.
|
||||
Defaults to `settings.DEFAULT_PERMISSION_CLASSES`
|
||||
#### SchemaGenerator
|
||||
|
||||
A class that walks a list of routed URL patterns, requests the schema for each
|
||||
view and collates the resulting OpenAPI schema.
|
||||
|
||||
## Using an explicit schema view
|
||||
|
||||
If you need a little more control than the `get_schema_view()` shortcut gives you,
|
||||
then you can use the `SchemaGenerator` class directly to auto-generate the
|
||||
`Document` instance, and to return that from a view.
|
||||
|
||||
This option gives you the flexibility of setting up the schema endpoint
|
||||
with whatever behaviour you want. For example, you can apply different
|
||||
permission, throttling, or authentication policies to the schema endpoint.
|
||||
|
||||
Here's an example of using `SchemaGenerator` together with a view to
|
||||
return the schema.
|
||||
|
||||
**views.py:**
|
||||
|
||||
from rest_framework.decorators import api_view, renderer_classes
|
||||
from rest_framework import renderers, response, schemas
|
||||
|
||||
generator = schemas.SchemaGenerator(title='Bookings API')
|
||||
|
||||
@api_view()
|
||||
@renderer_classes([renderers.CoreJSONRenderer])
|
||||
def schema_view(request):
|
||||
schema = generator.get_schema(request)
|
||||
return response.Response(schema)
|
||||
|
||||
**urls.py:**
|
||||
|
||||
urlpatterns = [
|
||||
url('/', schema_view),
|
||||
...
|
||||
]
|
||||
|
||||
You can also serve different schemas to different users, depending on the
|
||||
permissions they have available. This approach can be used to ensure that
|
||||
unauthenticated requests are presented with a different schema to
|
||||
authenticated requests, or to ensure that different parts of the API are
|
||||
made visible to different users depending on their role.
|
||||
|
||||
In order to present a schema with endpoints filtered by user permissions,
|
||||
you need to pass the `request` argument to the `get_schema()` method, like so:
|
||||
|
||||
@api_view()
|
||||
@renderer_classes([renderers.CoreJSONRenderer])
|
||||
def schema_view(request):
|
||||
generator = schemas.SchemaGenerator(title='Bookings API')
|
||||
return response.Response(generator.get_schema(request=request))
|
||||
|
||||
## Explicit schema definition
|
||||
|
||||
An alternative to the auto-generated approach is to specify the API schema
|
||||
explicitly, by declaring a `Document` object in your codebase. Doing so is a
|
||||
little more work, but ensures that you have full control over the schema
|
||||
representation.
|
||||
|
||||
import coreapi
|
||||
from rest_framework.decorators import api_view, renderer_classes
|
||||
from rest_framework import renderers, response
|
||||
|
||||
schema = coreapi.Document(
|
||||
title='Bookings API',
|
||||
content={
|
||||
...
|
||||
}
|
||||
)
|
||||
|
||||
@api_view()
|
||||
@renderer_classes([renderers.CoreJSONRenderer])
|
||||
def schema_view(request):
|
||||
return response.Response(schema)
|
||||
|
||||
## Static schema file
|
||||
|
||||
A final option is to write your API schema as a static file, using one
|
||||
of the available formats, such as Core JSON or Open API.
|
||||
|
||||
You could then either:
|
||||
|
||||
* Write a schema definition as a static file, and [serve the static file directly][static-files].
|
||||
* Write a schema definition that is loaded using `Core API`, and then
|
||||
rendered to one of many available formats, depending on the client request.
|
||||
|
||||
---
|
||||
|
||||
# Schemas as documentation
|
||||
|
||||
One common usage of API schemas is to use them to build documentation pages.
|
||||
|
||||
The schema generation in REST framework uses docstrings to automatically
|
||||
populate descriptions in the schema document.
|
||||
|
||||
These descriptions will be based on:
|
||||
|
||||
* The corresponding method docstring if one exists.
|
||||
* A named section within the class docstring, which can be either single line or multi-line.
|
||||
* The class docstring.
|
||||
|
||||
## Examples
|
||||
|
||||
An `APIView`, with an explicit method docstring.
|
||||
|
||||
class ListUsernames(APIView):
|
||||
def get(self, request):
|
||||
"""
|
||||
Return a list of all user names in the system.
|
||||
"""
|
||||
usernames = [user.username for user in User.objects.all()]
|
||||
return Response(usernames)
|
||||
|
||||
A `ViewSet`, with an explict action docstring.
|
||||
|
||||
class ListUsernames(ViewSet):
|
||||
def list(self, request):
|
||||
"""
|
||||
Return a list of all user names in the system.
|
||||
"""
|
||||
usernames = [user.username for user in User.objects.all()]
|
||||
return Response(usernames)
|
||||
|
||||
A generic view with sections in the class docstring, using single-line style.
|
||||
|
||||
class UserList(generics.ListCreateAPIView):
|
||||
"""
|
||||
get: List all the users.
|
||||
post: Create a new user.
|
||||
"""
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = (IsAdminUser,)
|
||||
|
||||
A generic viewset with sections in the class docstring, using multi-line style.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
API endpoint that allows users to be viewed or edited.
|
||||
|
||||
retrieve:
|
||||
Return a user instance.
|
||||
|
||||
list:
|
||||
Return all users, ordered by most recently joined.
|
||||
"""
|
||||
queryset = User.objects.all().order_by('-date_joined')
|
||||
serializer_class = UserSerializer
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## SchemaGenerator
|
||||
|
||||
A class that walks a list of routed URL patterns, requests the schema for each view,
|
||||
and collates the resulting CoreAPI Document.
|
||||
|
||||
Typically you'll instantiate `SchemaGenerator` with a single argument, like so:
|
||||
Typically you'll instantiate `SchemaGenerator` with a `title` argument, like so:
|
||||
|
||||
generator = SchemaGenerator(title='Stock Prices API')
|
||||
|
||||
Arguments:
|
||||
|
||||
* `title` **required** - The name of the API.
|
||||
* `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`.
|
||||
* `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`.
|
||||
|
||||
### get_schema(self, request)
|
||||
##### get_schema(self, request)
|
||||
|
||||
Returns a `coreapi.Document` instance that represents the API schema.
|
||||
Returns a dictionary that represents the OpenAPI schema:
|
||||
|
||||
@api_view
|
||||
@renderer_classes([renderers.CoreJSONRenderer])
|
||||
def schema_view(request):
|
||||
generator = schemas.SchemaGenerator(title='Bookings API')
|
||||
return Response(generator.get_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.
|
||||
The `request` argument is optional, and may be used if you want to apply
|
||||
per-user permissions to the resulting schema generation.
|
||||
|
||||
### get_links(self, request)
|
||||
This is a good point to override if you want to customize the generated
|
||||
dictionary, for example to add custom
|
||||
[specification extensions][openapi-specification-extensions].
|
||||
|
||||
Return a nested dictionary containing all the links that should be included in the API schema.
|
||||
### Per-View Customization
|
||||
|
||||
This is a good point to override if you want to modify the resulting structure of the generated schema,
|
||||
as you can build a new dictionary with a different layout.
|
||||
By default, view introspection is performed by an `AutoSchema` instance
|
||||
accessible via the `schema` attribute on `APIView`. This provides the
|
||||
appropriate [Open API operation object][openapi-operation] for the view,
|
||||
request method and path:
|
||||
|
||||
auto_schema = view.schema
|
||||
operation = auto_schema.get_operation(...)
|
||||
|
||||
## AutoSchema
|
||||
In compiling the schema, `SchemaGenerator` calls `view.schema.get_operation()`
|
||||
for each view, allowed method, and path.
|
||||
|
||||
A class that deals with introspection of individual views for schema generation.
|
||||
---
|
||||
|
||||
`AutoSchema` is attached to `APIView` via the `schema` attribute.
|
||||
**Note**: For basic `APIView` subclasses, default introspection is essentially
|
||||
limited to the URL kwarg path parameters. For `GenericAPIView`
|
||||
subclasses, which includes all the provided class based views, `AutoSchema` will
|
||||
attempt to introspect serializer, pagination and filter fields, as well as
|
||||
provide richer path field descriptions. (The key hooks here are the relevant
|
||||
`GenericAPIView` attributes and methods: `get_serializer`, `pagination_class`,
|
||||
`filter_backends` and so on.)
|
||||
|
||||
The `AutoSchema` constructor takes a single keyword argument `manual_fields`.
|
||||
---
|
||||
|
||||
**`manual_fields`**: a `list` of `coreapi.Field` instances that will be added to
|
||||
the generated fields. Generated fields with a matching `name` will be overwritten.
|
||||
In order to customize the operation generation, you should provide an `AutoSchema` subclass, overriding `get_operation()` as you need:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas.openapi import AutoSchema
|
||||
|
||||
class CustomSchema(AutoSchema):
|
||||
def get_operation(...):
|
||||
# Implement custom introspection here (or in other sub-methods)
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = AutoSchema(manual_fields=[
|
||||
coreapi.Field(
|
||||
"my_extra_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
])
|
||||
"""APIView subclass with custom schema introspection."""
|
||||
schema = CustomSchema()
|
||||
|
||||
For more advanced customisation subclass `AutoSchema` to customise schema generation.
|
||||
This provides complete control over view introspection.
|
||||
|
||||
class CustomViewSchema(AutoSchema):
|
||||
"""
|
||||
Overrides `get_link()` to provide Custom Behavior X
|
||||
"""
|
||||
You may disable schema generation for a view by setting `schema` to `None`:
|
||||
|
||||
def get_link(self, path, method, base_url):
|
||||
link = super().get_link(path, method, base_url)
|
||||
# Do something to customize link here...
|
||||
return link
|
||||
|
||||
class MyView(APIView):
|
||||
schema = CustomViewSchema()
|
||||
|
||||
The following methods are available to override.
|
||||
|
||||
### get_link(self, path, method, base_url)
|
||||
|
||||
Returns a `coreapi.Link` instance corresponding to the given view.
|
||||
|
||||
This is the main entry point.
|
||||
You can override this if you need to provide custom behaviors for particular views.
|
||||
|
||||
### get_description(self, path, method)
|
||||
|
||||
Returns a string to use as the link description. By default this is based on the
|
||||
view docstring as described in the "Schemas as Documentation" section above.
|
||||
|
||||
### get_encoding(self, path, method)
|
||||
|
||||
Returns a string to indicate the encoding for any request body, when interacting
|
||||
with the given view. Eg. `'application/json'`. May return a blank string for views
|
||||
that do not expect a request body.
|
||||
|
||||
### get_path_fields(self, path, method):
|
||||
|
||||
Return a list of `coreapi.Link()` instances. One for each path parameter in the URL.
|
||||
|
||||
### get_serializer_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Link()` instances. One for each field in the serializer class used by the view.
|
||||
|
||||
### get_pagination_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Link()` instances, as returned by the `get_schema_fields()` method on any pagination class used by the view.
|
||||
|
||||
### get_filter_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Link()` instances, as returned by the `get_schema_fields()` method of any filter classes used by the view.
|
||||
|
||||
### get_manual_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances to be added to or replace generated fields. Defaults to (optional) `manual_fields` passed to `AutoSchema` constructor.
|
||||
|
||||
May be overridden to customise manual fields by `path` or `method`. For example, a per-method adjustment may look like this:
|
||||
|
||||
```python
|
||||
def get_manual_fields(self, path, method):
|
||||
"""Example adding per-method fields."""
|
||||
|
||||
extra_fields = []
|
||||
if method=='GET':
|
||||
extra_fields = # ... list of extra fields for GET ...
|
||||
if method=='POST':
|
||||
extra_fields = # ... list of extra fields for POST ...
|
||||
|
||||
manual_fields = super().get_manual_fields()
|
||||
return manual_fields + extra_fields
|
||||
```
|
||||
|
||||
### update_fields(fields, update_with)
|
||||
|
||||
Utility `staticmethod`. Encapsulates logic to add or replace fields from a list
|
||||
by `Field.name`. May be overridden to adjust replacement criteria.
|
||||
|
||||
|
||||
## ManualSchema
|
||||
|
||||
Allows manually providing a list of `coreapi.Field` instances for the schema,
|
||||
plus an optional description.
|
||||
|
||||
class MyView(APIView):
|
||||
schema = ManualSchema(fields=[
|
||||
coreapi.Field(
|
||||
"first_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
coreapi.Field(
|
||||
"second_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
The `ManualSchema` constructor takes two arguments:
|
||||
|
||||
**`fields`**: A list of `coreapi.Field` instances. Required.
|
||||
|
||||
**`description`**: A string description. Optional.
|
||||
|
||||
---
|
||||
|
||||
## Core API
|
||||
|
||||
This documentation gives a brief overview of the components within the `coreapi`
|
||||
package that are used to represent an API schema.
|
||||
|
||||
Note that these classes are imported from the `coreapi` package, rather than
|
||||
from the `rest_framework` package.
|
||||
|
||||
### Document
|
||||
|
||||
Represents a container for the API schema.
|
||||
|
||||
#### `title`
|
||||
|
||||
A name for the API.
|
||||
|
||||
#### `url`
|
||||
|
||||
A canonical URL for the API.
|
||||
|
||||
#### `content`
|
||||
|
||||
A dictionary, containing the `Link` objects that the schema contains.
|
||||
|
||||
In order to provide more structure to the schema, the `content` dictionary
|
||||
may be nested, typically to a second level. For example:
|
||||
|
||||
content={
|
||||
"bookings": {
|
||||
"list": Link(...),
|
||||
"create": Link(...),
|
||||
class CustomView(APIView):
|
||||
...
|
||||
},
|
||||
"venues": {
|
||||
"list": Link(...),
|
||||
schema = None # Will not appear in schema
|
||||
|
||||
This also applies to extra actions for `ViewSet`s:
|
||||
|
||||
class CustomViewSet(viewsets.ModelViewSet):
|
||||
|
||||
@action(detail=True, schema=None)
|
||||
def extra_action(self, request, pk=None):
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
### Link
|
||||
If you wish to provide a base `AutoSchema` subclass to be used throughout your
|
||||
project you may adjust `settings.DEFAULT_SCHEMA_CLASS` appropriately.
|
||||
|
||||
Represents an individual API endpoint.
|
||||
|
||||
#### `url`
|
||||
|
||||
The URL of the endpoint. May be a URI template, such as `/users/{username}/`.
|
||||
|
||||
#### `action`
|
||||
|
||||
The HTTP method associated with the endpoint. Note that URLs that support
|
||||
more than one HTTP method, should correspond to a single `Link` for each.
|
||||
|
||||
#### `fields`
|
||||
|
||||
A list of `Field` instances, describing the available parameters on the input.
|
||||
|
||||
#### `description`
|
||||
|
||||
A short description of the meaning and intended usage of the endpoint.
|
||||
|
||||
### Field
|
||||
|
||||
Represents a single input parameter on a given API endpoint.
|
||||
|
||||
#### `name`
|
||||
|
||||
A descriptive name for the input.
|
||||
|
||||
#### `required`
|
||||
|
||||
A boolean, indicated if the client is required to included a value, or if
|
||||
the parameter can be omitted.
|
||||
|
||||
#### `location`
|
||||
|
||||
Determines how the information is encoded into the request. Should be one of
|
||||
the following strings:
|
||||
|
||||
**"path"**
|
||||
|
||||
Included in a templated URI. For example a `url` value of `/products/{product_code}/` could be used together with a `"path"` field, to handle API inputs in a URL path such as `/products/slim-fit-jeans/`.
|
||||
|
||||
These fields will normally correspond with [named arguments in the project URL conf][named-arguments].
|
||||
|
||||
**"query"**
|
||||
|
||||
Included as a URL query parameter. For example `?search=sale`. Typically for `GET` requests.
|
||||
|
||||
These fields will normally correspond with pagination and filtering controls on a view.
|
||||
|
||||
**"form"**
|
||||
|
||||
Included in the request body, as a single item of a JSON object or HTML form. For example `{"colour": "blue", ...}`. Typically for `POST`, `PUT` and `PATCH` requests. Multiple `"form"` fields may be included on a single link.
|
||||
|
||||
These fields will normally correspond with serializer fields on a view.
|
||||
|
||||
**"body"**
|
||||
|
||||
Included as the complete request body. Typically for `POST`, `PUT` and `PATCH` requests. No more than one `"body"` field may exist on a link. May not be used together with `"form"` fields.
|
||||
|
||||
These fields will normally correspond with views that use `ListSerializer` to validate the request input, or with file upload views.
|
||||
|
||||
#### `encoding`
|
||||
|
||||
**"application/json"**
|
||||
|
||||
JSON encoded request content. Corresponds to views using `JSONParser`.
|
||||
Valid only if either one or more `location="form"` fields, or a single
|
||||
`location="body"` field is included on the `Link`.
|
||||
|
||||
**"multipart/form-data"**
|
||||
|
||||
Multipart encoded request content. Corresponds to views using `MultiPartParser`.
|
||||
Valid only if one or more `location="form"` fields is included on the `Link`.
|
||||
|
||||
**"application/x-www-form-urlencoded"**
|
||||
|
||||
URL encoded request content. Corresponds to views using `FormParser`. Valid
|
||||
only if one or more `location="form"` fields is included on the `Link`.
|
||||
|
||||
**"application/octet-stream"**
|
||||
|
||||
Binary upload request content. Corresponds to views using `FileUploadParser`.
|
||||
Valid only if a `location="body"` field is included on the `Link`.
|
||||
|
||||
#### `description`
|
||||
|
||||
A short description of the meaning and intended usage of the input field.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Third party packages
|
||||
|
||||
## DRF OpenAPI
|
||||
|
||||
[DRF OpenAPI][drf-openapi] renders the schema generated by Django Rest Framework
|
||||
in [OpenAPI][open-api] format.
|
||||
|
||||
|
||||
[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api
|
||||
[coreapi]: http://www.coreapi.org/
|
||||
[corejson]: http://www.coreapi.org/specification/encoding/#core-json-encoding
|
||||
[open-api]: https://openapis.org/
|
||||
[drf-openapi]: https://github.com/limdauto/drf_openapi
|
||||
[json-hyperschema]: http://json-schema.org/latest/json-schema-hypermedia.html
|
||||
[api-blueprint]: https://apiblueprint.org/
|
||||
[static-files]: https://docs.djangoproject.com/en/stable/howto/static-files/
|
||||
[named-arguments]: https://docs.djangoproject.com/en/stable/topics/http/urls/#named-groups
|
||||
[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
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: serializers.py
|
||||
---
|
||||
source:
|
||||
- serializers.py
|
||||
---
|
||||
|
||||
# Serializers
|
||||
|
||||
|
@ -57,10 +60,10 @@ At this point we've translated the model instance into Python native datatypes.
|
|||
|
||||
Deserialization is similar. First we parse a stream into Python native datatypes...
|
||||
|
||||
from django.utils.six import BytesIO
|
||||
import io
|
||||
from rest_framework.parsers import JSONParser
|
||||
|
||||
stream = BytesIO(json)
|
||||
stream = io.BytesIO(json)
|
||||
data = JSONParser().parse(stream)
|
||||
|
||||
...then we restore those native datatypes into a dictionary of validated data.
|
||||
|
@ -73,7 +76,7 @@ Deserialization is similar. First we parse a stream into Python native datatypes
|
|||
|
||||
## Saving instances
|
||||
|
||||
If we want to be able to return complete object instances based on the validated data we need to implement one or both of the `.create()` and `update()` methods. For example:
|
||||
If we want to be able to return complete object instances based on the validated data we need to implement one or both of the `.create()` and `.update()` methods. For example:
|
||||
|
||||
class CommentSerializer(serializers.Serializer):
|
||||
email = serializers.EmailField()
|
||||
|
@ -152,7 +155,7 @@ When deserializing data, you always need to call `is_valid()` before attempting
|
|||
serializer.is_valid()
|
||||
# False
|
||||
serializer.errors
|
||||
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
|
||||
# {'email': ['Enter a valid e-mail address.'], 'created': ['This field is required.']}
|
||||
|
||||
Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The `non_field_errors` key may also be present, and will list any general validation errors. The name of the `non_field_errors` key may be customized using the `NON_FIELD_ERRORS_KEY` REST framework setting.
|
||||
|
||||
|
@ -197,7 +200,7 @@ Your `validate_<field_name>` methods should return the validated value or raise
|
|||
|
||||
#### Object-level validation
|
||||
|
||||
To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is a dictionary of field values. It should raise a `ValidationError` if necessary, or just return the validated values. For example:
|
||||
To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is a dictionary of field values. It should raise a `serializers.ValidationError` if necessary, or just return the validated values. For example:
|
||||
|
||||
from rest_framework import serializers
|
||||
|
||||
|
@ -208,7 +211,7 @@ To do any other validation that requires access to multiple fields, add a method
|
|||
|
||||
def validate(self, data):
|
||||
"""
|
||||
Check that the start is before the stop.
|
||||
Check that start is before finish.
|
||||
"""
|
||||
if data['start'] > data['finish']:
|
||||
raise serializers.ValidationError("finish must occur after start")
|
||||
|
@ -253,7 +256,7 @@ When passing data to a serializer instance, the unmodified data will be made ava
|
|||
By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the `partial` argument in order to allow partial updates.
|
||||
|
||||
# Update `comment` with partial data
|
||||
serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)
|
||||
serializer = CommentSerializer(comment, data={'content': 'foo bar'}, partial=True)
|
||||
|
||||
## Dealing with nested objects
|
||||
|
||||
|
@ -293,7 +296,7 @@ When dealing with nested representations that support deserializing the data, an
|
|||
serializer.is_valid()
|
||||
# False
|
||||
serializer.errors
|
||||
# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']}
|
||||
# {'user': {'email': ['Enter a valid e-mail address.']}, 'created': ['This field is required.']}
|
||||
|
||||
Similarly, the `.validated_data` property will include nested data structures.
|
||||
|
||||
|
@ -308,7 +311,7 @@ The following example demonstrates how you might handle creating a user with a n
|
|||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ('username', 'email', 'profile')
|
||||
fields = ['username', 'email', 'profile']
|
||||
|
||||
def create(self, validated_data):
|
||||
profile_data = validated_data.pop('profile')
|
||||
|
@ -325,7 +328,7 @@ For updates you'll want to think carefully about how to handle updates to relati
|
|||
* Ignore the data and leave the instance as it is.
|
||||
* Raise a validation error.
|
||||
|
||||
Here's an example for an `update()` method on our previous `UserSerializer` class.
|
||||
Here's an example for an `.update()` method on our previous `UserSerializer` class.
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
profile_data = validated_data.pop('profile')
|
||||
|
@ -352,7 +355,7 @@ Here's an example for an `update()` method on our previous `UserSerializer` clas
|
|||
|
||||
Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default `ModelSerializer` `.create()` and `.update()` methods do not include support for writable nested representations.
|
||||
|
||||
It is possible that a third party package, providing automatic support some kinds of automatic writable nested representations may be released alongside the 3.1 release.
|
||||
There are however, third-party packages available such as [DRF Writable Nested][thirdparty-writable-nested] that support automatic writable nested representations.
|
||||
|
||||
#### Handling saving related instances in model manager classes
|
||||
|
||||
|
@ -415,7 +418,7 @@ You can provide arbitrary additional context by passing a `context` argument whe
|
|||
|
||||
serializer = AccountSerializer(account, context={'request': request})
|
||||
serializer.data
|
||||
# {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}
|
||||
# {'id': 6, 'owner': 'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}
|
||||
|
||||
The context dictionary can be used within any serializer field logic, such as a custom `.to_representation()` method, by accessing the `self.context` attribute.
|
||||
|
||||
|
@ -438,7 +441,7 @@ Declaring a `ModelSerializer` looks like this:
|
|||
class AccountSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ('id', 'account_name', 'users', 'created')
|
||||
fields = ['id', 'account_name', 'users', 'created']
|
||||
|
||||
By default, all the model fields on the class will be mapped to a corresponding serializer fields.
|
||||
|
||||
|
@ -467,7 +470,7 @@ For example:
|
|||
class AccountSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ('id', 'account_name', 'users', 'created')
|
||||
fields = ['id', 'account_name', 'users', 'created']
|
||||
|
||||
You can also set the `fields` attribute to the special value `'__all__'` to indicate that all fields in the model should be used.
|
||||
|
||||
|
@ -485,7 +488,7 @@ For example:
|
|||
class AccountSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Account
|
||||
exclude = ('users',)
|
||||
exclude = ['users']
|
||||
|
||||
In the example above, if the `Account` model had 3 fields `account_name`, `users`, and `created`, this will result in the fields `account_name` and `created` to be serialized.
|
||||
|
||||
|
@ -502,7 +505,7 @@ The default `ModelSerializer` uses primary keys for relationships, but you can a
|
|||
class AccountSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ('id', 'account_name', 'users', 'created')
|
||||
fields = ['id', 'account_name', 'users', 'created']
|
||||
depth = 1
|
||||
|
||||
The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
|
||||
|
@ -531,8 +534,8 @@ This option should be a list or tuple of field names, and is declared as follows
|
|||
class AccountSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ('id', 'account_name', 'users', 'created')
|
||||
read_only_fields = ('account_name',)
|
||||
fields = ['id', 'account_name', 'users', 'created']
|
||||
read_only_fields = ['account_name']
|
||||
|
||||
Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option.
|
||||
|
||||
|
@ -560,7 +563,7 @@ This option is a dictionary, mapping field names to a dictionary of keyword argu
|
|||
class CreateUserSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ('email', 'username', 'password')
|
||||
fields = ['email', 'username', 'password']
|
||||
extra_kwargs = {'password': {'write_only': True}}
|
||||
|
||||
def create(self, validated_data):
|
||||
|
@ -572,6 +575,8 @@ This option is a dictionary, mapping field names to a dictionary of keyword argu
|
|||
user.save()
|
||||
return user
|
||||
|
||||
Please keep in mind that, if the field has already been explicitly declared on the serializer class, then the `extra_kwargs` option will be ignored.
|
||||
|
||||
## Relational fields
|
||||
|
||||
When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for `ModelSerializer` is to use the primary keys of the related instances.
|
||||
|
@ -624,7 +629,7 @@ The default implementation returns a serializer class based on the `serializer_f
|
|||
|
||||
Called to generate a serializer field that maps to a relational model field.
|
||||
|
||||
The default implementation returns a serializer class based on the `serializer_relational_field` attribute.
|
||||
The default implementation returns a serializer class based on the `serializer_related_field` attribute.
|
||||
|
||||
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
||||
|
||||
|
@ -668,7 +673,7 @@ You can explicitly include the primary key by adding it to the `fields` option,
|
|||
class AccountSerializer(serializers.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ('url', 'id', 'account_name', 'users', 'created')
|
||||
fields = ['url', 'id', 'account_name', 'users', 'created']
|
||||
|
||||
## Absolute and relative URLs
|
||||
|
||||
|
@ -700,7 +705,7 @@ You can override a URL field view name and lookup field by using either, or both
|
|||
class AccountSerializer(serializers.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ('account_url', 'account_name', 'users', 'created')
|
||||
fields = ['account_url', 'account_name', 'users', 'created']
|
||||
extra_kwargs = {
|
||||
'url': {'view_name': 'accounts', 'lookup_field': 'account_name'},
|
||||
'users': {'lookup_field': 'username'}
|
||||
|
@ -722,7 +727,7 @@ Alternatively you can set the fields on the serializer explicitly. For example:
|
|||
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ('url', 'account_name', 'users', 'created')
|
||||
fields = ['url', 'account_name', 'users', 'created']
|
||||
|
||||
---
|
||||
|
||||
|
@ -882,10 +887,10 @@ To implement a read-only serializer using the `BaseSerializer` class, we just ne
|
|||
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):
|
||||
def to_representation(self, instance):
|
||||
return {
|
||||
'score': obj.score,
|
||||
'player_name': obj.player_name
|
||||
'score': instance.score,
|
||||
'player_name': instance.player_name
|
||||
}
|
||||
|
||||
We can now use this class to serialize single `HighScore` instances:
|
||||
|
@ -906,7 +911,7 @@ Or use it to serialize multiple instances:
|
|||
|
||||
##### 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.
|
||||
To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `serializers.ValidationError` if the supplied data is in an incorrect format.
|
||||
|
||||
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`.
|
||||
|
||||
|
@ -921,15 +926,15 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
|
|||
|
||||
# Perform the data validation.
|
||||
if not score:
|
||||
raise ValidationError({
|
||||
raise serializers.ValidationError({
|
||||
'score': 'This field is required.'
|
||||
})
|
||||
if not player_name:
|
||||
raise ValidationError({
|
||||
raise serializers.ValidationError({
|
||||
'player_name': 'This field is required.'
|
||||
})
|
||||
if len(player_name) > 10:
|
||||
raise ValidationError({
|
||||
raise serializers.ValidationError({
|
||||
'player_name': 'May not be more than 10 characters.'
|
||||
})
|
||||
|
||||
|
@ -940,10 +945,10 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
|
|||
'player_name': player_name
|
||||
}
|
||||
|
||||
def to_representation(self, obj):
|
||||
def to_representation(self, instance):
|
||||
return {
|
||||
'score': obj.score,
|
||||
'player_name': obj.player_name
|
||||
'score': instance.score,
|
||||
'player_name': instance.player_name
|
||||
}
|
||||
|
||||
def create(self, validated_data):
|
||||
|
@ -960,10 +965,11 @@ The following class is an example of a generic serializer that can handle coerci
|
|||
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('_'):
|
||||
def to_representation(self, instance):
|
||||
output = {}
|
||||
for attribute_name in dir(instance):
|
||||
attribute = getattr(instance, attribute_name)
|
||||
if attribute_name.startswith('_'):
|
||||
# Ignore private attributes.
|
||||
pass
|
||||
elif hasattr(attribute, '__call__'):
|
||||
|
@ -986,6 +992,7 @@ The following class is an example of a generic serializer that can handle coerci
|
|||
else:
|
||||
# Force anything else to its string representation.
|
||||
output[attribute_name] = str(attribute)
|
||||
return output
|
||||
|
||||
---
|
||||
|
||||
|
@ -1003,10 +1010,18 @@ Some reasons this might be useful include...
|
|||
|
||||
The signatures for these methods are as follows:
|
||||
|
||||
#### `.to_representation(self, obj)`
|
||||
#### `.to_representation(self, instance)`
|
||||
|
||||
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
|
||||
|
||||
May be overridden in order to modify the representation style. For example:
|
||||
|
||||
def to_representation(self, instance):
|
||||
"""Convert `username` to lowercase."""
|
||||
ret = super().to_representation(instance)
|
||||
ret['username'] = ret['username'].lower()
|
||||
return ret
|
||||
|
||||
#### ``.to_internal_value(self, data)``
|
||||
|
||||
Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
|
||||
|
@ -1022,7 +1037,7 @@ Similar to Django forms, you can extend and reuse serializers through inheritanc
|
|||
class MyBaseSerializer(Serializer):
|
||||
my_field = serializers.CharField()
|
||||
|
||||
def validate_my_field(self):
|
||||
def validate_my_field(self, value):
|
||||
...
|
||||
|
||||
class MySerializer(MyBaseSerializer):
|
||||
|
@ -1075,7 +1090,7 @@ For example, if you wanted to be able to set which fields should be used by a se
|
|||
if fields is not None:
|
||||
# Drop any fields that are not specified in the `fields` argument.
|
||||
allowed = set(fields)
|
||||
existing = set(self.fields.keys())
|
||||
existing = set(self.fields)
|
||||
for field_name in existing - allowed:
|
||||
self.fields.pop(field_name)
|
||||
|
||||
|
@ -1084,12 +1099,12 @@ This would then allow you to do the following:
|
|||
>>> class UserSerializer(DynamicFieldsModelSerializer):
|
||||
>>> class Meta:
|
||||
>>> model = User
|
||||
>>> fields = ('id', 'username', 'email')
|
||||
>>> fields = ['id', 'username', 'email']
|
||||
>>>
|
||||
>>> print UserSerializer(user)
|
||||
>>> print(UserSerializer(user))
|
||||
{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}
|
||||
>>>
|
||||
>>> print UserSerializer(user, fields=('id', 'email'))
|
||||
>>> print(UserSerializer(user, fields=('id', 'email')))
|
||||
{'id': 2, 'email': 'jon@example.com'}
|
||||
|
||||
## Customizing the default fields
|
||||
|
@ -1164,8 +1179,9 @@ The [drf-writable-nested][drf-writable-nested] package provides writable nested
|
|||
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
|
||||
[relations]: relations.md
|
||||
[model-managers]: https://docs.djangoproject.com/en/stable/topics/db/managers/
|
||||
[encapsulation-blogpost]: http://www.dabapps.com/blog/django-models-and-encapsulation/
|
||||
[django-rest-marshmallow]: http://tomchristie.github.io/django-rest-marshmallow/
|
||||
[encapsulation-blogpost]: https://www.dabapps.com/blog/django-models-and-encapsulation/
|
||||
[thirdparty-writable-nested]: serializers.md#drf-writable-nested
|
||||
[django-rest-marshmallow]: https://marshmallow-code.github.io/django-rest-marshmallow/
|
||||
[marshmallow]: https://marshmallow.readthedocs.io/en/latest/
|
||||
[serpy]: https://github.com/clarkduvall/serpy
|
||||
[mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine
|
||||
|
@ -1179,5 +1195,5 @@ The [drf-writable-nested][drf-writable-nested] package provides writable nested
|
|||
[drf-dynamic-fields]: https://github.com/dbrgn/drf-dynamic-fields
|
||||
[drf-base64]: https://bitbucket.org/levit_scs/drf_base64
|
||||
[drf-serializer-extensions]: https://github.com/evenicoulddoit/django-rest-framework-serializer-extensions
|
||||
[djangorestframework-queryfields]: http://djangorestframework-queryfields.readthedocs.io/
|
||||
[drf-writable-nested]: http://github.com/beda-software/drf-writable-nested
|
||||
[djangorestframework-queryfields]: https://djangorestframework-queryfields.readthedocs.io/
|
||||
[drf-writable-nested]: https://github.com/beda-software/drf-writable-nested
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: settings.py
|
||||
---
|
||||
source:
|
||||
- settings.py
|
||||
---
|
||||
|
||||
# Settings
|
||||
|
||||
|
@ -11,12 +14,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': (
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
),
|
||||
'DEFAULT_PARSER_CLASSES': (
|
||||
],
|
||||
'DEFAULT_PARSER_CLASSES': [
|
||||
'rest_framework.parsers.JSONParser',
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
## Accessing settings
|
||||
|
@ -26,7 +29,7 @@ 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.
|
||||
|
||||
|
@ -44,10 +47,10 @@ A list or tuple of renderer classes, that determines the default set of renderer
|
|||
|
||||
Default:
|
||||
|
||||
(
|
||||
[
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
)
|
||||
]
|
||||
|
||||
#### DEFAULT_PARSER_CLASSES
|
||||
|
||||
|
@ -55,11 +58,11 @@ A list or tuple of parser classes, that determines the default set of parsers us
|
|||
|
||||
Default:
|
||||
|
||||
(
|
||||
[
|
||||
'rest_framework.parsers.JSONParser',
|
||||
'rest_framework.parsers.FormParser',
|
||||
'rest_framework.parsers.MultiPartParser'
|
||||
)
|
||||
]
|
||||
|
||||
#### DEFAULT_AUTHENTICATION_CLASSES
|
||||
|
||||
|
@ -67,10 +70,10 @@ A list or tuple of authentication classes, that determines the default set of au
|
|||
|
||||
Default:
|
||||
|
||||
(
|
||||
[
|
||||
'rest_framework.authentication.SessionAuthentication',
|
||||
'rest_framework.authentication.BasicAuthentication'
|
||||
)
|
||||
]
|
||||
|
||||
#### DEFAULT_PERMISSION_CLASSES
|
||||
|
||||
|
@ -78,15 +81,15 @@ A list or tuple of permission classes, that determines the default set of permis
|
|||
|
||||
Default:
|
||||
|
||||
(
|
||||
[
|
||||
'rest_framework.permissions.AllowAny',
|
||||
)
|
||||
]
|
||||
|
||||
#### 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
|
||||
|
||||
|
@ -94,38 +97,31 @@ A content negotiation class, that determines how a renderer is selected for the
|
|||
|
||||
Default: `'rest_framework.negotiation.DefaultContentNegotiation'`
|
||||
|
||||
#### DEFAULT_SCHEMA_CLASS
|
||||
|
||||
A view inspector class that will be used for schema generation.
|
||||
|
||||
Default: `'rest_framework.schemas.openapi.AutoSchema'`
|
||||
|
||||
---
|
||||
|
||||
## Generic view settings
|
||||
|
||||
*The following settings control the behavior of the generic class-based views.*
|
||||
|
||||
#### DEFAULT_PAGINATION_SERIALIZER_CLASS
|
||||
|
||||
---
|
||||
|
||||
**This setting has been removed.**
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
#### 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.
|
||||
|
||||
#### PAGINATE_BY
|
||||
#### 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.
|
||||
|
||||
**This setting has been removed.**
|
||||
|
||||
See the pagination documentation for further guidance on [setting the pagination style](pagination.md#modifying-the-pagination-style).
|
||||
|
||||
---
|
||||
Default: `None`
|
||||
|
||||
#### PAGE_SIZE
|
||||
|
||||
|
@ -133,26 +129,6 @@ The default page size to use for pagination. If set to `None`, pagination is di
|
|||
|
||||
Default: `None`
|
||||
|
||||
#### PAGINATE_BY_PARAM
|
||||
|
||||
---
|
||||
|
||||
**This setting has been removed.**
|
||||
|
||||
See the pagination documentation for further guidance on [setting the pagination style](pagination.md#modifying-the-pagination-style).
|
||||
|
||||
---
|
||||
|
||||
#### MAX_PAGINATE_BY
|
||||
|
||||
---
|
||||
|
||||
**This setting is pending deprecation.**
|
||||
|
||||
See the pagination documentation for further guidance on [setting the pagination style](pagination.md#modifying-the-pagination-style).
|
||||
|
||||
---
|
||||
|
||||
### SEARCH_PARAM
|
||||
|
||||
The name of a query parameter, which can be used to specify the search term used by `SearchFilter`.
|
||||
|
@ -196,6 +172,8 @@ Default: `'version'`
|
|||
#### 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`
|
||||
|
||||
|
@ -227,10 +205,10 @@ The format of any of these renderer classes may be used when constructing a test
|
|||
|
||||
Default:
|
||||
|
||||
(
|
||||
[
|
||||
'rest_framework.renderers.MultiPartRenderer',
|
||||
'rest_framework.renderers.JSONRenderer'
|
||||
)
|
||||
]
|
||||
|
||||
---
|
||||
|
||||
|
@ -390,10 +368,15 @@ A string representing the function that should be used when generating view name
|
|||
|
||||
This should be a function with the following signature:
|
||||
|
||||
view_name(cls, suffix=None)
|
||||
view_name(self)
|
||||
|
||||
* `cls`: The view class. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `cls.__name__`.
|
||||
* `suffix`: The optional suffix used when differentiating individual views in a viewset.
|
||||
* `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'`
|
||||
|
||||
|
@ -405,11 +388,15 @@ This setting can be changed to support markup styles other than the default mark
|
|||
|
||||
This should be a function with the following signature:
|
||||
|
||||
view_description(cls, html=False)
|
||||
view_description(self, html=False)
|
||||
|
||||
* `cls`: The view class. Typically the description function would inspect the docstring of the class when generating a description, by accessing `cls.__doc__`
|
||||
* `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
|
||||
|
@ -465,6 +452,6 @@ An integer of 0 or more, that may be used to specify the number of application p
|
|||
Default: `None`
|
||||
|
||||
[cite]: https://www.python.org/dev/peps/pep-0020/
|
||||
[rfc4627]: http://www.ietf.org/rfc/rfc4627.txt
|
||||
[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/time.html#time.strftime
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: status.py
|
||||
---
|
||||
source:
|
||||
- status.py
|
||||
---
|
||||
|
||||
# Status Codes
|
||||
|
||||
|
@ -51,6 +54,8 @@ This class of status code indicates that the client's request was successfully r
|
|||
HTTP_205_RESET_CONTENT
|
||||
HTTP_206_PARTIAL_CONTENT
|
||||
HTTP_207_MULTI_STATUS
|
||||
HTTP_208_ALREADY_REPORTED
|
||||
HTTP_226_IM_USED
|
||||
|
||||
## Redirection - 3xx
|
||||
|
||||
|
@ -64,6 +69,7 @@ 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
|
||||
|
||||
|
@ -90,6 +96,7 @@ The 4xx class of status code is intended for cases in which the client seems to
|
|||
HTTP_422_UNPROCESSABLE_ENTITY
|
||||
HTTP_423_LOCKED
|
||||
HTTP_424_FAILED_DEPENDENCY
|
||||
HTTP_426_UPGRADE_REQUIRED
|
||||
HTTP_428_PRECONDITION_REQUIRED
|
||||
HTTP_429_TOO_MANY_REQUESTS
|
||||
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
|
||||
|
@ -105,7 +112,11 @@ 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
|
||||
|
@ -118,6 +129,6 @@ The following helper functions are available for identifying the category of the
|
|||
is_client_error() # 4xx
|
||||
is_server_error() # 5xx
|
||||
|
||||
[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
|
||||
[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
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: test.py
|
||||
---
|
||||
source:
|
||||
- test.py
|
||||
---
|
||||
|
||||
# Testing
|
||||
|
||||
|
@ -119,7 +122,7 @@ 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 the that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. For example:
|
||||
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
|
||||
|
||||
|
@ -201,13 +204,15 @@ 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
|
||||
## 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.
|
||||
|
||||
|
@ -237,12 +242,12 @@ For example...
|
|||
client = RequestsClient()
|
||||
|
||||
# Obtain a CSRF token.
|
||||
response = client.get('/homepage/')
|
||||
response = client.get('http://testserver/homepage/')
|
||||
assert response.status_code == 200
|
||||
csrftoken = response.cookies['csrftoken']
|
||||
|
||||
# Interact with the API.
|
||||
response = client.post('/organisations/', json={
|
||||
response = client.post('http://testserver/organisations/', json={
|
||||
'name': 'MegaCorp',
|
||||
'status': 'active'
|
||||
}, headers={'X-CSRFToken': csrftoken})
|
||||
|
@ -292,7 +297,7 @@ similar way as with `RequestsClient`.
|
|||
|
||||
---
|
||||
|
||||
# Test cases
|
||||
# API Test cases
|
||||
|
||||
REST framework includes the following test case classes, that mirror the existing Django test case classes, but use `APIClient` instead of Django's default `Client`.
|
||||
|
||||
|
@ -324,6 +329,32 @@ You can use any of REST framework's test case classes as you would for the regul
|
|||
|
||||
---
|
||||
|
||||
# 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
|
||||
|
@ -371,14 +402,14 @@ For example, to add support for using `format='html'` in test requests, you migh
|
|||
|
||||
REST_FRAMEWORK = {
|
||||
...
|
||||
'TEST_REQUEST_RENDERER_CLASSES': (
|
||||
'TEST_REQUEST_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.MultiPartRenderer',
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.TemplateHTMLRenderer'
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
[cite]: http://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper
|
||||
[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
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: throttling.py
|
||||
---
|
||||
source:
|
||||
- throttling.py
|
||||
---
|
||||
|
||||
# Throttling
|
||||
|
||||
|
@ -28,10 +31,10 @@ 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'
|
||||
|
@ -48,7 +51,7 @@ using the `APIView` class-based views.
|
|||
from rest_framework.views import APIView
|
||||
|
||||
class ExampleView(APIView):
|
||||
throttle_classes = (UserRateThrottle,)
|
||||
throttle_classes = [UserRateThrottle]
|
||||
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
|
@ -72,9 +75,9 @@ The `X-Forwarded-For` HTTP header and `REMOTE_ADDR` WSGI variable are used to un
|
|||
|
||||
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](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client.
|
||||
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][identifing-clients].
|
||||
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
|
||||
|
||||
|
@ -82,8 +85,10 @@ The throttle classes provided by REST framework use Django's cache backend. You
|
|||
|
||||
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 = get_cache('alternate')
|
||||
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.
|
||||
|
||||
|
@ -124,10 +129,10 @@ 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'
|
||||
|
@ -159,9 +164,9 @@ For example, given the following views...
|
|||
...and the following settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_THROTTLE_CLASSES': (
|
||||
'DEFAULT_THROTTLE_CLASSES': [
|
||||
'rest_framework.throttling.ScopedRateThrottle',
|
||||
),
|
||||
],
|
||||
'DEFAULT_THROTTLE_RATES': {
|
||||
'contacts': '1000/day',
|
||||
'uploads': '20/day'
|
||||
|
@ -190,8 +195,8 @@ The following is an example of a rate throttle, that will randomly throttle 1 in
|
|||
def allow_request(self, request, view):
|
||||
return random.randint(1, 10) != 1
|
||||
|
||||
[cite]: https://dev.twitter.com/docs/error-codes-responses
|
||||
[cite]: https://developer.twitter.com/en/docs/basics/rate-limiting
|
||||
[permissions]: permissions.md
|
||||
[identifing-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster
|
||||
[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
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: validators.py
|
||||
---
|
||||
source:
|
||||
- validators.py
|
||||
---
|
||||
|
||||
# Validators
|
||||
|
||||
|
@ -94,13 +97,13 @@ The validator should be applied to *serializer classes*, like so:
|
|||
validators = [
|
||||
UniqueTogetherValidator(
|
||||
queryset=ToDoItem.objects.all(),
|
||||
fields=('list', 'position')
|
||||
fields=['list', 'position']
|
||||
)
|
||||
]
|
||||
|
||||
---
|
||||
|
||||
**Note**: The `UniqueTogetherValidation` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
|
||||
**Note**: The `UniqueTogetherValidator` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
|
||||
|
||||
---
|
||||
|
||||
|
@ -149,8 +152,6 @@ If you want the date field to be visible, but not editable by the user, then set
|
|||
|
||||
published = serializers.DateTimeField(read_only=True, default=timezone.now)
|
||||
|
||||
The field will not be writable to the user, but the default value will still be passed through to the `validated_data`.
|
||||
|
||||
#### 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.
|
||||
|
@ -159,7 +160,7 @@ If you want the date field to be entirely hidden from the user, then use `Hidden
|
|||
|
||||
---
|
||||
|
||||
**Note**: The `UniqueFor<Range>Validation` classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
|
||||
**Note**: The `UniqueFor<Range>Validator` classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
|
||||
|
||||
---
|
||||
|
||||
|
@ -189,7 +190,6 @@ A default class that can be used to *only set a default argument during create o
|
|||
It takes a single argument, which is the default value or callable that should be used during create operations.
|
||||
|
||||
created_at = serializers.DateTimeField(
|
||||
read_only=True,
|
||||
default=serializers.CreateOnlyDefault(timezone.now)
|
||||
)
|
||||
|
||||
|
@ -218,12 +218,12 @@ in the `.validate()` method, or else in the view.
|
|||
For example:
|
||||
|
||||
class BillingRecordSerializer(serializers.ModelSerializer):
|
||||
def validate(self, data):
|
||||
def validate(self, attrs):
|
||||
# Apply custom validation either here, or in the view.
|
||||
|
||||
class Meta:
|
||||
fields = ('client', 'date', 'amount')
|
||||
extra_kwargs = {'client': {'required': 'False'}}
|
||||
fields = ['client', 'date', 'amount']
|
||||
extra_kwargs = {'client': {'required': False}}
|
||||
validators = [] # Remove a default "unique together" constraint.
|
||||
|
||||
## Updating nested serializers
|
||||
|
@ -276,7 +276,7 @@ A validator may be any callable that raises a `serializers.ValidationError` on f
|
|||
|
||||
You can specify custom field-level validation by adding `.validate_<field_name>` methods
|
||||
to your `Serializer` subclass. This is documented in the
|
||||
[Serializer docs](http://www.django-rest-framework.org/api-guide/serializers/#field-level-validation)
|
||||
[Serializer docs](https://www.django-rest-framework.org/api-guide/serializers/#field-level-validation)
|
||||
|
||||
## Class-based
|
||||
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: versioning.py
|
||||
---
|
||||
source:
|
||||
- versioning.py
|
||||
---
|
||||
|
||||
# Versioning
|
||||
|
||||
|
@ -37,7 +40,7 @@ The `reverse` function included by REST framework ties in with the versioning sc
|
|||
|
||||
The above function will apply any URL transformations appropriate to the request version. For example:
|
||||
|
||||
* If `NamespacedVersioning` 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 `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
|
||||
|
@ -129,12 +132,12 @@ This scheme requires the client to specify the version as part of the URL path.
|
|||
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 = [
|
||||
url(
|
||||
re_path(
|
||||
r'^(?P<version>(v1|v2))/bookings/$',
|
||||
bookings_list,
|
||||
name='bookings-list'
|
||||
),
|
||||
url(
|
||||
re_path(
|
||||
r'^(?P<version>(v1|v2))/bookings/(?P<pk>[0-9]+)/$',
|
||||
bookings_detail,
|
||||
name='bookings-detail'
|
||||
|
@ -155,14 +158,14 @@ In the following example we're giving a set of views two different possible URL
|
|||
|
||||
# bookings/urls.py
|
||||
urlpatterns = [
|
||||
url(r'^$', bookings_list, name='bookings-list'),
|
||||
url(r'^(?P<pk>[0-9]+)/$', bookings_detail, name='bookings-detail')
|
||||
re_path(r'^$', bookings_list, name='bookings-list'),
|
||||
re_path(r'^(?P<pk>[0-9]+)/$', bookings_detail, name='bookings-detail')
|
||||
]
|
||||
|
||||
# urls.py
|
||||
urlpatterns = [
|
||||
url(r'^v1/bookings/', include('bookings.urls', namespace='v1')),
|
||||
url(r'^v2/bookings/', include('bookings.urls', namespace='v2'))
|
||||
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.
|
||||
|
@ -183,7 +186,7 @@ By default this implementation expects the hostname to match this simple regular
|
|||
|
||||
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 services which you to [access localhost with a custom subdomain][lvh] which you may find helpful in this case.
|
||||
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.
|
||||
|
||||
|
@ -211,10 +214,10 @@ The following example uses a custom `X-API-Version` header to determine the requ
|
|||
|
||||
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]: http://www.slideshare.net/evolve_conference/201308-fielding-evolve/31
|
||||
[roy-fielding-on-versioning]: http://www.infoq.com/articles/roy-fielding-on-versioning
|
||||
[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]: http://tools.ietf.org/html/rfc4627#section-6
|
||||
[vendor-media-type]: http://en.wikipedia.org/wiki/Internet_media_type#Vendor_tree
|
||||
[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,5 +1,8 @@
|
|||
source: decorators.py
|
||||
views.py
|
||||
---
|
||||
source:
|
||||
- decorators.py
|
||||
- views.py
|
||||
---
|
||||
|
||||
# Class-based Views
|
||||
|
||||
|
@ -32,8 +35,8 @@ For example:
|
|||
* 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):
|
||||
"""
|
||||
|
@ -42,6 +45,13 @@ 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.
|
||||
|
@ -207,8 +217,10 @@ You may pass `None` in order to exclude the view from schema generation.
|
|||
return Response({"message": "Will not appear in schema!"})
|
||||
|
||||
|
||||
[cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
|
||||
[cite]: https://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
|
||||
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: viewsets.py
|
||||
---
|
||||
source:
|
||||
- viewsets.py
|
||||
---
|
||||
|
||||
# ViewSets
|
||||
|
||||
|
@ -51,7 +54,7 @@ Typically we wouldn't do this, but would instead register the viewset with a rou
|
|||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register(r'users', UserViewSet, base_name='user')
|
||||
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:
|
||||
|
@ -70,9 +73,10 @@ There are two main advantages of using a `ViewSet` class over using a `View` cla
|
|||
|
||||
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.
|
||||
|
||||
## Marking extra actions for routing
|
||||
|
||||
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:
|
||||
## 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):
|
||||
"""
|
||||
|
@ -101,16 +105,38 @@ The default routers included with REST framework will provide routes for a stand
|
|||
def destroy(self, request, pk=None):
|
||||
pass
|
||||
|
||||
If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@detail_route` or `@list_route` decorators.
|
||||
## Introspecting ViewSet actions
|
||||
|
||||
The `@detail_route` decorator contains `pk` in its URL pattern and is intended for methods which require a single instance. The `@list_route` decorator is intended for methods which operate on a list of objects.
|
||||
During dispatch, the following attributes are available on the `ViewSet`.
|
||||
|
||||
For example:
|
||||
* `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 behaviour 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 = [IsAdmin]
|
||||
return [permission() for permission in permission_classes]
|
||||
|
||||
## 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
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.decorators import detail_route, list_route
|
||||
from rest_framework import status, viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from myapp.serializers import UserSerializer, PasswordSerializer
|
||||
|
||||
|
@ -121,7 +147,7 @@ For example:
|
|||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
|
||||
@detail_route(methods=['post'])
|
||||
@action(detail=True, methods=['post'])
|
||||
def set_password(self, request, pk=None):
|
||||
user = self.get_object()
|
||||
serializer = PasswordSerializer(data=request.data)
|
||||
|
@ -133,9 +159,9 @@ For example:
|
|||
return Response(serializer.errors,
|
||||
status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
@list_route()
|
||||
@action(detail=False)
|
||||
def recent_users(self, request):
|
||||
recent_users = User.objects.all().order('-last_login')
|
||||
recent_users = User.objects.all().order_by('-last_login')
|
||||
|
||||
page = self.paginate_queryset(recent_users)
|
||||
if page is not None:
|
||||
|
@ -145,20 +171,38 @@ For example:
|
|||
serializer = self.get_serializer(recent_users, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
The decorators can additionally take extra arguments that will be set for the routed view only. For example...
|
||||
The decorator can additionally take extra arguments that will be set for the routed view only. For example:
|
||||
|
||||
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])
|
||||
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])
|
||||
def set_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
These decorators will route `GET` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example:
|
||||
The `action` decorator will route `GET` requests by default, but may also accept other HTTP methods by setting the `methods` argument. For example:
|
||||
|
||||
@detail_route(methods=['post', 'delete'])
|
||||
@action(detail=True, methods=['post', 'delete'])
|
||||
def unset_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/$`
|
||||
|
||||
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.
|
||||
|
@ -172,7 +216,14 @@ Using the example from the previous section:
|
|||
'http://localhost:8000/api/users/1/set_password'
|
||||
```
|
||||
|
||||
The `url_name` argument should match the same argument to the `@list_route` and `@detail_route` decorators. Additionally, this can be used to reverse the default `list` and `detail` routes.
|
||||
Alternatively, you can use the `url_name` attribute set by the `@action` decorator.
|
||||
|
||||
```python
|
||||
>>> 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`.
|
||||
|
||||
---
|
||||
|
||||
|
@ -221,7 +272,7 @@ Note that you can use any of the standard attributes or method overrides provide
|
|||
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 base_name of your Model automatically, and so you will have to specify the `base_name` kwarg as part of your [router registration][routers].
|
||||
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.
|
||||
|
||||
|
@ -266,5 +317,5 @@ To create a base viewset class that provides `create`, `list` and `retrieve` ope
|
|||
|
||||
By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple viewsets across your API.
|
||||
|
||||
[cite]: http://guides.rubyonrails.org/routing.html
|
||||
[cite]: https://guides.rubyonrails.org/routing.html
|
||||
[routers]: routers.md
|
||||
|
|
|
@ -32,7 +32,7 @@ Significant new functionality continues to be planned for the 3.1 and 3.2 releas
|
|||
|
||||
#### REST framework: Under the hood.
|
||||
|
||||
This talk from the [Django: Under the Hood](http://www.djangounderthehood.com/) event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.
|
||||
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>
|
||||
|
||||
|
@ -258,13 +258,13 @@ If you try to use a writable nested serializer without writing a custom `create(
|
|||
>>> class ProfileSerializer(serializers.ModelSerializer):
|
||||
>>> class Meta:
|
||||
>>> model = Profile
|
||||
>>> fields = ('address', 'phone')
|
||||
>>> fields = ['address', 'phone']
|
||||
>>>
|
||||
>>> class UserSerializer(serializers.ModelSerializer):
|
||||
>>> profile = ProfileSerializer()
|
||||
>>> class Meta:
|
||||
>>> model = User
|
||||
>>> fields = ('username', 'email', 'profile')
|
||||
>>> fields = ['username', 'email', 'profile']
|
||||
>>>
|
||||
>>> data = {
|
||||
>>> 'username': 'lizzy',
|
||||
|
@ -283,7 +283,7 @@ To use writable nested serialization you'll want to declare a nested field on th
|
|||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ('username', 'email', 'profile')
|
||||
fields = ['username', 'email', 'profile']
|
||||
|
||||
def create(self, validated_data):
|
||||
profile_data = validated_data.pop('profile')
|
||||
|
@ -327,7 +327,7 @@ The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDe
|
|||
class MySerializer(serializer.ModelSerializer):
|
||||
class Meta:
|
||||
model = MyModel
|
||||
fields = ('id', 'email', 'notes', 'is_admin')
|
||||
fields = ['id', 'email', 'notes', 'is_admin']
|
||||
extra_kwargs = {
|
||||
'is_admin': {'write_only': True}
|
||||
}
|
||||
|
@ -339,7 +339,7 @@ Alternatively, specify the field explicitly on the serializer class:
|
|||
|
||||
class Meta:
|
||||
model = MyModel
|
||||
fields = ('id', 'email', 'notes', 'is_admin')
|
||||
fields = ['id', 'email', 'notes', 'is_admin']
|
||||
|
||||
The `read_only_fields` option remains as a convenient shortcut for the more common case.
|
||||
|
||||
|
@ -350,7 +350,7 @@ The `view_name` and `lookup_field` options have been moved to `PendingDeprecatio
|
|||
class MySerializer(serializer.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = MyModel
|
||||
fields = ('url', 'email', 'notes', 'is_admin')
|
||||
fields = ['url', 'email', 'notes', 'is_admin']
|
||||
extra_kwargs = {
|
||||
'url': {'lookup_field': 'uuid'}
|
||||
}
|
||||
|
@ -365,7 +365,7 @@ Alternatively, specify the field explicitly on the serializer class:
|
|||
|
||||
class Meta:
|
||||
model = MyModel
|
||||
fields = ('url', 'email', 'notes', 'is_admin')
|
||||
fields = ['url', 'email', 'notes', 'is_admin']
|
||||
|
||||
#### Fields for model methods and properties.
|
||||
|
||||
|
@ -384,12 +384,12 @@ 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')
|
||||
fields = ['to_email', 'message', 'expiry_date']
|
||||
|
||||
These fields will be mapped to `serializers.ReadOnlyField()` instances.
|
||||
|
||||
>>> serializer = InvitationSerializer()
|
||||
>>> print repr(serializer)
|
||||
>>> print(repr(serializer))
|
||||
InvitationSerializer():
|
||||
to_email = EmailField(max_length=75)
|
||||
message = CharField(max_length=1000)
|
||||
|
@ -523,7 +523,7 @@ The following class is an example of a generic serializer that can handle coerci
|
|||
def to_representation(self, obj):
|
||||
for attribute_name in dir(obj):
|
||||
attribute = getattr(obj, attribute_name)
|
||||
if attribute_name('_'):
|
||||
if attribute_name.startswith('_'):
|
||||
# Ignore private attributes.
|
||||
pass
|
||||
elif hasattr(attribute, '__call__'):
|
||||
|
@ -738,7 +738,7 @@ The `UniqueTogetherValidator` should be applied to a serializer, and takes a `qu
|
|||
class Meta:
|
||||
validators = [UniqueTogetherValidator(
|
||||
queryset=RaceResult.objects.all(),
|
||||
fields=('category', 'position')
|
||||
fields=['category', 'position']
|
||||
)]
|
||||
|
||||
#### The `UniqueForDateValidator` classes.
|
||||
|
@ -959,7 +959,7 @@ The 3.2 release is planned to introduce an alternative admin-style interface to
|
|||
|
||||
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]: http://kickstarter.com/projects/tomchristie/django-rest-framework-3
|
||||
[sponsors]: http://www.django-rest-framework.org/topics/kickstarter-announcement/#sponsors
|
||||
[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
|
|
@ -30,7 +30,7 @@ Note that as a result of this work a number of settings keys and generic view at
|
|||
|
||||
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](http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api) on the subject.
|
||||
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.
|
||||
|
||||
|
@ -61,7 +61,7 @@ For example, when using `NamespaceVersioning`, and the following hyperlinked ser
|
|||
class AccountsSerializer(serializer.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = Accounts
|
||||
fields = ('account_name', 'users')
|
||||
fields = ['account_name', 'users']
|
||||
|
||||
The output representation would match the version used on the incoming request. Like so:
|
||||
|
||||
|
@ -114,7 +114,7 @@ Note that the structure of the error responses is still the same. We still have
|
|||
|
||||
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/projects/p/django-rest-framework/).
|
||||
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:
|
||||
|
||||
|
@ -123,7 +123,7 @@ If you only wish to support a subset of the supported languages, use Django's st
|
|||
('en', _('English')),
|
||||
]
|
||||
|
||||
For more details, see the [internationalization documentation](internationalization.md).
|
||||
For more details, see the [internationalization documentation][internationalization].
|
||||
|
||||
Many thanks to [Craig Blaszczyk](https://github.com/jakul) for helping push this through.
|
||||
|
||||
|
@ -155,14 +155,14 @@ We've now moved a number of packages out of the core of REST framework, and into
|
|||
|
||||
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/evonove/django-oauth-toolkit) has now been promoted as our recommended option for integrating OAuth support.
|
||||
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](http://jpadilla.github.io/django-rest-framework-oauth/)
|
||||
* XML - [djangorestframework-xml](http://jpadilla.github.io/django-rest-framework-xml)
|
||||
* YAML - [djangorestframework-yaml](http://jpadilla.github.io/django-rest-framework-yaml)
|
||||
* JSONP - [djangorestframework-jsonp](http://jpadilla.github.io/django-rest-framework-jsonp)
|
||||
* 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:
|
||||
|
||||
|
@ -205,5 +205,5 @@ This will either be made as a single 3.2 release, or split across two separate r
|
|||
[custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling
|
||||
[pagination]: ../api-guide/pagination.md
|
||||
[versioning]: ../api-guide/versioning.md
|
||||
[internationalization]: internationalization.md
|
||||
[internationalization]: ../topics/internationalization.md
|
||||
[customizing-field-mappings]: ../api-guide/serializers.md#customizing-field-mappings
|
147
docs/community/3.10-announcement.md
Normal file
|
@ -0,0 +1,147 @@
|
|||
<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/master/docs/coreapi/index.md
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: community/funding.md
|
|
@ -10,7 +10,7 @@ We've also fixed a huge number of issues, and made numerous cleanups and improve
|
|||
|
||||
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](http://www.django-rest-framework.org/topics/kickstarter-announcement/#sponsors) and finding out who's hiring.
|
||||
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
|
||||
|
|
@ -37,8 +37,8 @@ This brings our supported versions into line with Django's [currently supported
|
|||
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](browser-enhancements.md#url-based-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](browser-enhancements.md#http-header-based-method-overriding).
|
||||
* 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.
|
||||
|
||||
|
@ -52,7 +52,9 @@ The following pagination view attributes and settings have been moved into attri
|
|||
|
||||
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]: html-and-forms.md
|
||||
[forms-api]: ../topics/html-and-forms.md
|
||||
[ajax-form]: https://github.com/encode/ajax-form
|
||||
[jsonfield]: ../../api-guide/fields#jsonfield
|
||||
[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
|
|
@ -36,13 +36,13 @@ 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="http://jobs.rover.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
||||
<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://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](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), and [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf).*
|
||||
*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).*
|
||||
|
||||
---
|
||||
|
||||
|
@ -178,17 +178,17 @@ 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]: http://www.coreapi.org/
|
||||
[core-api]: https://www.coreapi.org/
|
||||
[command-line-client]: api-clients#command-line-client
|
||||
[client-library]: api-clients#python-client-library
|
||||
[core-json]: http://www.coreapi.org/specification/encoding/#core-json-encoding
|
||||
[core-json]: https://www.coreapi.org/specification/encoding/#core-json-encoding
|
||||
[swagger]: https://openapis.org/specification
|
||||
[hyperschema]: http://json-schema.org/latest/json-schema-hypermedia.html
|
||||
[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]: api-clients.md
|
||||
[tut-7]: ../tutorial/7-schemas-and-client-libraries/
|
||||
[schema-generation]: ../api-guide/schemas/
|
||||
[api-clients]: ../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
|
||||
[metadata]: ../api-guide/metadata/#custom-metadata-classes
|
||||
[gh3751]: https://github.com/encode/django-rest-framework/issues/3751
|
|
@ -32,14 +32,14 @@ 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="http://jobs.rover.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
||||
<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://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="http://www.machinalis.com/#services" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</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](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), and [Machinalis](http://www.machinalis.com/#services).*
|
||||
*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).*
|
||||
|
||||
---
|
||||
|
||||
|
@ -256,8 +256,8 @@ in version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandato
|
|||
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
||||
[uploads]: http://core-api.github.io/python-client/api-guide/utils/#file
|
||||
[downloads]: http://core-api.github.io/python-client/api-guide/codecs/#downloadcodec
|
||||
[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
|
|
@ -39,16 +39,16 @@ 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="http://jobs.rover.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
||||
<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://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://hello.machinalis.co.uk/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</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](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://hello.machinalis.co.uk/), [Rollbar](https://rollbar.com), and [MicroPyramid](https://micropyramid.com/django-rest-framework-development-services/).*
|
||||
*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/).*
|
||||
|
||||
---
|
||||
|
||||
|
@ -60,7 +60,7 @@ REST framework's new API documentation supports a number of features:
|
|||
* Support for various authentication schemes.
|
||||
* Code snippets for the Python, JavaScript, and Command Line clients.
|
||||
|
||||
The `coreapi` library is required as a dependancy for the API docs. Make sure
|
||||
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.
|
||||
|
||||
|
@ -194,6 +194,6 @@ on realtime support, for the 3.7 release.
|
|||
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
||||
[api-docs]: documenting-your-api.md
|
||||
[js-docs]: api-clients.md#javascript-client-library
|
||||
[py-docs]: api-clients.md#python-client-library
|
||||
[api-docs]: ../topics/documenting-your-api.md
|
||||
[js-docs]: ../topics/api-clients.md#javascript-client-library
|
||||
[py-docs]: ../topics/api-clients.md#python-client-library
|
|
@ -33,15 +33,15 @@ If you use REST framework commercially and would like to see this work continue,
|
|||
**[signing up for a paid plan][funding]**.
|
||||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="http://jobs.rover.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
||||
<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://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://hello.machinalis.co.uk/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</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](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://hello.machinalis.co.uk/), and [Rollbar](https://rollbar.com).*
|
||||
*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).*
|
||||
|
||||
---
|
||||
|
97
docs/community/3.8-announcement.md
Normal file
|
@ -0,0 +1,97 @@
|
|||
<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/
|
212
docs/community/3.9-announcement.md
Normal file
|
@ -0,0 +1,212 @@
|
|||
<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
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
renderer_classes=[JSONOpenAPIRenderer]
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
url('^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 | IsAdmin)]
|
||||
```
|
||||
|
||||
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
|
|
@ -48,9 +48,15 @@ Getting involved in triaging incoming issues is a good way to start contributing
|
|||
|
||||
# Development
|
||||
|
||||
To start developing on Django REST framework, clone the repo:
|
||||
To start developing on Django REST framework, first create a Fork from the
|
||||
[Django REST Framework repo][repo] on GitHub.
|
||||
|
||||
git clone git@github.com:encode/django-rest-framework.git
|
||||
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/Spoon-Knife
|
||||
|
||||
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.
|
||||
|
||||
|
@ -59,7 +65,7 @@ Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recom
|
|||
To run the tests, clone the repository, and then:
|
||||
|
||||
# Setup the virtual environment
|
||||
virtualenv env
|
||||
python3 -m venv env
|
||||
source env/bin/activate
|
||||
pip install django
|
||||
pip install -r requirements.txt
|
||||
|
@ -115,7 +121,7 @@ It's also useful to remember that if you have an outstanding pull request then p
|
|||
|
||||
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 with both Python 2 and Python 3, and that they run properly on all supported versions of Django.
|
||||
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 Travis build status in the GitHub interface and make sure the tests are running as you'd expect.
|
||||
|
||||
|
@ -198,15 +204,17 @@ If you want to draw attention to a note or warning, use a pair of enclosing line
|
|||
---
|
||||
|
||||
|
||||
[cite]: http://www.w3.org/People/Berners-Lee/FAQ.html
|
||||
[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]: http://stackexchange.com/filters/66475/rest-framework
|
||||
[so-filter]: https://stackexchange.com/filters/66475/rest-framework
|
||||
[issues]: https://github.com/encode/django-rest-framework/issues?state=open
|
||||
[pep-8]: http://www.python.org/dev/peps/pep-0008/
|
||||
[pep-8]: https://www.python.org/dev/peps/pep-0008/
|
||||
[travis-status]: ../img/travis-status.png
|
||||
[pull-requests]: https://help.github.com/articles/using-pull-requests
|
||||
[tox]: https://tox.readthedocs.io/en/latest/
|
||||
[markdown]: http://daringfireball.net/projects/markdown/basics
|
||||
[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/
|
|
@ -123,9 +123,10 @@ REST framework continues to be open-source and permissively licensed, but we fir
|
|||
|
||||
## What funding has enabled so far
|
||||
|
||||
* The [3.4](http://www.django-rest-framework.org/topics/3.4-announcement/) and [3.5](http://www.django-rest-framework.org/topics/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](http://www.django-rest-framework.org/topics/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
|
||||
* The recent [3.7 release](http://www.django-rest-framework.org/topics/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
|
||||
* 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.
|
||||
|
@ -340,7 +341,7 @@ For further enquires please contact <a href=mailto:funding@django-rest-framework
|
|||
|
||||
## Accountability
|
||||
|
||||
In an effort to keep the project as transparent as possible, we are releasing [monthly progress reports](http://www.encode.io/reports/october-2017) and regularly include financial reports and cost breakdowns.
|
||||
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">
|
|
@ -9,9 +9,9 @@ Looking for a new Django REST Framework related role? On this site we provide a
|
|||
* [https://www.python.org/jobs/][python-org-jobs]
|
||||
* [https://djangogigs.com][django-gigs-com]
|
||||
* [https://djangojobs.net/jobs/][django-jobs-net]
|
||||
* [http://djangojobbers.com][django-jobbers-com]
|
||||
* [https://findwork.dev/django-rest-framework-jobs][findwork-dev]
|
||||
* [https://www.indeed.com/q-Django-jobs.html][indeed-com]
|
||||
* [http://stackoverflow.com/jobs/developer-jobs-using-django][stackoverflow-com]
|
||||
* [https://stackoverflow.com/jobs/developer-jobs-using-django][stackoverflow-com]
|
||||
* [https://www.upwork.com/o/jobs/browse/skill/django-framework/][upwork-com]
|
||||
* [https://www.technojobs.co.uk/django-jobs][technobjobs-co-uk]
|
||||
* [https://remoteok.io/remote-django-jobs][remoteok-io]
|
||||
|
@ -27,9 +27,9 @@ Wonder how else you can help? One of the best ways you can help Django REST Fram
|
|||
[python-org-jobs]: https://www.python.org/jobs/
|
||||
[django-gigs-com]: https://djangogigs.com
|
||||
[django-jobs-net]: https://djangojobs.net/jobs/
|
||||
[django-jobbers-com]: http://djangojobbers.com
|
||||
[findwork-dev]: https://findwork.dev/django-rest-framework-jobs
|
||||
[indeed-com]: https://www.indeed.com/q-Django-jobs.html
|
||||
[stackoverflow-com]: http://stackoverflow.com/jobs/developer-jobs-using-django
|
||||
[stackoverflow-com]: https://stackoverflow.com/jobs/developer-jobs-using-django
|
||||
[upwork-com]: https://www.upwork.com/o/jobs/browse/skill/django-framework/
|
||||
[technobjobs-co-uk]: https://www.technojobs.co.uk/django-jobs
|
||||
[remoteok-io]: https://remoteok.io/remote-django-jobs
|
|
@ -47,8 +47,8 @@ Our platinum sponsors have each made a hugely substantial contribution to the fu
|
|||
</ul>
|
||||
|
||||
<ul class="sponsor platinum">
|
||||
<li><a href="https://www.divio.ch/" rel="nofollow" style="background-image:url(../../img/sponsors/1-divio.png);">Divio</a></li>
|
||||
<li><a href="http://company.onlulu.com/en/" rel="nofollow" style="background-image:url(../../img/sponsors/1-lulu.png);">Lulu</a></li>
|
||||
<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>
|
||||
|
@ -72,27 +72,27 @@ Our gold sponsors include companies large and small. Many thanks for their signi
|
|||
<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="http://www.sirono.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-sirono.png);">Sirono</a></li>
|
||||
<li><a href="http://www.vinta.com.br/" rel="nofollow" style="background-image:url(../../img/sponsors/2-vinta.png);">Vinta Software Studio</a></li>
|
||||
<li><a href="http://www.rapasso.nl/index.php/en" rel="nofollow" style="background-image:url(../../img/sponsors/2-rapasso.png);">Rapasso</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="http://hipolabs.com" rel="nofollow" style="background-image:url(../../img/sponsors/2-hipo.png);">Hipo</a></li>
|
||||
<li><a href="http://www.byte.nl" rel="nofollow" style="background-image:url(../../img/sponsors/2-byte.png);">Byte</a></li>
|
||||
<li><a href="http://lightningkite.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-lightning_kite.png);">Lightning Kite</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 href="http://pulsecode.ca" rel="nofollow" style="background-image:url(../../img/sponsors/2-pulsecode.png);">Pulsecode Inc.</a></li>
|
||||
<li><a href="http://singinghorsestudio.com" rel="nofollow" style="background-image:url(../../img/sponsors/2-singing-horse.png);">Singing Horse Studio Ltd.</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="http://www.securitycompass.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-security_compass.png);">Security Compass</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 href="http://www.nexthub.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-nexthub.png);">NextHub</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 href="http://wusawork.org" rel="nofollow" style="background-image:url(../../img/sponsors/2-wusawork.png);">WusaWork</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>
|
||||
|
||||
|
@ -105,38 +105,38 @@ Our gold sponsors include companies large and small. Many thanks for their signi
|
|||
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="http://www.imtapps.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-imt_computer_services.png);">IMT Computer Services</a></li>
|
||||
<li><a href="http://wildfish.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-wildfish.png);">Wildfish</a></li>
|
||||
<li><a href="http://www.thermondo.de/" rel="nofollow" style="background-image:url(../../img/sponsors/3-thermondo-gmbh.png);">Thermondo GmbH</a></li>
|
||||
<li><a href="http://providenz.fr/" rel="nofollow" style="background-image:url(../../img/sponsors/3-providenz.png);">Providenz</a></li>
|
||||
<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="http://www.triggeredmessaging.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-triggered_messaging.png);">Triggered Messaging</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="http://www.tivix.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-tivix.png);">Tivix</a></li>
|
||||
<li><a href="http://www.safaribooksonline.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-safari.png);">Safari</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="http://crosswordtracker.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-crosswordtracker.png);">Crossword Tracker</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="http://pathwright.com" rel="nofollow" style="background-image:url(../../img/sponsors/3-pathwright.png);">Pathwright</a></li>
|
||||
<li><a href="http://fluxility.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-fluxility.png);">Fluxility</a></li>
|
||||
<li><a href="http://teonite.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-teonite.png);">Teonite</a></li>
|
||||
<li><a href="http://trackmaven.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-trackmaven.png);">TrackMaven</a></li>
|
||||
<li><a href="http://www.phurba.net/" rel="nofollow" style="background-image:url(../../img/sponsors/3-phurba.png);">Phurba</a></li>
|
||||
<li><a href="http://www.nephila.co.uk/" rel="nofollow" style="background-image:url(../../img/sponsors/3-nephila.png);">Nephila</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="http://www.eyesopen.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-openeye.png);">OpenEye Scientific Software</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="http://cantemo.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-cantemo.gif);">Cantemo</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>
|
||||
|
@ -144,7 +144,7 @@ The serious financial contribution that our silver sponsors have made is very mu
|
|||
|
||||
<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="http://chrisheisel.com/">Chris Heisel</a>, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.
|
||||
**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.
|
||||
|
||||
---
|
||||
|
|
@ -4,7 +4,7 @@ We have recently been [awarded a Mozilla grant](https://blog.mozilla.org/blog/20
|
|||
|
||||
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](http://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.
|
||||
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:
|
||||
|
||||
|
@ -31,10 +31,10 @@ The next goal is to build on the realtime support offered by Django Channels, ad
|
|||
## 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](http://www.dabapps.com)
|
||||
& 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](http://www.encode.io), which will
|
||||
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).
|
|
@ -39,7 +39,7 @@ The following template should be used for the description of the issue, and serv
|
|||
|
||||
This issue is for determining the maintenance team for the *** period.
|
||||
|
||||
Please see the [Project management](http://www.django-rest-framework.org/topics/project-management/) section of our documentation for more details.
|
||||
Please see the [Project management](https://www.django-rest-framework.org/topics/project-management/) section of our documentation for more details.
|
||||
|
||||
---
|
||||
|
||||
|
@ -59,7 +59,7 @@ The following template should be used for the description of the issue, and serv
|
|||
|
||||
If you wish to be considered for this or a future date, please comment against this or subsequent issues.
|
||||
|
||||
To modify this process for future maintenance cycles make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation.
|
||||
To modify this process for future maintenance cycles make a pull request to the [project management](https://www.django-rest-framework.org/topics/project-management/) documentation.
|
||||
|
||||
#### Responsibilities of team members
|
||||
|
||||
|
@ -99,13 +99,18 @@ The following template should be used for the description of the issue, and serv
|
|||
|
||||
During development cycle:
|
||||
|
||||
- [ ] Upload the new content to be translated to [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).
|
||||
- [ ] 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 the translations from [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).
|
||||
- [ ] 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).
|
||||
- [ ] Confirm with @tomchristie that release is finalized and ready to go.
|
||||
- [ ] Ensure that release date is included in pull request.
|
||||
|
@ -117,7 +122,7 @@ The following template should be used for the description of the issue, and serv
|
|||
- [ ] 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](http://www.django-rest-framework.org/topics/project-management/) documentation.
|
||||
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.
|
||||
|
||||
|
@ -147,7 +152,7 @@ When any user visible strings are changed, they should be uploaded to Transifex
|
|||
|
||||
# 1. Update the source django.po file, which is the US English version.
|
||||
cd rest_framework
|
||||
django-admin.py makemessages -l en_US
|
||||
django-admin makemessages -l en_US
|
||||
# 2. Push the source django.po file to Transifex.
|
||||
cd ..
|
||||
tx push -s
|
||||
|
@ -168,7 +173,7 @@ When a translator has finished translating their work needs to be downloaded fro
|
|||
tx pull -a --minimum-perc 10
|
||||
cd rest_framework
|
||||
# 4. Compile the binary .mo files for all supported languages.
|
||||
django-admin.py compilemessages
|
||||
django-admin compilemessages
|
||||
|
||||
---
|
||||
|
||||
|
@ -190,17 +195,15 @@ If `@tomchristie` ceases to participate in the project then `@j4mie` has respons
|
|||
|
||||
The following issues still need to be addressed:
|
||||
|
||||
* [Consider moving the repo into a proper GitHub organization][github-org].
|
||||
* Ensure `@jamie` has back-up access to the `django-rest-framework.org` domain setup and admin.
|
||||
* Document ownership of the [live example][sandbox] API.
|
||||
* Document ownership of the [mailing list][mailing-list] and IRC channel.
|
||||
* Document ownership and management of the security mailing list.
|
||||
|
||||
[bus-factor]: http://en.wikipedia.org/wiki/Bus_factor
|
||||
[bus-factor]: https://en.wikipedia.org/wiki/Bus_factor
|
||||
[un-triaged]: https://github.com/encode/django-rest-framework/issues?q=is%3Aopen+no%3Alabel
|
||||
[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/
|
||||
[transifex-client]: https://pypi.python.org/pypi/transifex-client
|
||||
[transifex-client]: https://pypi.org/project/transifex-client/
|
||||
[translation-memory]: http://docs.transifex.com/guides/tm#let-tm-automatically-populate-translations
|
||||
[github-org]: https://github.com/encode/django-rest-framework/issues/2162
|
||||
[sandbox]: http://restframework.herokuapp.com/
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
[mailing-list]: https://groups.google.com/forum/#!forum/django-rest-framework
|
|
@ -18,9 +18,9 @@ REST framework releases follow a formal deprecation policy, which is in line wit
|
|||
|
||||
The timeline for deprecation of a feature present in version 1.0 would work as follows:
|
||||
|
||||
* Version 1.1 would remain **fully backwards compatible** with 1.0, but would raise `PendingDeprecationWarning` warnings if you use the feature that are due to be deprecated. These warnings are **silent by default**, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using `python -Wd manage.py test`, you'll be warned of any API changes you need to make.
|
||||
* Version 1.1 would remain **fully backwards compatible** with 1.0, but would raise `RemovedInDRF13Warning` warnings, subclassing `PendingDeprecationWarning`, if you use the feature that are due to be deprecated. These warnings are **silent by default**, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using `python -Wd manage.py test`, you'll be warned of any API changes you need to make.
|
||||
|
||||
* Version 1.2 would escalate these warnings to `DeprecationWarning`, which is loud by default.
|
||||
* Version 1.2 would escalate these warnings to subclass `DeprecationWarning`, which is loud by default.
|
||||
|
||||
* Version 1.3 would remove the deprecated bits of API entirely.
|
||||
|
||||
|
@ -32,19 +32,323 @@ To upgrade Django REST framework to the latest version, use pip:
|
|||
|
||||
pip install -U djangorestframework
|
||||
|
||||
You can determine your currently installed version using `pip freeze`:
|
||||
You can determine your currently installed version using `pip show`:
|
||||
|
||||
pip freeze | grep djangorestframework
|
||||
pip show djangorestframework
|
||||
|
||||
---
|
||||
|
||||
## 3.10.x series
|
||||
|
||||
### 3.10.3
|
||||
|
||||
* Include API version in OpenAPI schema generation, defaulting to empty string.
|
||||
* Add pagination properties to OpenAPI response schemas.
|
||||
* Add missing "description" property to OpenAPI response schemas.
|
||||
* Only include "required" for non-empty cases in OpenAPI schemas.
|
||||
* Fix response schemas for "DELETE" case in OpenAPI schemas.
|
||||
* Use an array type for list view response schemas.
|
||||
* Use consistent `lowerInitialCamelCase` style in OpenAPI operation IDs.
|
||||
* Fix `minLength`/`maxLength`/`minItems`/`maxItems` properties in OpenAPI schemas.
|
||||
* Only call `FileField.url` once in serialization, for improved performance.
|
||||
* Fix an edge case where throttling calcualtions could error after a configuration change.
|
||||
|
||||
* TODO
|
||||
|
||||
### 3.10.2
|
||||
|
||||
**Date**: 29th July 2019
|
||||
|
||||
* Various `OpenAPI` schema fixes.
|
||||
* Ability to specify urlconf in include_docs_urls.
|
||||
|
||||
### 3.10.1
|
||||
|
||||
**Date**: 17th July 2019
|
||||
|
||||
* Don't include autocomplete fields on TokenAuth admin, since it forces constraints on custom user models & admin.
|
||||
* Require `uritemplate` for OpenAPI schema generation, but not `coreapi`.
|
||||
|
||||
### 3.10.0
|
||||
|
||||
**Date**: [15th July 2019][3.10.0-milestone]
|
||||
|
||||
* Switch to OpenAPI schema generation.
|
||||
* Drop Python 2 support.
|
||||
* Add `generateschema --generator_class` CLI option
|
||||
* Updated PyYaml dependency for OpenAPI schema generation to `pyyaml>=5.1` [#6680][gh6680]
|
||||
* Resolve DeprecationWarning with markdown. [#6317][gh6317]
|
||||
* Use `user.get_username` in templates, in preference to `user.username`.
|
||||
* Fix for cursor pagination issue that could occur after object deletions.
|
||||
* Fix for nullable fields with `source="*"`
|
||||
* Always apply all throttle classes during throttling checks.
|
||||
* Updates to jQuery and Markdown dependencies.
|
||||
* Don't strict disallow redundant `SerializerMethodField` field name arguments.
|
||||
* Don't render extra actions in browable API if not authenticated.
|
||||
* Strip null characters from search parameters.
|
||||
|
||||
## 3.9.x series
|
||||
|
||||
### 3.9.4
|
||||
|
||||
**Date**: 10th May 2019
|
||||
|
||||
This is a maintenance release that fixes an error handling bug under Python 2.
|
||||
|
||||
### 3.9.3
|
||||
|
||||
**Date**: 29th April 2019
|
||||
|
||||
This is the last Django REST Framework release that will support Python 2.
|
||||
Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
|
||||
|
||||
* Adjusted the compat check for django-guardian to allow the last guardian
|
||||
version (v1.4.9) compatible with Python 2. [#6613][gh6613]
|
||||
|
||||
### 3.9.2
|
||||
|
||||
**Date**: [3rd March 2019][3.9.2-milestone]
|
||||
|
||||
* Routers: invalidate `_urls` cache on `register()` [#6407][gh6407]
|
||||
* Deferred schema renderer creation to avoid requiring pyyaml. [#6416][gh6416]
|
||||
* Added 'request_forms' block to base.html [#6340][gh6340]
|
||||
* Fixed SchemaView to reset renderer on exception. [#6429][gh6429]
|
||||
* Update Django Guardian dependency. [#6430][gh6430]
|
||||
* Ensured support for Django 2.2 [#6422][gh6422] & [#6455][gh6455]
|
||||
* Made templates compatible with session-based CSRF. [#6207][gh6207]
|
||||
* Adjusted field `validators` to accept non-list iterables. [#6282][gh6282]
|
||||
* Added SearchFilter.get_search_fields() hook. [#6279][gh6279]
|
||||
* Fix DeprecationWarning when accessing collections.abc classes via collections [#6268][gh6268]
|
||||
* Allowed Q objects in limit_choices_to introspection. [#6472][gh6472]
|
||||
* Added lazy evaluation to composed permissions. [#6463][gh6463]
|
||||
* Add negation ~ operator to permissions composition [#6361][gh6361]
|
||||
* Avoided calling distinct on annotated fields in SearchFilter. [#6240][gh6240]
|
||||
* Introduced `RemovedInDRF…Warning` classes to simplify deprecations. [#6480][gh6480]
|
||||
|
||||
### 3.9.1
|
||||
|
||||
**Date**: [16th January 2019][3.9.1-milestone]
|
||||
|
||||
* Resolve XSS issue in browsable API. [#6330][gh6330]
|
||||
* Upgrade Bootstrap to 3.4.0 to resolve XSS issue.
|
||||
* Resolve issues with composable permissions. [#6299][gh6299]
|
||||
* Respect `limit_choices_to` on foreign keys. [#6371][gh6371]
|
||||
|
||||
### 3.9.0
|
||||
|
||||
**Date**: [18th October 2018][3.9.0-milestone]
|
||||
|
||||
* Improvements to ViewSet extra actions [#5605][gh5605]
|
||||
* Fix `action` support for ViewSet suffixes [#6081][gh6081]
|
||||
* Allow `action` docs sections [#6060][gh6060]
|
||||
* Deprecate the `Router.register` `base_name` argument in favor of `basename`. [#5990][gh5990]
|
||||
* Deprecate the `Router.get_default_base_name` method in favor of `Router.get_default_basename`. [#5990][gh5990]
|
||||
* Change `CharField` to disallow null bytes. [#6073][gh6073]
|
||||
To revert to the old behavior, subclass `CharField` and remove `ProhibitNullCharactersValidator` from the validators.
|
||||
```python
|
||||
class NullableCharField(serializers.CharField):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.validators = [v for v in self.validators if not isinstance(v, ProhibitNullCharactersValidator)]
|
||||
```
|
||||
* Add `OpenAPIRenderer` and `generate_schema` management command. [#6229][gh6229]
|
||||
* Add OpenAPIRenderer by default, and add schema docs. [#6233][gh6233]
|
||||
* Allow permissions to be composed [#5753][gh5753]
|
||||
* Allow nullable BooleanField in Django 2.1 [#6183][gh6183]
|
||||
* Add testing of Python 3.7 support [#6141][gh6141]
|
||||
* Test using Django 2.1 final release. [#6109][gh6109]
|
||||
* Added djangorestframework-datatables to third-party packages [#5931][gh5931]
|
||||
* Change ISO 8601 date format to exclude year/month [#5936][gh5936]
|
||||
* Update all pypi.python.org URLs to pypi.org [#5942][gh5942]
|
||||
* Ensure that html forms (multipart form data) respect optional fields [#5927][gh5927]
|
||||
* Allow hashing of ErrorDetail. [#5932][gh5932]
|
||||
* Correct schema parsing for JSONField [#5878][gh5878]
|
||||
* Render descriptions (from help_text) using safe [#5869][gh5869]
|
||||
* Removed input value from deault_error_message [#5881][gh5881]
|
||||
* Added min_value/max_value support in DurationField [#5643][gh5643]
|
||||
* Fixed instance being overwritten in pk-only optimization try/except block [#5747][gh5747]
|
||||
* Fixed AttributeError from items filter when value is None [#5981][gh5981]
|
||||
* Fixed Javascript `e.indexOf` is not a function error [#5982][gh5982]
|
||||
* Fix schemas for extra actions [#5992][gh5992]
|
||||
* Improved get_error_detail to use error_dict/error_list [#5785][gh5785]
|
||||
* Imprvied URLs in Admin renderer [#5988][gh5988]
|
||||
* Add "Community" section to docs, minor cleanup [#5993][gh5993]
|
||||
* Moved guardian imports out of compat [#6054][gh6054]
|
||||
* Deprecate the `DjangoObjectPermissionsFilter` class, moved to the `djangorestframework-guardian` package. [#6075][gh6075]
|
||||
* Drop Django 1.10 support [#5657][gh5657]
|
||||
* Only catch TypeError/ValueError for object lookups [#6028][gh6028]
|
||||
* Handle models without .objects manager in ModelSerializer. [#6111][gh6111]
|
||||
* Improve ModelSerializer.create() error message. [#6112][gh6112]
|
||||
* Fix CSRF cookie check failure when using session auth with django 1.11.6+ [#6113][gh6113]
|
||||
* Updated JWT docs. [#6138][gh6138]
|
||||
* Fix autoescape not getting passed to urlize_quoted_links filter [#6191][gh6191]
|
||||
|
||||
|
||||
## 3.8.x series
|
||||
|
||||
### 3.8.2
|
||||
|
||||
**Date**: [6th April 2018][3.8.2-milestone]
|
||||
|
||||
* Fix `read_only` + `default` `unique_together` validation. [#5922][gh5922]
|
||||
* authtoken.views import coreapi from rest_framework.compat, not directly. [#5921][gh5921]
|
||||
* Docs: Add missing argument 'detail' to Route [#5920][gh5920]
|
||||
|
||||
|
||||
### 3.8.1
|
||||
|
||||
**Date**: [4th April 2018][3.8.1-milestone]
|
||||
|
||||
* Use old `url_name` behavior in route decorators [#5915][gh5915]
|
||||
|
||||
For `list_route` and `detail_route` maintain the old behavior of `url_name`,
|
||||
basing it on the `url_path` instead of the function name.
|
||||
|
||||
|
||||
### 3.8.0
|
||||
|
||||
**Date**: [3rd April 2018][3.8.0-milestone]
|
||||
|
||||
|
||||
* **Breaking Change**: Alter `read_only` plus `default` behaviour. [#5886][gh5886]
|
||||
|
||||
`read_only` fields will now **always** be excluded from writable fields.
|
||||
|
||||
Previously `read_only` fields with a `default` value would use the `default` for create and update operations.
|
||||
|
||||
In order to maintain the old behaviour you may need to pass the value of `read_only` fields when calling `save()` in
|
||||
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.
|
||||
|
||||
* Correct allow_null behaviour when required=False [#5888][gh5888]
|
||||
|
||||
Without an explicit `default`, `allow_null` implies a default of `null` for outgoing serialization. Previously such
|
||||
fields were being skipped when read-only or otherwise not required.
|
||||
|
||||
**Possible backwards compatibility break** if you were relying on such fields being excluded from the outgoing
|
||||
representation. In order to restore the old behaviour you can override `data` to exclude the field when `None`.
|
||||
|
||||
For example:
|
||||
|
||||
@property
|
||||
def data(self):
|
||||
"""
|
||||
Drop `maybe_none` field if None.
|
||||
"""
|
||||
data = super().data
|
||||
if 'maybe_none' in data and data['maybe_none'] is None:
|
||||
del data['maybe_none']
|
||||
return data
|
||||
|
||||
* Refactor dynamic route generation and improve viewset action introspectibility. [#5705][gh5705]
|
||||
|
||||
`ViewSet`s have been provided with new attributes and methods that allow
|
||||
it to introspect its set of actions and the details of the current action.
|
||||
|
||||
* Merged `list_route` and `detail_route` into a single `action` decorator.
|
||||
* Get all extra actions on a `ViewSet` with `.get_extra_actions()`.
|
||||
* Extra actions now set the `url_name` and `url_path` on the decorated method.
|
||||
* `url_name` is now based on the function name, instead of the `url_path`,
|
||||
as the path is not always suitable (e.g., capturing arguments in the path).
|
||||
* Enable action url reversing through `.reverse_action()` method (added in 3.7.4)
|
||||
* Example reverse call: `self.reverse_action(self.custom_action.url_name)`
|
||||
* Add `detail` initkwarg to indicate if the current action is operating on a
|
||||
collection or a single instance.
|
||||
|
||||
Additional changes:
|
||||
|
||||
* Deprecated `list_route` & `detail_route` in favor of `action` decorator with `detail` boolean.
|
||||
* Deprecated dynamic list/detail route variants in favor of `DynamicRoute` with `detail` boolean.
|
||||
* Refactored the router's dynamic route generation.
|
||||
* `list_route` and `detail_route` maintain the old behavior of `url_name`,
|
||||
basing it on the `url_path` instead of the function name.
|
||||
|
||||
* Fix formatting of the 3.7.4 release note [#5704][gh5704]
|
||||
* Docs: Update DRF Writable Nested Serializers references [#5711][gh5711]
|
||||
* Docs: Fixed typo in auth URLs example. [#5713][gh5713]
|
||||
* Improve composite field child errors [#5655][gh5655]
|
||||
* Disable HTML inputs for dict/list fields [#5702][gh5702]
|
||||
* Fix typo in HostNameVersioning doc [#5709][gh5709]
|
||||
* Use rsplit to get module and classname for imports [#5712][gh5712]
|
||||
* Formalize URLPatternsTestCase [#5703][gh5703]
|
||||
* Add exception translation test [#5700][gh5700]
|
||||
* Test staticfiles [#5701][gh5701]
|
||||
* Add drf-yasg to documentation and schema 3rd party packages [#5720][gh5720]
|
||||
* Remove unused `compat._resolve_model()` [#5733][gh5733]
|
||||
* Drop compat workaround for unsupported Python 3.2 [#5734][gh5734]
|
||||
* Prefer `iter(dict)` over `iter(dict.keys())` [#5736][gh5736]
|
||||
* Pass `python_requires` argument to setuptools [#5739][gh5739]
|
||||
* Remove unused links from docs [#5735][gh5735]
|
||||
* Prefer https protocol for links in docs when available [#5729][gh5729]
|
||||
* Add HStoreField, postgres fields tests [#5654][gh5654]
|
||||
* Always fully qualify ValidationError in docs [#5751][gh5751]
|
||||
* Remove unreachable code from ManualSchema [#5766][gh5766]
|
||||
* Allowed customising API documentation code samples [#5752][gh5752]
|
||||
* Updated docs to use `pip show` [#5757][gh5757]
|
||||
* Load 'static' instead of 'staticfiles' in templates [#5773][gh5773]
|
||||
* Fixed a typo in `fields` docs [#5783][gh5783]
|
||||
* Refer to "NamespaceVersioning" instead of "NamespacedVersioning" in the documentation [#5754][gh5754]
|
||||
* ErrorDetail: add `__eq__`/`__ne__` and `__repr__` [#5787][gh5787]
|
||||
* Replace `background-attachment: fixed` in docs [#5777][gh5777]
|
||||
* Make 404 & 403 responses consistent with `exceptions.APIException` output [#5763][gh5763]
|
||||
* Small fix to API documentation: schemas [#5796][gh5796]
|
||||
* Fix schema generation for PrimaryKeyRelatedField [#5764][gh5764]
|
||||
* Represent serializer DictField as an Object in schema [#5765][gh5765]
|
||||
* Added docs example reimplementing ObtainAuthToken [#5802][gh5802]
|
||||
* Add schema to the ObtainAuthToken view [#5676][gh5676]
|
||||
* Fix request formdata handling [#5800][gh5800]
|
||||
* Fix authtoken views imports [#5818][gh5818]
|
||||
* Update pytest, isort [#5815][gh5815] [#5817][gh5817] [#5894][gh5894]
|
||||
* Fixed active timezone handling for non ISO8601 datetimes. [#5833][gh5833]
|
||||
* Made TemplateHTMLRenderer render IntegerField inputs when value is `0`. [#5834][gh5834]
|
||||
* Corrected endpoint in tutorial instructions [#5835][gh5835]
|
||||
* Add Django Rest Framework Role Filters to Third party packages [#5809][gh5809]
|
||||
* Use single copy of static assets. Update jQuery [#5823][gh5823]
|
||||
* Changes ternary conditionals to be PEP308 compliant [#5827][gh5827]
|
||||
* Added links to 'A Todo List API with React' and 'Blog API' tutorials [#5837][gh5837]
|
||||
* Fix comment typo in ModelSerializer [#5844][gh5844]
|
||||
* Add admin to installed apps to avoid test failures. [#5870][gh5870]
|
||||
* Fixed schema for UUIDField in SimpleMetadata. [#5872][gh5872]
|
||||
* Corrected docs on router include with namespaces. [#5843][gh5843]
|
||||
* Test using model objects for dotted source default [#5880][gh5880]
|
||||
* Allow traversing nullable related fields [#5849][gh5849]
|
||||
* Added: Tutorial: Django REST with React (Django 2.0) [#5891][gh5891]
|
||||
* Add `LimitOffsetPagination.get_count` to allow method override [#5846][gh5846]
|
||||
* Don't show hidden fields in metadata [#5854][gh5854]
|
||||
* Enable OrderingFilter to handle an empty tuple (or list) for the 'ordering' field. [#5899][gh5899]
|
||||
* Added generic 500 and 400 JSON error handlers. [#5904][gh5904]
|
||||
|
||||
|
||||
## 3.7.x series
|
||||
|
||||
### 3.7.7
|
||||
|
||||
**Date**: [21st December 2017][3.7.7-milestone]
|
||||
|
||||
* Fix typo to include *.mo locale files to packaging. [#5697][gh5697], [#5695][gh5695]
|
||||
|
||||
### 3.7.6
|
||||
|
||||
**Date**: [21st December 2017][3.7.6-milestone]
|
||||
|
||||
* Add missing *.ico icon files to packaging.
|
||||
|
||||
### 3.7.5
|
||||
|
||||
**Date**: [21st December 2017][3.7.5-milestone]
|
||||
|
||||
* Add missing *.woff2 font files to packaging. [#5692][gh5692]
|
||||
* Add missing *.mo locale files to packaging. [#5695][gh5695], [#5696][gh5696]
|
||||
|
||||
### 3.7.4
|
||||
|
||||
**Date**: UNRELEASED
|
||||
**Date**: [20th December 2017][3.7.4-milestone]
|
||||
|
||||
* Extract method for `manual_fields` processing [#5633][gh5633]
|
||||
* Schema: Extract method for `manual_fields` processing [#5633][gh5633]
|
||||
|
||||
Allows for easier customisation of `manual_fields` processing, for example
|
||||
to provide per-method manual fields. `AutoSchema` adds `get_manual_fields`,
|
||||
|
@ -55,9 +359,51 @@ You can determine your currently installed version using `pip freeze`:
|
|||
Note: `AutoSchema.__init__` now ensures `manual_fields` is a list.
|
||||
Previously may have been stored internally as `None`.
|
||||
|
||||
|
||||
[gh5633]: https://github.com/encode/django-rest-framework/issues/5633
|
||||
|
||||
* Remove ulrparse compatibility shim; use six instead [#5579][gh5579]
|
||||
* Drop compat wrapper for `TimeDelta.total_seconds()` [#5577][gh5577]
|
||||
* Clean up all whitespace throughout project [#5578][gh5578]
|
||||
* Compat cleanup [#5581][gh5581]
|
||||
* Add pygments CSS block in browsable API views [#5584][gh5584] [#5587][gh5587]
|
||||
* Remove `set_rollback()` from compat [#5591][gh5591]
|
||||
* Fix request body/POST access [#5590][gh5590]
|
||||
* Rename test to reference correct issue [#5610][gh5610]
|
||||
* Documentation Fixes [#5611][gh5611] [#5612][gh5612]
|
||||
* Remove references to unsupported Django versions in docs and code [#5602][gh5602]
|
||||
* Test Serializer exclude for declared fields [#5599][gh5599]
|
||||
* Fixed schema generation for filter backends [#5613][gh5613]
|
||||
* Minor cleanup for ModelSerializer tests [#5598][gh5598]
|
||||
* Reimplement request attribute access w/ `__getattr__` [#5617][gh5617]
|
||||
* Fixed SchemaJSRenderer renders invalid Javascript [#5607][gh5607]
|
||||
* Make Django 2.0 support official/explicit [#5619][gh5619]
|
||||
* Perform type check on passed request argument [#5618][gh5618]
|
||||
* Fix AttributeError hiding on request authenticators [#5600][gh5600]
|
||||
* Update test requirements [#5626][gh5626]
|
||||
* Docs: `Serializer._declared_fields` enable modifying fields on a serializer [#5629][gh5629]
|
||||
* Fix packaging [#5624][gh5624]
|
||||
* Fix readme rendering for PyPI, add readme build to CI [#5625][gh5625]
|
||||
* Update tutorial [#5622][gh5622]
|
||||
* Non-required fields with `allow_null=True` should not imply a default value [#5639][gh5639]
|
||||
* Docs: Add `allow_null` serialization output note [#5641][gh5641]
|
||||
* Update to use the Django 2.0 release in tox.ini [#5645][gh5645]
|
||||
* Fix `Serializer.data` for Browsable API rendering when provided invalid `data` [#5646][gh5646]
|
||||
* Docs: Note AutoSchema limitations on bare APIView [#5649][gh5649]
|
||||
* Add `.basename` and `.reverse_action()` to ViewSet [#5648][gh5648]
|
||||
* Docs: Fix typos in serializers documentation [#5652][gh5652]
|
||||
* Fix `override_settings` compat [#5668][gh5668]
|
||||
* Add DEFAULT_SCHEMA_CLASS setting [#5658][gh5658]
|
||||
* Add docs note re generated BooleanField being `required=False` [#5665][gh5665]
|
||||
* Add 'dist' build [#5656][gh5656]
|
||||
* Fix typo in docstring [#5678][gh5678]
|
||||
* Docs: Add `UNAUTHENTICATED_USER = None` note [#5679][gh5679]
|
||||
* Update OPTIONS example from “Documenting Your API” [#5680][gh5680]
|
||||
* Docs: Add note on object permissions for FBVs [#5681][gh5681]
|
||||
* Docs: Add example to `to_representation` docs [#5682][gh5682]
|
||||
* Add link to Classy DRF in docs [#5683][gh5683]
|
||||
* Document ViewSet.action [#5685][gh5685]
|
||||
* Fix schema docs typo [#5687][gh5687]
|
||||
* Fix URL pattern parsing in schema generation [#5689][gh5689]
|
||||
* Add example using `source=‘*’` to custom field docs. [#5688][gh5688]
|
||||
* Fix format_suffix_patterns behavior with Django 2 path() routes [#5691][gh5691]
|
||||
|
||||
|
||||
### 3.7.3
|
||||
|
@ -118,7 +464,7 @@ You can determine your currently installed version using `pip freeze`:
|
|||
* Deprecated `exclude_from_schema` on `APIView` and `api_view` decorator. Set `schema = None` or `@schema(None)` as appropriate. [#5422][gh5422]
|
||||
* Timezone-aware `DateTimeField`s now respect active or default `timezone` during serialization, instead of always using UTC. [#5435][gh5435]
|
||||
|
||||
Resolves inconsistency whereby instances were serialised with supplied datetime for `create` but UTC for `retrieve`. [#3732][gh3732]
|
||||
Resolves inconsistency whereby instances were serialized with supplied datetime for `create` but UTC for `retrieve`. [#3732][gh3732]
|
||||
|
||||
**Possible backwards compatibility break** if you were relying on datetime strings being UTC. Have client interpret datetimes or [set default or active timezone (docs)][djangodocs-set-timezone] to UTC if needed.
|
||||
|
||||
|
@ -831,13 +1177,6 @@ For older release notes, [please see the version 2.x documentation][old-release-
|
|||
[cite]: http://www.catb.org/~esr/writings/cathedral-bazaar/cathedral-bazaar/ar01s04.html
|
||||
[deprecation-policy]: #deprecation-policy
|
||||
[django-deprecation-policy]: https://docs.djangoproject.com/en/stable/internals/release-process/#internal-release-deprecation-policy
|
||||
[defusedxml-announce]: http://blog.python.org/2013/02/announcing-defusedxml-fixes-for-xml.html
|
||||
[743]: https://github.com/encode/django-rest-framework/pull/743
|
||||
[staticfiles14]: https://docs.djangoproject.com/en/1.4/howto/static-files/#with-a-template-tag
|
||||
[staticfiles13]: https://docs.djangoproject.com/en/1.3/howto/static-files/#with-a-template-tag
|
||||
[2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion
|
||||
[ticket-582]: https://github.com/encode/django-rest-framework/issues/582
|
||||
[rfc-6266]: http://tools.ietf.org/html/rfc6266#section-4.3
|
||||
[old-release-notes]: https://github.com/encode/django-rest-framework/blob/version-2.4.x/docs/topics/release-notes.md
|
||||
[3.6-release]: 3.6-announcement.md
|
||||
|
||||
|
@ -882,7 +1221,17 @@ For older release notes, [please see the version 2.x documentation][old-release-
|
|||
[3.7.1-milestone]: https://github.com/encode/django-rest-framework/milestone/58?closed=1
|
||||
[3.7.2-milestone]: https://github.com/encode/django-rest-framework/milestone/59?closed=1
|
||||
[3.7.3-milestone]: https://github.com/encode/django-rest-framework/milestone/60?closed=1
|
||||
|
||||
[3.7.4-milestone]: https://github.com/encode/django-rest-framework/milestone/62?closed=1
|
||||
[3.7.5-milestone]: https://github.com/encode/django-rest-framework/milestone/63?closed=1
|
||||
[3.7.6-milestone]: https://github.com/encode/django-rest-framework/milestone/64?closed=1
|
||||
[3.7.7-milestone]: https://github.com/encode/django-rest-framework/milestone/65?closed=1
|
||||
[3.8.0-milestone]: https://github.com/encode/django-rest-framework/milestone/61?closed=1
|
||||
[3.8.1-milestone]: https://github.com/encode/django-rest-framework/milestone/67?closed=1
|
||||
[3.8.2-milestone]: https://github.com/encode/django-rest-framework/milestone/68?closed=1
|
||||
[3.9.0-milestone]: https://github.com/encode/django-rest-framework/milestone/66?closed=1
|
||||
[3.9.1-milestone]: https://github.com/encode/django-rest-framework/milestone/70?closed=1
|
||||
[3.9.2-milestone]: https://github.com/encode/django-rest-framework/milestone/71?closed=1
|
||||
[3.10.0-milestone]: https://github.com/encode/django-rest-framework/milestone/69?closed=1
|
||||
|
||||
<!-- 3.0.1 -->
|
||||
[gh2013]: https://github.com/encode/django-rest-framework/issues/2013
|
||||
|
@ -1089,7 +1438,6 @@ For older release notes, [please see the version 2.x documentation][old-release-
|
|||
[gh3249]: https://github.com/encode/django-rest-framework/issues/3249
|
||||
[gh3250]: https://github.com/encode/django-rest-framework/issues/3250
|
||||
[gh3275]: https://github.com/encode/django-rest-framework/issues/3275
|
||||
[gh3288]: https://github.com/encode/django-rest-framework/issues/3288
|
||||
[gh3290]: https://github.com/encode/django-rest-framework/issues/3290
|
||||
[gh3303]: https://github.com/encode/django-rest-framework/issues/3303
|
||||
[gh3313]: https://github.com/encode/django-rest-framework/issues/3313
|
||||
|
@ -1346,7 +1694,6 @@ For older release notes, [please see the version 2.x documentation][old-release-
|
|||
|
||||
<!-- 3.4.4 -->
|
||||
|
||||
[gh2829]: https://github.com/encode/django-rest-framework/issues/2829
|
||||
[gh3329]: https://github.com/encode/django-rest-framework/issues/3329
|
||||
[gh3330]: https://github.com/encode/django-rest-framework/issues/3330
|
||||
[gh3365]: https://github.com/encode/django-rest-framework/issues/3365
|
||||
|
@ -1587,7 +1934,6 @@ For older release notes, [please see the version 2.x documentation][old-release-
|
|||
[gh5457]: https://github.com/encode/django-rest-framework/issues/5457
|
||||
[gh5376]: https://github.com/encode/django-rest-framework/issues/5376
|
||||
[gh5422]: https://github.com/encode/django-rest-framework/issues/5422
|
||||
[gh5408]: https://github.com/encode/django-rest-framework/issues/5408
|
||||
[gh3732]: https://github.com/encode/django-rest-framework/issues/3732
|
||||
[djangodocs-set-timezone]: https://docs.djangoproject.com/en/1.11/topics/i18n/timezones/#default-time-zone-and-current-time-zone
|
||||
[gh5273]: https://github.com/encode/django-rest-framework/issues/5273
|
||||
|
@ -1640,3 +1986,196 @@ For older release notes, [please see the version 2.x documentation][old-release-
|
|||
|
||||
<!-- 3.7.3 -->
|
||||
[gh5567]: https://github.com/encode/django-rest-framework/issues/5567
|
||||
|
||||
<!-- 3.7.4 -->
|
||||
[gh5691]: https://github.com/encode/django-rest-framework/issues/5691
|
||||
[gh5688]: https://github.com/encode/django-rest-framework/issues/5688
|
||||
[gh5689]: https://github.com/encode/django-rest-framework/issues/5689
|
||||
[gh5687]: https://github.com/encode/django-rest-framework/issues/5687
|
||||
[gh5685]: https://github.com/encode/django-rest-framework/issues/5685
|
||||
[gh5683]: https://github.com/encode/django-rest-framework/issues/5683
|
||||
[gh5682]: https://github.com/encode/django-rest-framework/issues/5682
|
||||
[gh5681]: https://github.com/encode/django-rest-framework/issues/5681
|
||||
[gh5680]: https://github.com/encode/django-rest-framework/issues/5680
|
||||
[gh5679]: https://github.com/encode/django-rest-framework/issues/5679
|
||||
[gh5678]: https://github.com/encode/django-rest-framework/issues/5678
|
||||
[gh5656]: https://github.com/encode/django-rest-framework/issues/5656
|
||||
[gh5665]: https://github.com/encode/django-rest-framework/issues/5665
|
||||
[gh5658]: https://github.com/encode/django-rest-framework/issues/5658
|
||||
[gh5668]: https://github.com/encode/django-rest-framework/issues/5668
|
||||
[gh5652]: https://github.com/encode/django-rest-framework/issues/5652
|
||||
[gh5648]: https://github.com/encode/django-rest-framework/issues/5648
|
||||
[gh5649]: https://github.com/encode/django-rest-framework/issues/5649
|
||||
[gh5646]: https://github.com/encode/django-rest-framework/issues/5646
|
||||
[gh5645]: https://github.com/encode/django-rest-framework/issues/5645
|
||||
[gh5641]: https://github.com/encode/django-rest-framework/issues/5641
|
||||
[gh5639]: https://github.com/encode/django-rest-framework/issues/5639
|
||||
[gh5622]: https://github.com/encode/django-rest-framework/issues/5622
|
||||
[gh5625]: https://github.com/encode/django-rest-framework/issues/5625
|
||||
[gh5624]: https://github.com/encode/django-rest-framework/issues/5624
|
||||
[gh5629]: https://github.com/encode/django-rest-framework/issues/5629
|
||||
[gh5626]: https://github.com/encode/django-rest-framework/issues/5626
|
||||
[gh5600]: https://github.com/encode/django-rest-framework/issues/5600
|
||||
[gh5618]: https://github.com/encode/django-rest-framework/issues/5618
|
||||
[gh5619]: https://github.com/encode/django-rest-framework/issues/5619
|
||||
[gh5607]: https://github.com/encode/django-rest-framework/issues/5607
|
||||
[gh5617]: https://github.com/encode/django-rest-framework/issues/5617
|
||||
[gh5598]: https://github.com/encode/django-rest-framework/issues/5598
|
||||
[gh5613]: https://github.com/encode/django-rest-framework/issues/5613
|
||||
[gh5599]: https://github.com/encode/django-rest-framework/issues/5599
|
||||
[gh5602]: https://github.com/encode/django-rest-framework/issues/5602
|
||||
[gh5612]: https://github.com/encode/django-rest-framework/issues/5612
|
||||
[gh5611]: https://github.com/encode/django-rest-framework/issues/5611
|
||||
[gh5610]: https://github.com/encode/django-rest-framework/issues/5610
|
||||
[gh5590]: https://github.com/encode/django-rest-framework/issues/5590
|
||||
[gh5591]: https://github.com/encode/django-rest-framework/issues/5591
|
||||
[gh5587]: https://github.com/encode/django-rest-framework/issues/5587
|
||||
[gh5584]: https://github.com/encode/django-rest-framework/issues/5584
|
||||
[gh5581]: https://github.com/encode/django-rest-framework/issues/5581
|
||||
[gh5578]: https://github.com/encode/django-rest-framework/issues/5578
|
||||
[gh5577]: https://github.com/encode/django-rest-framework/issues/5577
|
||||
[gh5579]: https://github.com/encode/django-rest-framework/issues/5579
|
||||
[gh5633]: https://github.com/encode/django-rest-framework/issues/5633
|
||||
|
||||
<!-- 3.7.5 -->
|
||||
[gh5692]: https://github.com/encode/django-rest-framework/issues/5692
|
||||
[gh5695]: https://github.com/encode/django-rest-framework/issues/5695
|
||||
[gh5696]: https://github.com/encode/django-rest-framework/issues/5696
|
||||
[gh5697]: https://github.com/encode/django-rest-framework/issues/5697
|
||||
|
||||
<!-- 3.8.0 -->
|
||||
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886
|
||||
[gh5888]: https://github.com/encode/django-rest-framework/issues/5888
|
||||
[gh5705]: https://github.com/encode/django-rest-framework/issues/5705
|
||||
[gh5796]: https://github.com/encode/django-rest-framework/issues/5796
|
||||
[gh5763]: https://github.com/encode/django-rest-framework/issues/5763
|
||||
[gh5777]: https://github.com/encode/django-rest-framework/issues/5777
|
||||
[gh5787]: https://github.com/encode/django-rest-framework/issues/5787
|
||||
[gh5754]: https://github.com/encode/django-rest-framework/issues/5754
|
||||
[gh5783]: https://github.com/encode/django-rest-framework/issues/5783
|
||||
[gh5773]: https://github.com/encode/django-rest-framework/issues/5773
|
||||
[gh5757]: https://github.com/encode/django-rest-framework/issues/5757
|
||||
[gh5752]: https://github.com/encode/django-rest-framework/issues/5752
|
||||
[gh5766]: https://github.com/encode/django-rest-framework/issues/5766
|
||||
[gh5751]: https://github.com/encode/django-rest-framework/issues/5751
|
||||
[gh5654]: https://github.com/encode/django-rest-framework/issues/5654
|
||||
[gh5729]: https://github.com/encode/django-rest-framework/issues/5729
|
||||
[gh5735]: https://github.com/encode/django-rest-framework/issues/5735
|
||||
[gh5739]: https://github.com/encode/django-rest-framework/issues/5739
|
||||
[gh5736]: https://github.com/encode/django-rest-framework/issues/5736
|
||||
[gh5734]: https://github.com/encode/django-rest-framework/issues/5734
|
||||
[gh5733]: https://github.com/encode/django-rest-framework/issues/5733
|
||||
[gh5720]: https://github.com/encode/django-rest-framework/issues/5720
|
||||
[gh5701]: https://github.com/encode/django-rest-framework/issues/5701
|
||||
[gh5700]: https://github.com/encode/django-rest-framework/issues/5700
|
||||
[gh5703]: https://github.com/encode/django-rest-framework/issues/5703
|
||||
[gh5712]: https://github.com/encode/django-rest-framework/issues/5712
|
||||
[gh5709]: https://github.com/encode/django-rest-framework/issues/5709
|
||||
[gh5702]: https://github.com/encode/django-rest-framework/issues/5702
|
||||
[gh5655]: https://github.com/encode/django-rest-framework/issues/5655
|
||||
[gh5713]: https://github.com/encode/django-rest-framework/issues/5713
|
||||
[gh5711]: https://github.com/encode/django-rest-framework/issues/5711
|
||||
[gh5704]: https://github.com/encode/django-rest-framework/issues/5704
|
||||
[gh5854]: https://github.com/encode/django-rest-framework/issues/5854
|
||||
[gh5846]: https://github.com/encode/django-rest-framework/issues/5846
|
||||
[gh5891]: https://github.com/encode/django-rest-framework/issues/5891
|
||||
[gh5849]: https://github.com/encode/django-rest-framework/issues/5849
|
||||
[gh5880]: https://github.com/encode/django-rest-framework/issues/5880
|
||||
[gh5843]: https://github.com/encode/django-rest-framework/issues/5843
|
||||
[gh5872]: https://github.com/encode/django-rest-framework/issues/5872
|
||||
[gh5870]: https://github.com/encode/django-rest-framework/issues/5870
|
||||
[gh5844]: https://github.com/encode/django-rest-framework/issues/5844
|
||||
[gh5837]: https://github.com/encode/django-rest-framework/issues/5837
|
||||
[gh5827]: https://github.com/encode/django-rest-framework/issues/5827
|
||||
[gh5823]: https://github.com/encode/django-rest-framework/issues/5823
|
||||
[gh5809]: https://github.com/encode/django-rest-framework/issues/5809
|
||||
[gh5835]: https://github.com/encode/django-rest-framework/issues/5835
|
||||
[gh5834]: https://github.com/encode/django-rest-framework/issues/5834
|
||||
[gh5833]: https://github.com/encode/django-rest-framework/issues/5833
|
||||
[gh5894]: https://github.com/encode/django-rest-framework/issues/5894
|
||||
[gh5817]: https://github.com/encode/django-rest-framework/issues/5817
|
||||
[gh5815]: https://github.com/encode/django-rest-framework/issues/5815
|
||||
[gh5818]: https://github.com/encode/django-rest-framework/issues/5818
|
||||
[gh5800]: https://github.com/encode/django-rest-framework/issues/5800
|
||||
[gh5676]: https://github.com/encode/django-rest-framework/issues/5676
|
||||
[gh5802]: https://github.com/encode/django-rest-framework/issues/5802
|
||||
[gh5765]: https://github.com/encode/django-rest-framework/issues/5765
|
||||
[gh5764]: https://github.com/encode/django-rest-framework/issues/5764
|
||||
[gh5904]: https://github.com/encode/django-rest-framework/issues/5904
|
||||
[gh5899]: https://github.com/encode/django-rest-framework/issues/5899
|
||||
|
||||
<!-- 3.8.1 -->
|
||||
[gh5915]: https://github.com/encode/django-rest-framework/issues/5915
|
||||
|
||||
<!-- 3.8.2 -->
|
||||
[gh5922]: https://github.com/encode/django-rest-framework/issues/5922
|
||||
[gh5921]: https://github.com/encode/django-rest-framework/issues/5921
|
||||
[gh5920]: https://github.com/encode/django-rest-framework/issues/5920
|
||||
|
||||
<!-- 3.9.0 -->
|
||||
[gh6109]: https://github.com/encode/django-rest-framework/issues/6109
|
||||
[gh6141]: https://github.com/encode/django-rest-framework/issues/6141
|
||||
[gh6113]: https://github.com/encode/django-rest-framework/issues/6113
|
||||
[gh6112]: https://github.com/encode/django-rest-framework/issues/6112
|
||||
[gh6111]: https://github.com/encode/django-rest-framework/issues/6111
|
||||
[gh6028]: https://github.com/encode/django-rest-framework/issues/6028
|
||||
[gh5657]: https://github.com/encode/django-rest-framework/issues/5657
|
||||
[gh6054]: https://github.com/encode/django-rest-framework/issues/6054
|
||||
[gh5993]: https://github.com/encode/django-rest-framework/issues/5993
|
||||
[gh5990]: https://github.com/encode/django-rest-framework/issues/5990
|
||||
[gh5988]: https://github.com/encode/django-rest-framework/issues/5988
|
||||
[gh5785]: https://github.com/encode/django-rest-framework/issues/5785
|
||||
[gh5992]: https://github.com/encode/django-rest-framework/issues/5992
|
||||
[gh5605]: https://github.com/encode/django-rest-framework/issues/5605
|
||||
[gh5982]: https://github.com/encode/django-rest-framework/issues/5982
|
||||
[gh5981]: https://github.com/encode/django-rest-framework/issues/5981
|
||||
[gh5747]: https://github.com/encode/django-rest-framework/issues/5747
|
||||
[gh5643]: https://github.com/encode/django-rest-framework/issues/5643
|
||||
[gh5881]: https://github.com/encode/django-rest-framework/issues/5881
|
||||
[gh5869]: https://github.com/encode/django-rest-framework/issues/5869
|
||||
[gh5878]: https://github.com/encode/django-rest-framework/issues/5878
|
||||
[gh5932]: https://github.com/encode/django-rest-framework/issues/5932
|
||||
[gh5927]: https://github.com/encode/django-rest-framework/issues/5927
|
||||
[gh5942]: https://github.com/encode/django-rest-framework/issues/5942
|
||||
[gh5936]: https://github.com/encode/django-rest-framework/issues/5936
|
||||
[gh5931]: https://github.com/encode/django-rest-framework/issues/5931
|
||||
[gh6183]: https://github.com/encode/django-rest-framework/issues/6183
|
||||
[gh6075]: https://github.com/encode/django-rest-framework/issues/6075
|
||||
[gh6138]: https://github.com/encode/django-rest-framework/issues/6138
|
||||
[gh6081]: https://github.com/encode/django-rest-framework/issues/6081
|
||||
[gh6073]: https://github.com/encode/django-rest-framework/issues/6073
|
||||
[gh6191]: https://github.com/encode/django-rest-framework/issues/6191
|
||||
[gh6060]: https://github.com/encode/django-rest-framework/issues/6060
|
||||
[gh6233]: https://github.com/encode/django-rest-framework/issues/6233
|
||||
[gh5753]: https://github.com/encode/django-rest-framework/issues/5753
|
||||
[gh6229]: https://github.com/encode/django-rest-framework/issues/6229
|
||||
|
||||
<!-- 3.9.1 -->
|
||||
[gh6330]: https://github.com/encode/django-rest-framework/issues/6330
|
||||
[gh6299]: https://github.com/encode/django-rest-framework/issues/6299
|
||||
[gh6371]: https://github.com/encode/django-rest-framework/issues/6371
|
||||
|
||||
<!-- 3.9.2 -->
|
||||
[gh6480]: https://github.com/encode/django-rest-framework/issues/6480
|
||||
[gh6240]: https://github.com/encode/django-rest-framework/issues/6240
|
||||
[gh6361]: https://github.com/encode/django-rest-framework/issues/6361
|
||||
[gh6463]: https://github.com/encode/django-rest-framework/issues/6463
|
||||
[gh6472]: https://github.com/encode/django-rest-framework/issues/6472
|
||||
[gh6268]: https://github.com/encode/django-rest-framework/issues/6268
|
||||
[gh6279]: https://github.com/encode/django-rest-framework/issues/6279
|
||||
[gh6282]: https://github.com/encode/django-rest-framework/issues/6282
|
||||
[gh6207]: https://github.com/encode/django-rest-framework/issues/6207
|
||||
[gh6455]: https://github.com/encode/django-rest-framework/issues/6455
|
||||
[gh6422]: https://github.com/encode/django-rest-framework/issues/6422
|
||||
[gh6430]: https://github.com/encode/django-rest-framework/issues/6430
|
||||
[gh6429]: https://github.com/encode/django-rest-framework/issues/6429
|
||||
[gh6340]: https://github.com/encode/django-rest-framework/issues/6340
|
||||
[gh6416]: https://github.com/encode/django-rest-framework/issues/6416
|
||||
[gh6407]: https://github.com/encode/django-rest-framework/issues/6407
|
||||
|
||||
<!-- 3.9.3 -->
|
||||
[gh6613]: https://github.com/encode/django-rest-framework/issues/6613
|
||||
|
||||
<!-- 3.10.0 -->
|
||||
[gh6680]: https://github.com/encode/django-rest-framework/issues/6680
|
||||
[gh6317]: https://github.com/encode/django-rest-framework/issues/6317
|
|
@ -20,7 +20,7 @@ If you have an idea for a new feature please consider how it may be packaged as
|
|||
|
||||
You can use [this cookiecutter template][cookiecutter] for creating reusable Django REST Framework packages quickly. Cookiecutter creates projects from project templates. While optional, this cookiecutter template includes best practices from Django REST framework and other packages, as well as a Travis CI configuration, Tox configuration, and a sane setup.py for easy PyPI registration/distribution.
|
||||
|
||||
Note: Let us know if you have an alternate cookiecuter package so we can also link to it.
|
||||
Note: Let us know if you have an alternate cookiecutter package so we can also link to it.
|
||||
|
||||
#### Running the initial cookiecutter command
|
||||
|
||||
|
@ -183,9 +183,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
|
||||
* [djangorestframework-digestauth][djangorestframework-digestauth] - Provides Digest Access Authentication support.
|
||||
* [django-oauth-toolkit][django-oauth-toolkit] - Provides OAuth 2.0 support.
|
||||
* [doac][doac] - Provides OAuth 2.0 support.
|
||||
* [djangorestframework-jwt][djangorestframework-jwt] - Provides JSON Web Token Authentication support.
|
||||
* [djangorestframework-simplejwt][djangorestframework-simplejwt] - An alternative package that provides JSON Web Token Authentication 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.
|
||||
|
@ -199,6 +197,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [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.
|
||||
|
||||
### Serializers
|
||||
|
||||
|
@ -210,6 +209,10 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [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).
|
||||
|
||||
### Serializer fields
|
||||
|
||||
|
@ -219,7 +222,6 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
|
||||
### Views
|
||||
|
||||
* [djangorestframework-bulk][djangorestframework-bulk] - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.
|
||||
* [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.
|
||||
|
||||
### Routers
|
||||
|
@ -246,11 +248,12 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [djangorestframework-chain][djangorestframework-chain] - Allows arbitrary chaining of both relations and lookup filters.
|
||||
* [django-url-filter][django-url-filter] - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.
|
||||
* [drf-url-filter][drf-url-filter] is a simple Django app to apply filters on drf `ModelViewSet`'s `Queryset` in a clean, simple and configurable way. It also supports validations on incoming query params and their values.
|
||||
* [django-rest-framework-guardian][django-rest-framework-guardian] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF.
|
||||
|
||||
### Misc
|
||||
|
||||
* [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 serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.
|
||||
* [djangorestrelationalhyperlink][djangorestrelationalhyperlink] - A hyperlinked serializer that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.
|
||||
* [django-rest-swagger][django-rest-swagger] - An API documentation generator for Swagger UI.
|
||||
* [django-rest-framework-proxy][django-rest-framework-proxy] - Proxy to redirect incoming request to another API server.
|
||||
* [gaiarestframework][gaiarestframework] - Utils for django-rest-framework
|
||||
|
@ -264,6 +267,10 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [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.
|
||||
|
||||
[cite]: http://www.software-ecosystems.com/Software_Ecosystems/Ecosystems.html
|
||||
[cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework
|
||||
|
@ -271,8 +278,8 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[create-a-repo]: https://help.github.com/articles/create-a-repo/
|
||||
[travis-ci]: https://travis-ci.org
|
||||
[travis-profile]: https://travis-ci.org/profile
|
||||
[pypi-register]: https://pypi.python.org/pypi?%3Aaction=register_form
|
||||
[semver]: http://semver.org/
|
||||
[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/
|
||||
|
@ -284,7 +291,6 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[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
|
||||
[doac]: https://github.com/Rediker-Software/doac
|
||||
[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
|
||||
|
@ -298,10 +304,9 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[djangorestframework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore
|
||||
[drf-compound-fields]: https://github.com/estebistec/drf-compound-fields
|
||||
[django-extra-fields]: https://github.com/Hipo/drf-extra-fields
|
||||
[djangorestframework-bulk]: https://github.com/miki725/django-rest-framework-bulk
|
||||
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
|
||||
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
|
||||
[wq.db.rest]: http://wq.io/docs/about-rest
|
||||
[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
|
||||
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
|
||||
|
@ -337,3 +342,13 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[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-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
|
|
@ -11,6 +11,12 @@ There are a wide range of resources available for learning and using Django REST
|
|||
<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://wsvincent.com/books/">
|
||||
<img src="../../img/books/rad-cover.png"/>
|
||||
</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>
|
||||
|
||||
## Tutorials
|
||||
|
@ -29,6 +35,9 @@ There are a wide range of resources available for learning and using Django REST
|
|||
* [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]
|
||||
* [Django REST Framework Tutorial - Build a Blog API][django-rest-framework-tutorial-build-a-blog]
|
||||
* [Django REST Framework & React Tutorial - Build a Todo List API][django-rest-framework-react-tutorial-build-a-todo-list]
|
||||
* [Tutorial: Django REST with React (Django 2.0)][django-rest-react-valentinog]
|
||||
|
||||
|
||||
## Videos
|
||||
|
@ -75,34 +84,36 @@ There are a wide range of resources available for learning and using Django REST
|
|||
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]: http://code.tutsplus.com/tutorials/beginners-guide-to-the-django-rest-framework--cms-19786
|
||||
[getting-started-with-django-rest-framework-and-angularjs]: http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html
|
||||
[end-to-end-web-app-with-django-rest-framework-angularjs]: http://mourafiq.com/2013/07/01/end-to-end-web-app-with-django-angular-1.html
|
||||
[start-your-api-django-rest-framework-part-1]: https://godjango.com/41-start-your-api-django-rest-framework-part-1/
|
||||
[permissions-authentication-django-rest-framework-part-2]: https://godjango.com/43-permissions-authentication-django-rest-framework-part-2/
|
||||
[viewsets-and-routers-django-rest-framework-part-3]: https://godjango.com/45-viewsets-and-routers-django-rest-framework-part-3/
|
||||
[django-rest-framework-user-endpoint]: http://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/
|
||||
[check-credentials-using-django-rest-framework]: http://richardtier.com/2014/03/06/110/
|
||||
[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]: http://dabapps.com/blog/api-performance-profiling-django-rest-framework/
|
||||
[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/api-development-with-django-and-django-rest-framework/
|
||||
[cdrf.co]:http://www.cdrf.co
|
||||
[medium-django-rest-framework]: https://medium.com/django-rest-framework
|
||||
[django-rest-framework-course]: https://teamtreehouse.com/library/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]: http://machinalis.com/blog/pandas-django-rest-framework-bokeh/
|
||||
[controlling-uncertainty-on-web-apps-and-apis]: http://machinalis.com/blog/controlling-uncertainty-on-web-applications-and-apis/
|
||||
[full-text-search-in-drf]: http://machinalis.com/blog/full-text-search-on-django-rest-framework/
|
||||
[oauth2-authentication-with-drf]: http://machinalis.com/blog/oauth2-authentication/
|
||||
[nested-resources-with-drf]: http://machinalis.com/blog/nested-resources-with-django/
|
||||
[image-fields-with-drf]: http://machinalis.com/blog/image-fields-with-django-rest-framework/
|
||||
[integrating-pandas-drf-and-bokeh]: https://machinalis.com/blog/pandas-django-rest-framework-bokeh/
|
||||
[controlling-uncertainty-on-web-apps-and-apis]: https://machinalis.com/blog/controlling-uncertainty-on-web-applications-and-apis/
|
||||
[full-text-search-in-drf]: https://machinalis.com/blog/full-text-search-on-django-rest-framework/
|
||||
[oauth2-authentication-with-drf]: https://machinalis.com/blog/oauth2-authentication/
|
||||
[nested-resources-with-drf]: https://machinalis.com/blog/nested-resources-with-django/
|
||||
[image-fields-with-drf]: https://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]: http://drf-schema-adapter.readthedocs.io/en/latest/
|
||||
[drf-schema]: https://drf-schema-adapter.readthedocs.io/en/latest/
|
||||
[creating-a-production-ready-api-with-python-and-drf-part1]: https://www.andreagrandi.it/2016/09/28/creating-production-ready-api-python-django-rest-framework-part-1/
|
||||
[creating-a-production-ready-api-with-python-and-drf-part2]: https://www.andreagrandi.it/2016/10/01/creating-a-production-ready-api-with-python-and-django-rest-framework-part-2/
|
||||
[django-rest-framework-tutorial-build-a-blog]: https://wsvincent.com/django-rest-framework-tutorial/
|
||||
[django-rest-framework-react-tutorial-build-a-todo-list]: https://wsvincent.com/django-rest-framework-react-tutorial/
|
||||
[django-rest-api-so-easy]: https://www.youtube.com/watch?v=cqP758k1BaQ
|
||||
[full-fledged-rest-api-with-django-oauth-tookit]: https://www.youtube.com/watch?v=M6Ud3qC2tTk
|
||||
[drf-in-your-pjs]: https://www.youtube.com/watch?v=xMtHsWa72Ww
|
||||
|
@ -112,7 +123,8 @@ Want your Django REST Framework talk/tutorial/article to be added to our website
|
|||
[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]: http://agiliq.com/blog/2014/12/building-a-restful-api-with-django-rest-framework/
|
||||
[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/
|
|
@ -29,9 +29,10 @@ automatically generated schemas. Since we're using viewsets and routers,
|
|||
we can simply use the automatic schema generation.
|
||||
|
||||
You'll need to install the `coreapi` python package in order to include an
|
||||
API schema.
|
||||
API schema, and `pyyaml` to render the schema into the commonly used
|
||||
YAML-based OpenAPI format.
|
||||
|
||||
$ pip install coreapi
|
||||
$ pip install coreapi pyyaml
|
||||
|
||||
We can now include a schema for our API, by including an autogenerated schema
|
||||
view in our URL configuration.
|
||||
|
@ -42,12 +43,12 @@ from rest_framework.schemas import get_schema_view
|
|||
schema_view = get_schema_view(title='Pastebin API')
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^schema/$', schema_view),
|
||||
path('schema/', schema_view),
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
If you visit the API root endpoint in a browser you should now see `corejson`
|
||||
If you visit the `/schema/` endpoint in a browser you should now see `corejson`
|
||||
representation become available as an option.
|
||||
|
||||

|
||||
|
@ -89,7 +90,7 @@ Now check that it is available on the command line...
|
|||
|
||||
Command line client for interacting with CoreAPI services.
|
||||
|
||||
Visit http://www.coreapi.org for more information.
|
||||
Visit https://www.coreapi.org/ for more information.
|
||||
|
||||
Options:
|
||||
--version Display the package version number.
|
||||
|
@ -220,11 +221,11 @@ We've reached the end of our tutorial. If you want to get more involved in the
|
|||
|
||||
**Now go build awesome things.**
|
||||
|
||||
[coreapi]: http://www.coreapi.org
|
||||
[corejson]: http://www.coreapi.org/specification/encoding/#core-json-encoding
|
||||
[coreapi]: https://www.coreapi.org/
|
||||
[corejson]: https://www.coreapi.org/specification/encoding/#core-json-encoding
|
||||
[openapi]: https://openapis.org/
|
||||
[repo]: https://github.com/encode/rest-framework-tutorial
|
||||
[sandbox]: http://restframework.herokuapp.com/
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
[github]: https://github.com/encode/django-rest-framework
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[twitter]: https://twitter.com/_tomchristie
|
171
docs/coreapi/from-documenting-your-api.md
Normal file
|
@ -0,0 +1,171 @@
|
|||
|
||||
## Built-in API documentation
|
||||
|
||||
The built-in API documentation includes:
|
||||
|
||||
* Documentation of API endpoints.
|
||||
* Automatically generated code samples for each of the available API client libraries.
|
||||
* Support for API interaction.
|
||||
|
||||
### Installation
|
||||
|
||||
The `coreapi` library is required as a dependency for the API docs. Make sure
|
||||
to install the latest version. The `Pygments` and `Markdown` libraries
|
||||
are optional but recommended.
|
||||
|
||||
To install the API documentation, you'll need to include it in your project's URLconf:
|
||||
|
||||
from rest_framework.documentation import include_docs_urls
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
url(r'^docs/', include_docs_urls(title='My API title'))
|
||||
]
|
||||
|
||||
This will include two different views:
|
||||
|
||||
* `/docs/` - The documentation page itself.
|
||||
* `/docs/schema.js` - A JavaScript resource that exposes the API schema.
|
||||
|
||||
---
|
||||
|
||||
**Note**: By default `include_docs_urls` configures the underlying `SchemaView` to generate _public_ schemas.
|
||||
This means that views will not be instantiated with a `request` instance. i.e. Inside the view `self.request` will be `None`.
|
||||
|
||||
To be compatible with this behaviour, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
|
||||
|
||||
You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:
|
||||
|
||||
from rest_framework.documentation import include_docs_urls
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
# Generate schema with valid `request` instance:
|
||||
url(r'^docs/', include_docs_urls(title='My API title', public=False))
|
||||
]
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Documenting your views
|
||||
|
||||
You can document your views by including docstrings that describe each of the available actions.
|
||||
For example:
|
||||
|
||||
class UserList(generics.ListAPIView):
|
||||
"""
|
||||
Return a list of all the existing users.
|
||||
"""
|
||||
|
||||
If a view supports multiple methods, you should split your documentation using `method:` style delimiters.
|
||||
|
||||
class UserList(generics.ListCreateAPIView):
|
||||
"""
|
||||
get:
|
||||
Return a list of all the existing users.
|
||||
|
||||
post:
|
||||
Create a new user instance.
|
||||
"""
|
||||
|
||||
When using viewsets, you should use the relevant action names as delimiters.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
retrieve:
|
||||
Return the given user.
|
||||
|
||||
list:
|
||||
Return a list of all the existing users.
|
||||
|
||||
create:
|
||||
Create a new user instance.
|
||||
"""
|
||||
|
||||
Custom actions on viewsets can also be documented in a similar way using the method names
|
||||
as delimiters or by attaching the documentation to action mapping methods.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewset):
|
||||
...
|
||||
|
||||
@action(detail=False, methods=['get', 'post'])
|
||||
def some_action(self, request, *args, **kwargs):
|
||||
"""
|
||||
get:
|
||||
A description of the get method on the custom action.
|
||||
|
||||
post:
|
||||
A description of the post method on the custom action.
|
||||
"""
|
||||
|
||||
@some_action.mapping.put
|
||||
def put_some_action():
|
||||
"""
|
||||
A description of the put method on the custom action.
|
||||
"""
|
||||
|
||||
|
||||
### `documentation` API Reference
|
||||
|
||||
The `rest_framework.documentation` module provides three helper functions to help configure the interactive API documentation, `include_docs_urls` (usage shown above), `get_docs_view` and `get_schemajs_view`.
|
||||
|
||||
`include_docs_urls` employs `get_docs_view` and `get_schemajs_view` to generate the url patterns for the documentation page and JavaScript resource that exposes the API schema respectively. They expose the following options for customisation. (`get_docs_view` and `get_schemajs_view` ultimately call `rest_frameworks.schemas.get_schema_view()`, see the Schemas docs for more options there.)
|
||||
|
||||
#### `include_docs_urls`
|
||||
|
||||
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Default `None`. May be used to provide a description for the schema definition.
|
||||
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
|
||||
* `public`: Default `True`. Should the schema be considered _public_? If `True` schema is generated without a `request` instance being passed to views.
|
||||
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
|
||||
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
|
||||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`.
|
||||
* `renderer_classes`: Default `None`. May be used to pass custom renderer classes to the `SchemaView`.
|
||||
|
||||
#### `get_docs_view`
|
||||
|
||||
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Default `None`. May be used to provide a description for the schema definition.
|
||||
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
|
||||
* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views.
|
||||
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
|
||||
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
|
||||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES`. May be used to pass custom permission classes to the `SchemaView`.
|
||||
* `renderer_classes`: Default `None`. May be used to pass custom renderer classes to the `SchemaView`. If `None` the `SchemaView` will be configured with `DocumentationRenderer` and `CoreJSONRenderer` renderers, corresponding to the (default) `html` and `corejson` formats.
|
||||
|
||||
#### `get_schemajs_view`
|
||||
|
||||
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Default `None`. May be used to provide a description for the schema definition.
|
||||
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
|
||||
* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views.
|
||||
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
|
||||
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
|
||||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`.
|
||||
|
||||
|
||||
### Customising code samples
|
||||
|
||||
The built-in API documentation includes automatically generated code samples for
|
||||
each of the available API client libraries.
|
||||
|
||||
You may customise these samples by subclassing `DocumentationRenderer`, setting
|
||||
`languages` to the list of languages you wish to support:
|
||||
|
||||
from rest_framework.renderers import DocumentationRenderer
|
||||
|
||||
|
||||
class CustomRenderer(DocumentationRenderer):
|
||||
languages = ['ruby', 'go']
|
||||
|
||||
For each language you need to provide an `intro` template, detailing installation instructions and such,
|
||||
plus a generic template for making API requests, that can be filled with individual request details.
|
||||
See the [templates for the bundled languages][client-library-templates] for examples.
|
||||
|
||||
---
|
||||
|
||||
[client-library-templates]: https://github.com/encode/django-rest-framework/tree/master/rest_framework/templates/rest_framework/docs/langs
|
29
docs/coreapi/index.md
Normal file
|
@ -0,0 +1,29 @@
|
|||
# Legacy CoreAPI Schemas Docs
|
||||
|
||||
Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation in Django REST Framework v3.10.
|
||||
|
||||
See the [Version 3.10 Release Announcement](/community/3.10-announcement.md) for more details.
|
||||
|
||||
----
|
||||
|
||||
You can continue to use CoreAPI schemas by setting the appropriate default schema class:
|
||||
|
||||
```python
|
||||
# In settings.py
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
|
||||
}
|
||||
```
|
||||
|
||||
Under-the-hood, any subclass of `coreapi.AutoSchema` here will trigger use of the old CoreAPI schemas.
|
||||
**Otherwise** you will automatically be opted-in to the new OpenAPI schemas.
|
||||
|
||||
All CoreAPI related code will be removed in Django REST Framework v3.12. Switch to OpenAPI schemas by then.
|
||||
|
||||
----
|
||||
|
||||
For reference this folder contains the old CoreAPI related documentation:
|
||||
|
||||
* [Tutorial 7: Schemas & client libraries](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//7-schemas-and-client-libraries.md).
|
||||
* [Excerpts from _Documenting your API_ topic page](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//from-documenting-your-api.md).
|
||||
* [`rest_framework.schemas` API Reference](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//schemas.md).
|
838
docs/coreapi/schemas.md
Normal file
|
@ -0,0 +1,838 @@
|
|||
source: schemas.py
|
||||
|
||||
# Schemas
|
||||
|
||||
> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.
|
||||
>
|
||||
> — Heroku, [JSON Schema for the Heroku Platform API][cite]
|
||||
|
||||
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.
|
||||
|
||||
## Install Core API & PyYAML
|
||||
|
||||
You'll need to install the `coreapi` package in order to add schema support
|
||||
for REST framework. You probably also want to install `pyyaml`, so that you
|
||||
can render the schema into the commonly used YAML-based OpenAPI format.
|
||||
|
||||
pip install coreapi pyyaml
|
||||
|
||||
## Quickstart
|
||||
|
||||
There are two different ways you can serve a schema description for your API.
|
||||
|
||||
### Generating a schema with the `generateschema` management command
|
||||
|
||||
To generate a static API schema, use the `generateschema` management command.
|
||||
|
||||
```shell
|
||||
$ python manage.py generateschema > 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.
|
||||
|
||||
### Adding a view with `get_schema_view`
|
||||
|
||||
To add a dynamically generated schema view to your API, use `get_schema_view`.
|
||||
|
||||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
|
||||
schema_view = get_schema_view(title="Example API")
|
||||
|
||||
urlpatterns = [
|
||||
url('^schema$', schema_view),
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
See below [for more details](#the-get_schema_view-shortcut) on customizing a
|
||||
dynamically generated schema view.
|
||||
|
||||
## Internal schema representation
|
||||
|
||||
REST framework uses [Core API][coreapi] in order to model schema information in
|
||||
a format-independent representation. This information can then be rendered
|
||||
into various different schema formats, or used to generate API documentation.
|
||||
|
||||
When using Core API, a schema is represented as a `Document` which is the
|
||||
top-level container object for information about the API. Available API
|
||||
interactions are represented using `Link` objects. Each link includes a URL,
|
||||
HTTP method, and may include a list of `Field` instances, which describe any
|
||||
parameters that may be accepted by the API endpoint. The `Link` and `Field`
|
||||
instances may also include descriptions, that allow an API schema to be
|
||||
rendered into user documentation.
|
||||
|
||||
Here's an example of an API description that includes a single `search`
|
||||
endpoint:
|
||||
|
||||
coreapi.Document(
|
||||
title='Flight Search API',
|
||||
url='https://api.example.org/',
|
||||
content={
|
||||
'search': coreapi.Link(
|
||||
url='/search/',
|
||||
action='get',
|
||||
fields=[
|
||||
coreapi.Field(
|
||||
name='from',
|
||||
required=True,
|
||||
location='query',
|
||||
description='City name or airport code.'
|
||||
),
|
||||
coreapi.Field(
|
||||
name='to',
|
||||
required=True,
|
||||
location='query',
|
||||
description='City name or airport code.'
|
||||
),
|
||||
coreapi.Field(
|
||||
name='date',
|
||||
required=True,
|
||||
location='query',
|
||||
description='Flight date in "YYYY-MM-DD" format.'
|
||||
)
|
||||
],
|
||||
description='Return flight availability and prices.'
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
## Schema output formats
|
||||
|
||||
In order to be presented in an HTTP response, the internal representation
|
||||
has to be rendered into the actual bytes that are used in the response.
|
||||
|
||||
REST framework includes a few different renderers that you can use for
|
||||
encoding the API schema.
|
||||
|
||||
* `renderers.OpenAPIRenderer` - Renders into YAML-based [OpenAPI][open-api], the most widely used API schema format.
|
||||
* `renderers.JSONOpenAPIRenderer` - Renders into JSON-based [OpenAPI][open-api].
|
||||
* `renderers.CoreJSONRenderer` - Renders into [Core JSON][corejson], a format designed for
|
||||
use with the `coreapi` client library.
|
||||
|
||||
|
||||
[Core JSON][corejson] is designed as a canonical format for use with Core API.
|
||||
REST framework includes a renderer class for handling this media type, which
|
||||
is available as `renderers.CoreJSONRenderer`.
|
||||
|
||||
|
||||
## Schemas vs Hypermedia
|
||||
|
||||
It's worth pointing out here that Core API can also be used to model hypermedia
|
||||
responses, which present an alternative interaction style to API schemas.
|
||||
|
||||
With an API schema, the entire available interface is presented up-front
|
||||
as a single endpoint. Responses to individual API endpoints are then typically
|
||||
presented as plain data, without any further interactions contained in each
|
||||
response.
|
||||
|
||||
With Hypermedia, the client is instead presented with a document containing
|
||||
both data and available interactions. Each interaction results in a new
|
||||
document, detailing both the current state and the available interactions.
|
||||
|
||||
Further information and support on building Hypermedia APIs with REST framework
|
||||
is planned for a future version.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Creating a schema
|
||||
|
||||
REST framework includes functionality for auto-generating a schema,
|
||||
or allows you to specify one explicitly.
|
||||
|
||||
## Manual Schema Specification
|
||||
|
||||
To manually specify a schema you create a Core API `Document`, similar to the
|
||||
example above.
|
||||
|
||||
schema = coreapi.Document(
|
||||
title='Flight Search API',
|
||||
content={
|
||||
...
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
## Automatic Schema Generation
|
||||
|
||||
Automatic schema generation is provided by the `SchemaGenerator` class.
|
||||
|
||||
`SchemaGenerator` processes a list of routed URL patterns and compiles the
|
||||
appropriately structured Core API Document.
|
||||
|
||||
Basic usage is just to provide the title for your schema and call
|
||||
`get_schema()`:
|
||||
|
||||
generator = schemas.SchemaGenerator(title='Flight Search API')
|
||||
schema = generator.get_schema()
|
||||
|
||||
## Per-View Schema Customisation
|
||||
|
||||
By default, view introspection is performed by an `AutoSchema` instance
|
||||
accessible via the `schema` attribute on `APIView`. This provides the
|
||||
appropriate Core API `Link` object for the view, request method and path:
|
||||
|
||||
auto_schema = view.schema
|
||||
coreapi_link = auto_schema.get_link(...)
|
||||
|
||||
(In compiling the schema, `SchemaGenerator` calls `view.schema.get_link()` for
|
||||
each view, allowed method and path.)
|
||||
|
||||
---
|
||||
|
||||
**Note**: For basic `APIView` subclasses, default introspection is essentially
|
||||
limited to the URL kwarg path parameters. For `GenericAPIView`
|
||||
subclasses, which includes all the provided class based views, `AutoSchema` will
|
||||
attempt to introspect serializer, pagination and filter fields, as well as
|
||||
provide richer path field descriptions. (The key hooks here are the relevant
|
||||
`GenericAPIView` attributes and methods: `get_serializer`, `pagination_class`,
|
||||
`filter_backends` and so on.)
|
||||
|
||||
---
|
||||
|
||||
To customise the `Link` generation you may:
|
||||
|
||||
* Instantiate `AutoSchema` on your view with the `manual_fields` kwarg:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import AutoSchema
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = AutoSchema(
|
||||
manual_fields=[
|
||||
coreapi.Field("extra_field", ...),
|
||||
]
|
||||
)
|
||||
|
||||
This allows extension for the most common case without subclassing.
|
||||
|
||||
* Provide an `AutoSchema` subclass with more complex customisation:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import AutoSchema
|
||||
|
||||
class CustomSchema(AutoSchema):
|
||||
def get_link(...):
|
||||
# Implement custom introspection here (or in other sub-methods)
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = CustomSchema()
|
||||
|
||||
This provides complete control over view introspection.
|
||||
|
||||
* Instantiate `ManualSchema` on your view, providing the Core API `Fields` for
|
||||
the view explicitly:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import ManualSchema
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = ManualSchema(fields=[
|
||||
coreapi.Field(
|
||||
"first_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
coreapi.Field(
|
||||
"second_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
])
|
||||
|
||||
This allows manually specifying the schema for some views whilst maintaining
|
||||
automatic generation elsewhere.
|
||||
|
||||
You may disable schema generation for a view by setting `schema` to `None`:
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = None # Will not appear in schema
|
||||
|
||||
This also applies to extra actions for `ViewSet`s:
|
||||
|
||||
class CustomViewSet(viewsets.ModelViewSet):
|
||||
|
||||
@action(detail=True, schema=None)
|
||||
def extra_action(self, request, pk=None):
|
||||
...
|
||||
|
||||
---
|
||||
|
||||
**Note**: For full details on `SchemaGenerator` plus the `AutoSchema` and
|
||||
`ManualSchema` descriptors see the [API Reference below](#api-reference).
|
||||
|
||||
---
|
||||
|
||||
# Adding a schema view
|
||||
|
||||
There are a few different ways to add a schema view to your API, depending on
|
||||
exactly what you need.
|
||||
|
||||
## The get_schema_view shortcut
|
||||
|
||||
The simplest way to include a schema in your project is to use the
|
||||
`get_schema_view()` function.
|
||||
|
||||
from rest_framework.schemas import get_schema_view
|
||||
|
||||
schema_view = get_schema_view(title="Server Monitoring API")
|
||||
|
||||
urlpatterns = [
|
||||
url('^$', schema_view),
|
||||
...
|
||||
]
|
||||
|
||||
Once the view has been added, you'll be able to make API requests to retrieve
|
||||
the auto-generated schema definition.
|
||||
|
||||
$ http http://127.0.0.1:8000/ Accept:application/coreapi+json
|
||||
HTTP/1.0 200 OK
|
||||
Allow: GET, HEAD, OPTIONS
|
||||
Content-Type: application/vnd.coreapi+json
|
||||
|
||||
{
|
||||
"_meta": {
|
||||
"title": "Server Monitoring API"
|
||||
},
|
||||
"_type": "document",
|
||||
...
|
||||
}
|
||||
|
||||
The arguments to `get_schema_view()` are:
|
||||
|
||||
#### `title`
|
||||
|
||||
May be used to provide a descriptive title for the schema definition.
|
||||
|
||||
#### `url`
|
||||
|
||||
May be used to pass a canonical 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'
|
||||
)
|
||||
|
||||
#### `renderer_classes`
|
||||
|
||||
May be used to pass the set of renderer classes that can be used to render the API root endpoint.
|
||||
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework.renderers import JSONOpenAPIRenderer
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
renderer_classes=[JSONOpenAPIRenderer]
|
||||
)
|
||||
|
||||
#### `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 = [
|
||||
url(r'^api/', include('myproject.api.urls')),
|
||||
]
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
patterns=schema_url_patterns,
|
||||
)
|
||||
|
||||
#### `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`
|
||||
|
||||
## Using an explicit schema view
|
||||
|
||||
If you need a little more control than the `get_schema_view()` shortcut gives you,
|
||||
then you can use the `SchemaGenerator` class directly to auto-generate the
|
||||
`Document` instance, and to return that from a view.
|
||||
|
||||
This option gives you the flexibility of setting up the schema endpoint
|
||||
with whatever behaviour you want. For example, you can apply different
|
||||
permission, throttling, or authentication policies to the schema endpoint.
|
||||
|
||||
Here's an example of using `SchemaGenerator` together with a view to
|
||||
return the schema.
|
||||
|
||||
**views.py:**
|
||||
|
||||
from rest_framework.decorators import api_view, renderer_classes
|
||||
from rest_framework import renderers, response, schemas
|
||||
|
||||
generator = schemas.SchemaGenerator(title='Bookings API')
|
||||
|
||||
@api_view()
|
||||
@renderer_classes([renderers.OpenAPIRenderer])
|
||||
def schema_view(request):
|
||||
schema = generator.get_schema(request)
|
||||
return response.Response(schema)
|
||||
|
||||
**urls.py:**
|
||||
|
||||
urlpatterns = [
|
||||
url('/', schema_view),
|
||||
...
|
||||
]
|
||||
|
||||
You can also serve different schemas to different users, depending on the
|
||||
permissions they have available. This approach can be used to ensure that
|
||||
unauthenticated requests are presented with a different schema to
|
||||
authenticated requests, or to ensure that different parts of the API are
|
||||
made visible to different users depending on their role.
|
||||
|
||||
In order to present a schema with endpoints filtered by user permissions,
|
||||
you need to pass the `request` argument to the `get_schema()` method, like so:
|
||||
|
||||
@api_view()
|
||||
@renderer_classes([renderers.OpenAPIRenderer])
|
||||
def schema_view(request):
|
||||
generator = schemas.SchemaGenerator(title='Bookings API')
|
||||
return response.Response(generator.get_schema(request=request))
|
||||
|
||||
## Explicit schema definition
|
||||
|
||||
An alternative to the auto-generated approach is to specify the API schema
|
||||
explicitly, by declaring a `Document` object in your codebase. Doing so is a
|
||||
little more work, but ensures that you have full control over the schema
|
||||
representation.
|
||||
|
||||
import coreapi
|
||||
from rest_framework.decorators import api_view, renderer_classes
|
||||
from rest_framework import renderers, response
|
||||
|
||||
schema = coreapi.Document(
|
||||
title='Bookings API',
|
||||
content={
|
||||
...
|
||||
}
|
||||
)
|
||||
|
||||
@api_view()
|
||||
@renderer_classes([renderers.OpenAPIRenderer])
|
||||
def schema_view(request):
|
||||
return response.Response(schema)
|
||||
|
||||
---
|
||||
|
||||
# Schemas as documentation
|
||||
|
||||
One common usage of API schemas is to use them to build documentation pages.
|
||||
|
||||
The schema generation in REST framework uses docstrings to automatically
|
||||
populate descriptions in the schema document.
|
||||
|
||||
These descriptions will be based on:
|
||||
|
||||
* The corresponding method docstring if one exists.
|
||||
* A named section within the class docstring, which can be either single line or multi-line.
|
||||
* The class docstring.
|
||||
|
||||
## Examples
|
||||
|
||||
An `APIView`, with an explicit method docstring.
|
||||
|
||||
class ListUsernames(APIView):
|
||||
def get(self, request):
|
||||
"""
|
||||
Return a list of all user names in the system.
|
||||
"""
|
||||
usernames = [user.username for user in User.objects.all()]
|
||||
return Response(usernames)
|
||||
|
||||
A `ViewSet`, with an explicit action docstring.
|
||||
|
||||
class ListUsernames(ViewSet):
|
||||
def list(self, request):
|
||||
"""
|
||||
Return a list of all user names in the system.
|
||||
"""
|
||||
usernames = [user.username for user in User.objects.all()]
|
||||
return Response(usernames)
|
||||
|
||||
A generic view with sections in the class docstring, using single-line style.
|
||||
|
||||
class UserList(generics.ListCreateAPIView):
|
||||
"""
|
||||
get: List all the users.
|
||||
post: Create a new user.
|
||||
"""
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = [IsAdminUser]
|
||||
|
||||
A generic viewset with sections in the class docstring, using multi-line style.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
API endpoint that allows users to be viewed or edited.
|
||||
|
||||
retrieve:
|
||||
Return a user instance.
|
||||
|
||||
list:
|
||||
Return all users, ordered by most recently joined.
|
||||
"""
|
||||
queryset = User.objects.all().order_by('-date_joined')
|
||||
serializer_class = UserSerializer
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## SchemaGenerator
|
||||
|
||||
A class that walks a list of routed URL patterns, requests the schema for each view,
|
||||
and collates the resulting CoreAPI Document.
|
||||
|
||||
Typically you'll instantiate `SchemaGenerator` with a single argument, like so:
|
||||
|
||||
generator = SchemaGenerator(title='Stock Prices API')
|
||||
|
||||
Arguments:
|
||||
|
||||
* `title` **required** - The name of the API.
|
||||
* `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`.
|
||||
|
||||
### get_schema(self, request)
|
||||
|
||||
Returns a `coreapi.Document` instance that represents the API schema.
|
||||
|
||||
@api_view
|
||||
@renderer_classes([renderers.OpenAPIRenderer])
|
||||
def schema_view(request):
|
||||
generator = schemas.SchemaGenerator(title='Bookings API')
|
||||
return Response(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.
|
||||
|
||||
### get_links(self, request)
|
||||
|
||||
Return a nested dictionary containing all the links that should be included in the API schema.
|
||||
|
||||
This is a good point to override if you want to modify the resulting structure of the generated schema,
|
||||
as you can build a new dictionary with a different layout.
|
||||
|
||||
|
||||
## AutoSchema
|
||||
|
||||
A class that deals with introspection of individual views for schema generation.
|
||||
|
||||
`AutoSchema` is attached to `APIView` via the `schema` attribute.
|
||||
|
||||
The `AutoSchema` constructor takes a single keyword argument `manual_fields`.
|
||||
|
||||
**`manual_fields`**: a `list` of `coreapi.Field` instances that will be added to
|
||||
the generated fields. Generated fields with a matching `name` will be overwritten.
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = AutoSchema(manual_fields=[
|
||||
coreapi.Field(
|
||||
"my_extra_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
])
|
||||
|
||||
For more advanced customisation subclass `AutoSchema` to customise schema generation.
|
||||
|
||||
class CustomViewSchema(AutoSchema):
|
||||
"""
|
||||
Overrides `get_link()` to provide Custom Behavior X
|
||||
"""
|
||||
|
||||
def get_link(self, path, method, base_url):
|
||||
link = super().get_link(path, method, base_url)
|
||||
# Do something to customize link here...
|
||||
return link
|
||||
|
||||
class MyView(APIView):
|
||||
schema = CustomViewSchema()
|
||||
|
||||
The following methods are available to override.
|
||||
|
||||
### get_link(self, path, method, base_url)
|
||||
|
||||
Returns a `coreapi.Link` instance corresponding to the given view.
|
||||
|
||||
This is the main entry point.
|
||||
You can override this if you need to provide custom behaviors for particular views.
|
||||
|
||||
### get_description(self, path, method)
|
||||
|
||||
Returns a string to use as the link description. By default this is based on the
|
||||
view docstring as described in the "Schemas as Documentation" section above.
|
||||
|
||||
### get_encoding(self, path, method)
|
||||
|
||||
Returns a string to indicate the encoding for any request body, when interacting
|
||||
with the given view. Eg. `'application/json'`. May return a blank string for views
|
||||
that do not expect a request body.
|
||||
|
||||
### get_path_fields(self, path, method):
|
||||
|
||||
Return a list of `coreapi.Field()` instances. One for each path parameter in the URL.
|
||||
|
||||
### get_serializer_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances. One for each field in the serializer class used by the view.
|
||||
|
||||
### get_pagination_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method on any pagination class used by the view.
|
||||
|
||||
### get_filter_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method of any filter classes used by the view.
|
||||
|
||||
### get_manual_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances to be added to or replace generated fields. Defaults to (optional) `manual_fields` passed to `AutoSchema` constructor.
|
||||
|
||||
May be overridden to customise manual fields by `path` or `method`. For example, a per-method adjustment may look like this:
|
||||
|
||||
```python
|
||||
def get_manual_fields(self, path, method):
|
||||
"""Example adding per-method fields."""
|
||||
|
||||
extra_fields = []
|
||||
if method=='GET':
|
||||
extra_fields = # ... list of extra fields for GET ...
|
||||
if method=='POST':
|
||||
extra_fields = # ... list of extra fields for POST ...
|
||||
|
||||
manual_fields = super().get_manual_fields(path, method)
|
||||
return manual_fields + extra_fields
|
||||
```
|
||||
|
||||
### update_fields(fields, update_with)
|
||||
|
||||
Utility `staticmethod`. Encapsulates logic to add or replace fields from a list
|
||||
by `Field.name`. May be overridden to adjust replacement criteria.
|
||||
|
||||
|
||||
## ManualSchema
|
||||
|
||||
Allows manually providing a list of `coreapi.Field` instances for the schema,
|
||||
plus an optional description.
|
||||
|
||||
class MyView(APIView):
|
||||
schema = ManualSchema(fields=[
|
||||
coreapi.Field(
|
||||
"first_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
coreapi.Field(
|
||||
"second_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
The `ManualSchema` constructor takes two arguments:
|
||||
|
||||
**`fields`**: A list of `coreapi.Field` instances. Required.
|
||||
|
||||
**`description`**: A string description. Optional.
|
||||
|
||||
**`encoding`**: Default `None`. A string encoding, e.g `application/json`. Optional.
|
||||
|
||||
---
|
||||
|
||||
## Core API
|
||||
|
||||
This documentation gives a brief overview of the components within the `coreapi`
|
||||
package that are used to represent an API schema.
|
||||
|
||||
Note that these classes are imported from the `coreapi` package, rather than
|
||||
from the `rest_framework` package.
|
||||
|
||||
### Document
|
||||
|
||||
Represents a container for the API schema.
|
||||
|
||||
#### `title`
|
||||
|
||||
A name for the API.
|
||||
|
||||
#### `url`
|
||||
|
||||
A canonical URL for the API.
|
||||
|
||||
#### `content`
|
||||
|
||||
A dictionary, containing the `Link` objects that the schema contains.
|
||||
|
||||
In order to provide more structure to the schema, the `content` dictionary
|
||||
may be nested, typically to a second level. For example:
|
||||
|
||||
content={
|
||||
"bookings": {
|
||||
"list": Link(...),
|
||||
"create": Link(...),
|
||||
...
|
||||
},
|
||||
"venues": {
|
||||
"list": Link(...),
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
### Link
|
||||
|
||||
Represents an individual API endpoint.
|
||||
|
||||
#### `url`
|
||||
|
||||
The URL of the endpoint. May be a URI template, such as `/users/{username}/`.
|
||||
|
||||
#### `action`
|
||||
|
||||
The HTTP method associated with the endpoint. Note that URLs that support
|
||||
more than one HTTP method, should correspond to a single `Link` for each.
|
||||
|
||||
#### `fields`
|
||||
|
||||
A list of `Field` instances, describing the available parameters on the input.
|
||||
|
||||
#### `description`
|
||||
|
||||
A short description of the meaning and intended usage of the endpoint.
|
||||
|
||||
### Field
|
||||
|
||||
Represents a single input parameter on a given API endpoint.
|
||||
|
||||
#### `name`
|
||||
|
||||
A descriptive name for the input.
|
||||
|
||||
#### `required`
|
||||
|
||||
A boolean, indicated if the client is required to included a value, or if
|
||||
the parameter can be omitted.
|
||||
|
||||
#### `location`
|
||||
|
||||
Determines how the information is encoded into the request. Should be one of
|
||||
the following strings:
|
||||
|
||||
**"path"**
|
||||
|
||||
Included in a templated URI. For example a `url` value of `/products/{product_code}/` could be used together with a `"path"` field, to handle API inputs in a URL path such as `/products/slim-fit-jeans/`.
|
||||
|
||||
These fields will normally correspond with [named arguments in the project URL conf][named-arguments].
|
||||
|
||||
**"query"**
|
||||
|
||||
Included as a URL query parameter. For example `?search=sale`. Typically for `GET` requests.
|
||||
|
||||
These fields will normally correspond with pagination and filtering controls on a view.
|
||||
|
||||
**"form"**
|
||||
|
||||
Included in the request body, as a single item of a JSON object or HTML form. For example `{"colour": "blue", ...}`. Typically for `POST`, `PUT` and `PATCH` requests. Multiple `"form"` fields may be included on a single link.
|
||||
|
||||
These fields will normally correspond with serializer fields on a view.
|
||||
|
||||
**"body"**
|
||||
|
||||
Included as the complete request body. Typically for `POST`, `PUT` and `PATCH` requests. No more than one `"body"` field may exist on a link. May not be used together with `"form"` fields.
|
||||
|
||||
These fields will normally correspond with views that use `ListSerializer` to validate the request input, or with file upload views.
|
||||
|
||||
#### `encoding`
|
||||
|
||||
**"application/json"**
|
||||
|
||||
JSON encoded request content. Corresponds to views using `JSONParser`.
|
||||
Valid only if either one or more `location="form"` fields, or a single
|
||||
`location="body"` field is included on the `Link`.
|
||||
|
||||
**"multipart/form-data"**
|
||||
|
||||
Multipart encoded request content. Corresponds to views using `MultiPartParser`.
|
||||
Valid only if one or more `location="form"` fields is included on the `Link`.
|
||||
|
||||
**"application/x-www-form-urlencoded"**
|
||||
|
||||
URL encoded request content. Corresponds to views using `FormParser`. Valid
|
||||
only if one or more `location="form"` fields is included on the `Link`.
|
||||
|
||||
**"application/octet-stream"**
|
||||
|
||||
Binary upload request content. Corresponds to views using `FileUploadParser`.
|
||||
Valid only if a `location="body"` field is included on the `Link`.
|
||||
|
||||
#### `description`
|
||||
|
||||
A short description of the meaning and intended usage of the input field.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Third party packages
|
||||
|
||||
## drf-yasg - Yet Another Swagger Generator
|
||||
|
||||
[drf-yasg][drf-yasg] generates [OpenAPI][open-api] documents suitable for code generation - nested schemas,
|
||||
named models, response bodies, enum/pattern/min/max validators, form parameters, etc.
|
||||
|
||||
[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api
|
||||
[coreapi]: https://www.coreapi.org/
|
||||
[corejson]: https://www.coreapi.org/specification/encoding/#core-json-encoding
|
||||
[drf-yasg]: https://github.com/axnsan12/drf-yasg/
|
||||
[open-api]: https://openapis.org/
|
||||
[json-hyperschema]: https://json-schema.org/latest/json-schema-hypermedia.html
|
||||
[api-blueprint]: https://apiblueprint.org/
|
||||
[static-files]: https://docs.djangoproject.com/en/stable/howto/static-files/
|
||||
[named-arguments]: https://docs.djangoproject.com/en/stable/topics/http/urls/#named-groups
|
BIN
docs/img/books/bda-cover.png
Normal file
After Width: | Height: | Size: 46 KiB |
BIN
docs/img/books/rad-cover.png
Normal file
After Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 74 KiB |
BIN
docs/img/drf-yasg.png
Normal file
After Width: | Height: | Size: 58 KiB |
Before Width: | Height: | Size: 567 KiB |
BIN
docs/img/premium/cadre-readme.png
Normal file
After Width: | Height: | Size: 6.8 KiB |
BIN
docs/img/premium/esg-readme.png
Normal file
After Width: | Height: | Size: 13 KiB |
BIN
docs/img/premium/kloudless-readme.png
Normal file
After Width: | Height: | Size: 14 KiB |
BIN
docs/img/premium/lightson-readme.png
Normal file
After Width: | Height: | Size: 16 KiB |
Before Width: | Height: | Size: 13 KiB |
Before Width: | Height: | Size: 23 KiB |
BIN
docs/img/premium/release-history.png
Normal file
After Width: | Height: | Size: 18 KiB |
BIN
docs/img/premium/retool-readme.png
Normal file
After Width: | Height: | Size: 8.8 KiB |
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
Before Width: | Height: | Size: 52 KiB |
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 24 KiB |
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 19 KiB |
209
docs/index.md
|
@ -18,23 +18,19 @@
|
|||
</style>
|
||||
|
||||
<p class="badges" height=20px>
|
||||
<iframe src="http://ghbtns.com/github-btn.html?user=encode&repo=django-rest-framework&type=watch&count=true" class="github-star-button" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
|
||||
<iframe src="https://ghbtns.com/github-btn.html?user=encode&repo=django-rest-framework&type=watch&count=true" class="github-star-button" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
|
||||
|
||||
<a href="http://travis-ci.org/encode/django-rest-framework?branch=master">
|
||||
<a href="https://travis-ci.org/encode/django-rest-framework?branch=master">
|
||||
<img src="https://secure.travis-ci.org/encode/django-rest-framework.svg?branch=master" class="status-badge">
|
||||
</a>
|
||||
|
||||
<a href="https://pypi.python.org/pypi/djangorestframework">
|
||||
<a href="https://pypi.org/project/djangorestframework/">
|
||||
<img src="https://img.shields.io/pypi/v/djangorestframework.svg" class="status-badge">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
**Note**: This is the documentation for the **version 3** of REST framework. Documentation for [version 2](http://tomchristie.github.io/rest-framework-2-docs/) is also available.
|
||||
|
||||
---
|
||||
|
||||
<p>
|
||||
<h1 style="position: absolute;
|
||||
width: 1px;
|
||||
|
@ -70,15 +66,18 @@ 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="http://jobs.rover.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
||||
<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://hello.machinalis.co.uk/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</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, [Rover](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://hello.machinalis.co.uk/), and [Rollbar](https://rollbar.com).*
|
||||
*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).*
|
||||
|
||||
---
|
||||
|
||||
|
@ -86,15 +85,18 @@ continued development by **[signing up for a paid plan][funding]**.
|
|||
|
||||
REST framework requires the following:
|
||||
|
||||
* Python (2.7, 3.2, 3.3, 3.4, 3.5, 3.6)
|
||||
* Django (1.10, 1.11, 2.0 alpha)
|
||||
* Python (3.5, 3.6, 3.7)
|
||||
* Django (1.11, 2.0, 2.1, 2.2)
|
||||
|
||||
We **highly recommend** and only officially support the latest patch release of
|
||||
each Python and Django series.
|
||||
|
||||
The following packages are optional:
|
||||
|
||||
* [coreapi][coreapi] (1.32.0+) - Schema generation support.
|
||||
* [Markdown][markdown] (2.1.0+) - Markdown support for the browsable API.
|
||||
* [Markdown][markdown] (3.0.0+) - Markdown support for the browsable API.
|
||||
* [Pygments][pygments] (2.4.0+) - Add syntax highlighting to Markdown processing.
|
||||
* [django-filter][django-filter] (1.0.1+) - Filtering support.
|
||||
* [django-crispy-forms][django-crispy-forms] - Improved HTML display for filtering.
|
||||
* [django-guardian][django-guardian] (1.1.1+) - Object level permissions support.
|
||||
|
||||
## Installation
|
||||
|
@ -107,14 +109,14 @@ Install using `pip`, including any optional packages you want...
|
|||
|
||||
...or clone the project from github.
|
||||
|
||||
git clone git@github.com:encode/django-rest-framework.git
|
||||
git clone https://github.com/encode/django-rest-framework
|
||||
|
||||
Add `'rest_framework'` to your `INSTALLED_APPS` setting.
|
||||
|
||||
INSTALLED_APPS = (
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
)
|
||||
]
|
||||
|
||||
If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root `urls.py` file.
|
||||
|
||||
|
@ -154,7 +156,7 @@ Here's our project's root `urls.py` module:
|
|||
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ('url', 'username', 'email', 'is_staff')
|
||||
fields = ['url', 'username', 'email', 'is_staff']
|
||||
|
||||
# ViewSets define the view behavior.
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
|
@ -178,82 +180,6 @@ You can now open the API in your browser at [http://127.0.0.1:8000/](http://127.
|
|||
|
||||
Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running, and building APIs with REST framework.
|
||||
|
||||
## Tutorial
|
||||
|
||||
The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.
|
||||
|
||||
* [1 - Serialization][tut-1]
|
||||
* [2 - Requests & Responses][tut-2]
|
||||
* [3 - Class-based views][tut-3]
|
||||
* [4 - Authentication & permissions][tut-4]
|
||||
* [5 - Relationships & hyperlinked APIs][tut-5]
|
||||
* [6 - Viewsets & routers][tut-6]
|
||||
* [7 - Schemas & client libraries][tut-7]
|
||||
|
||||
There is a live example API of the finished tutorial API for testing purposes, [available here][sandbox].
|
||||
|
||||
## API Guide
|
||||
|
||||
The API guide is your complete reference manual to all the functionality provided by REST framework.
|
||||
|
||||
* [Requests][request]
|
||||
* [Responses][response]
|
||||
* [Views][views]
|
||||
* [Generic views][generic-views]
|
||||
* [Viewsets][viewsets]
|
||||
* [Routers][routers]
|
||||
* [Parsers][parsers]
|
||||
* [Renderers][renderers]
|
||||
* [Serializers][serializers]
|
||||
* [Serializer fields][fields]
|
||||
* [Serializer relations][relations]
|
||||
* [Validators][validators]
|
||||
* [Authentication][authentication]
|
||||
* [Permissions][permissions]
|
||||
* [Throttling][throttling]
|
||||
* [Filtering][filtering]
|
||||
* [Pagination][pagination]
|
||||
* [Versioning][versioning]
|
||||
* [Content negotiation][contentnegotiation]
|
||||
* [Metadata][metadata]
|
||||
* [Schemas][schemas]
|
||||
* [Format suffixes][formatsuffixes]
|
||||
* [Returning URLs][reverse]
|
||||
* [Exceptions][exceptions]
|
||||
* [Status codes][status]
|
||||
* [Testing][testing]
|
||||
* [Settings][settings]
|
||||
|
||||
## Topics
|
||||
|
||||
General guides to using REST framework.
|
||||
|
||||
* [Documenting your API][documenting-your-api]
|
||||
* [API Clients][api-clients]
|
||||
* [Internationalization][internationalization]
|
||||
* [AJAX, CSRF & CORS][ajax-csrf-cors]
|
||||
* [HTML & Forms][html-and-forms]
|
||||
* [Browser enhancements][browser-enhancements]
|
||||
* [The Browsable API][browsableapi]
|
||||
* [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas]
|
||||
* [Third Party Packages][third-party-packages]
|
||||
* [Tutorials and Resources][tutorials-and-resources]
|
||||
* [Contributing to REST framework][contributing]
|
||||
* [Project management][project-management]
|
||||
* [3.0 Announcement][3.0-announcement]
|
||||
* [3.1 Announcement][3.1-announcement]
|
||||
* [3.2 Announcement][3.2-announcement]
|
||||
* [3.3 Announcement][3.3-announcement]
|
||||
* [3.4 Announcement][3.4-announcement]
|
||||
* [3.5 Announcement][3.5-announcement]
|
||||
* [3.6 Announcement][3.6-announcement]
|
||||
* [3.7 Announcement][3.7-announcement]
|
||||
* [Kickstarter Announcement][kickstarter-announcement]
|
||||
* [Mozilla Grant][mozilla-grant]
|
||||
* [Funding][funding]
|
||||
* [Release Notes][release-notes]
|
||||
* [Jobs][jobs]
|
||||
|
||||
## Development
|
||||
|
||||
See the [Contribution guidelines][contributing] for information on how to clone
|
||||
|
@ -279,17 +205,22 @@ Send a description of the issue via email to [rest-framework-security@googlegrou
|
|||
|
||||
## License
|
||||
|
||||
Copyright (c) 2011-2017, Tom Christie
|
||||
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
|
||||
* 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.
|
||||
|
||||
* 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
|
||||
|
@ -302,98 +233,38 @@ 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.
|
||||
|
||||
[mozilla]: http://www.mozilla.org/en-US/about/
|
||||
[mozilla]: https://www.mozilla.org/en-US/about/
|
||||
[redhat]: https://www.redhat.com/
|
||||
[heroku]: https://www.heroku.com/
|
||||
[eventbrite]: https://www.eventbrite.co.uk/about/
|
||||
[coreapi]: http://pypi.python.org/pypi/coreapi/
|
||||
[markdown]: http://pypi.python.org/pypi/Markdown/
|
||||
[django-filter]: http://pypi.python.org/pypi/django-filter
|
||||
[django-crispy-forms]: https://github.com/maraujop/django-crispy-forms
|
||||
[coreapi]: https://pypi.org/project/coreapi/
|
||||
[markdown]: https://pypi.org/project/Markdown/
|
||||
[pygments]: https://pypi.org/project/Pygments/
|
||||
[django-filter]: https://pypi.org/project/django-filter/
|
||||
[django-guardian]: https://github.com/django-guardian/django-guardian
|
||||
[0.4]: https://github.com/encode/django-rest-framework/tree/0.4.X
|
||||
[image]: img/quickstart.png
|
||||
[index]: .
|
||||
[oauth1-section]: api-guide/authentication/#django-rest-framework-oauth
|
||||
[oauth2-section]: api-guide/authentication/#django-oauth-toolkit
|
||||
[serializer-section]: api-guide/serializers#serializers
|
||||
[modelserializer-section]: api-guide/serializers#modelserializer
|
||||
[functionview-section]: api-guide/views#function-based-views
|
||||
[sandbox]: http://restframework.herokuapp.com/
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
|
||||
[quickstart]: tutorial/quickstart.md
|
||||
[tut-1]: tutorial/1-serialization.md
|
||||
[tut-2]: tutorial/2-requests-and-responses.md
|
||||
[tut-3]: tutorial/3-class-based-views.md
|
||||
[tut-4]: tutorial/4-authentication-and-permissions.md
|
||||
[tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md
|
||||
[tut-6]: tutorial/6-viewsets-and-routers.md
|
||||
[tut-7]: tutorial/7-schemas-and-client-libraries.md
|
||||
|
||||
[request]: api-guide/requests.md
|
||||
[response]: api-guide/responses.md
|
||||
[views]: api-guide/views.md
|
||||
[generic-views]: api-guide/generic-views.md
|
||||
[viewsets]: api-guide/viewsets.md
|
||||
[routers]: api-guide/routers.md
|
||||
[parsers]: api-guide/parsers.md
|
||||
[renderers]: api-guide/renderers.md
|
||||
[serializers]: api-guide/serializers.md
|
||||
[fields]: api-guide/fields.md
|
||||
[relations]: api-guide/relations.md
|
||||
[validators]: api-guide/validators.md
|
||||
[authentication]: api-guide/authentication.md
|
||||
[permissions]: api-guide/permissions.md
|
||||
[throttling]: api-guide/throttling.md
|
||||
[filtering]: api-guide/filtering.md
|
||||
[pagination]: api-guide/pagination.md
|
||||
[versioning]: api-guide/versioning.md
|
||||
[contentnegotiation]: api-guide/content-negotiation.md
|
||||
[metadata]: api-guide/metadata.md
|
||||
[schemas]: api-guide/schemas.md
|
||||
[formatsuffixes]: api-guide/format-suffixes.md
|
||||
[reverse]: api-guide/reverse.md
|
||||
[exceptions]: api-guide/exceptions.md
|
||||
[status]: api-guide/status-codes.md
|
||||
[testing]: api-guide/testing.md
|
||||
[settings]: api-guide/settings.md
|
||||
|
||||
[documenting-your-api]: topics/documenting-your-api.md
|
||||
[api-clients]: topics/api-clients.md
|
||||
[internationalization]: topics/internationalization.md
|
||||
[ajax-csrf-cors]: topics/ajax-csrf-cors.md
|
||||
[html-and-forms]: topics/html-and-forms.md
|
||||
[browser-enhancements]: topics/browser-enhancements.md
|
||||
[browsableapi]: topics/browsable-api.md
|
||||
[rest-hypermedia-hateoas]: topics/rest-hypermedia-hateoas.md
|
||||
[contributing]: topics/contributing.md
|
||||
[project-management]: topics/project-management.md
|
||||
[third-party-packages]: topics/third-party-packages.md
|
||||
[tutorials-and-resources]: topics/tutorials-and-resources.md
|
||||
[3.0-announcement]: topics/3.0-announcement.md
|
||||
[3.1-announcement]: topics/3.1-announcement.md
|
||||
[3.2-announcement]: topics/3.2-announcement.md
|
||||
[3.3-announcement]: topics/3.3-announcement.md
|
||||
[3.4-announcement]: topics/3.4-announcement.md
|
||||
[3.5-announcement]: topics/3.5-announcement.md
|
||||
[3.6-announcement]: topics/3.6-announcement.md
|
||||
[3.7-announcement]: topics/3.7-announcement.md
|
||||
[kickstarter-announcement]: topics/kickstarter-announcement.md
|
||||
[mozilla-grant]: topics/mozilla-grant.md
|
||||
[funding]: topics/funding.md
|
||||
[release-notes]: topics/release-notes.md
|
||||
[jobs]: topics/jobs.md
|
||||
|
||||
[tox]: http://testrun.org/tox/latest/
|
||||
[contributing]: community/contributing.md
|
||||
[funding]: community/funding.md
|
||||
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[botbot]: https://botbot.me/freenode/restframework/
|
||||
[stack-overflow]: http://stackoverflow.com/
|
||||
[django-rest-framework-tag]: http://stackoverflow.com/questions/tagged/django-rest-framework
|
||||
[django-tag]: http://stackoverflow.com/questions/tagged/django
|
||||
[stack-overflow]: https://stackoverflow.com/
|
||||
[django-rest-framework-tag]: https://stackoverflow.com/questions/tagged/django-rest-framework
|
||||
[security-mail]: mailto:rest-framework-security@googlegroups.com
|
||||
[paid-support]: http://dabapps.com/services/build/api-development/
|
||||
[dabapps]: http://dabapps.com
|
||||
[contact-dabapps]: http://dabapps.com/contact/
|
||||
[twitter]: https://twitter.com/_tomchristie
|
||||
|
|
|
@ -1,159 +0,0 @@
|
|||
# Django REST framework 2.2
|
||||
|
||||
The 2.2 release represents an important point for REST framework, with the addition of Python 3 support, and the introduction of an official deprecation policy.
|
||||
|
||||
## Python 3 support
|
||||
|
||||
Thanks to some fantastic work from [Xavier Ordoquy][xordoquy], Django REST framework 2.2 now supports Python 3. You'll need to be running Django 1.5, and it's worth keeping in mind that Django's Python 3 support is currently [considered experimental][django-python-3].
|
||||
|
||||
Django 1.6's Python 3 support is expected to be officially labeled as 'production-ready'.
|
||||
|
||||
If you want to start ensuring that your own projects are Python 3 ready, we can highly recommend Django's [Porting to Python 3][porting-python-3] documentation.
|
||||
|
||||
Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line with [Django 1.5's Python compatibility][python-compat].
|
||||
|
||||
## Deprecation policy
|
||||
|
||||
We've now introduced an official deprecation policy, which is in line with [Django's deprecation policy][django-deprecation-policy]. This policy will make it easy for you to continue to track the latest, greatest version of REST framework.
|
||||
|
||||
The timeline for deprecation works as follows:
|
||||
|
||||
* Version 2.2 introduces some API changes as detailed in the release notes. It remains fully backwards compatible with 2.1, but will raise `PendingDeprecationWarning` warnings if you use bits of API that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using `python -Wd manage.py test`, you'll be warned of any API changes you need to make.
|
||||
|
||||
* Version 2.3 will escalate these warnings to `DeprecationWarning`, which is loud by default.
|
||||
|
||||
* Version 2.4 will remove the deprecated bits of API entirely.
|
||||
|
||||
Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.
|
||||
|
||||
## Community
|
||||
|
||||
As of the 2.2 merge, we've also hit an impressive milestone. The number of committers listed in [the credits][credits], is now at over **one hundred individuals**. Each name on that list represents at least one merged pull request, however large or small.
|
||||
|
||||
Our [mailing list][mailing-list] and #restframework IRC channel are also very active, and we've got a really impressive rate of development both on REST framework itself, and on third party packages such as the great [django-rest-framework-docs][django-rest-framework-docs] package from [Marc Gibbons][marcgibbons].
|
||||
|
||||
---
|
||||
|
||||
## API changes
|
||||
|
||||
The 2.2 release makes a few changes to the API, in order to make it more consistent, simple, and easier to use.
|
||||
|
||||
### Cleaner to-many related fields
|
||||
|
||||
The `ManyRelatedField()` style is being deprecated in favor of a new `RelatedField(many=True)` syntax.
|
||||
|
||||
For example, if a user is associated with multiple questions, which we want to represent using a primary key relationship, we might use something like the following:
|
||||
|
||||
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||
questions = serializers.PrimaryKeyRelatedField(many=True)
|
||||
|
||||
class Meta:
|
||||
fields = ('username', 'questions')
|
||||
|
||||
The new syntax is cleaner and more obvious, and the change will also make the documentation cleaner, simplify the internal API, and make writing custom relational fields easier.
|
||||
|
||||
The change also applies to serializers. If you have a nested serializer, you should start using `many=True` for to-many relationships. For example, a serializer representation of an Album that can contain many Tracks might look something like this:
|
||||
|
||||
class TrackSerializer(serializer.ModelSerializer):
|
||||
class Meta:
|
||||
model = Track
|
||||
fields = ('name', 'duration')
|
||||
|
||||
class AlbumSerializer(serializer.ModelSerializer):
|
||||
tracks = TrackSerializer(many=True)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ('album_name', 'artist', 'tracks')
|
||||
|
||||
Additionally, the change also applies when serializing or deserializing data. For example to serialize a queryset of models you should now use the `many=True` flag.
|
||||
|
||||
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
|
||||
serializer.data
|
||||
|
||||
This more explicit behavior on serializing and deserializing data [makes integration with non-ORM backends such as MongoDB easier][564], as instances to be serialized can include the `__iter__` method, without incorrectly triggering list-based serialization, or requiring workarounds.
|
||||
|
||||
The implicit to-many behavior on serializers, and the `ManyRelatedField` style classes will continue to function, but will raise a `PendingDeprecationWarning`, which can be made visible using the `-Wd` flag.
|
||||
|
||||
**Note**: If you need to forcibly turn off the implicit "`many=True` for `__iter__` objects" behavior, you can now do so by specifying `many=False`. This will become the default (instead of the current default of `None`) once the deprecation of the implicit behavior is finalised in version 2.4.
|
||||
|
||||
### Cleaner optional relationships
|
||||
|
||||
Serializer relationships for nullable Foreign Keys will change from using the current `null=True` flag, to instead using `required=False`.
|
||||
|
||||
For example, is a user account has an optional foreign key to a company, that you want to express using a hyperlink, you might use the following field in a `Serializer` class:
|
||||
|
||||
current_company = serializers.HyperlinkedRelatedField(required=False)
|
||||
|
||||
This is in line both with the rest of the serializer fields API, and with Django's `Form` and `ModelForm` API.
|
||||
|
||||
Using `required` throughout the serializers API means you won't need to consider if a particular field should take `blank` or `null` arguments instead of `required`, and also means there will be more consistent behavior for how fields are treated when they are not present in the incoming data.
|
||||
|
||||
The `null=True` argument will continue to function, and will imply `required=False`, but will raise a `PendingDeprecationWarning`.
|
||||
|
||||
### Cleaner CharField syntax
|
||||
|
||||
The `CharField` API previously took an optional `blank=True` argument, which was intended to differentiate between null CharField input, and blank CharField input.
|
||||
|
||||
In keeping with Django's CharField API, REST framework's `CharField` will only ever return the empty string, for missing or `None` inputs. The `blank` flag will no longer be in use, and you should instead just use the `required=<bool>` flag. For example:
|
||||
|
||||
extra_details = CharField(required=False)
|
||||
|
||||
The `blank` keyword argument will continue to function, but will raise a `PendingDeprecationWarning`.
|
||||
|
||||
### Simpler object-level permissions
|
||||
|
||||
Custom permissions classes previously used the signature `.has_permission(self, request, view, obj=None)`. This method would be called twice, firstly for the global permissions check, with the `obj` parameter set to `None`, and again for the object-level permissions check when appropriate, with the `obj` parameter set to the relevant model instance.
|
||||
|
||||
The global permissions check and object-level permissions check are now separated into two separate methods, which gives a cleaner, more obvious API.
|
||||
|
||||
* Global permission checks now use the `.has_permission(self, request, view)` signature.
|
||||
* Object-level permission checks use a new method `.has_object_permission(self, request, view, obj)`.
|
||||
|
||||
For example, the following custom permission class:
|
||||
|
||||
class IsOwner(permissions.BasePermission):
|
||||
"""
|
||||
Custom permission to only allow owners of an object to view or edit it.
|
||||
Model instances are expected to include an `owner` attribute.
|
||||
"""
|
||||
|
||||
def has_permission(self, request, view, obj=None):
|
||||
if obj is None:
|
||||
# Ignore global permissions check
|
||||
return True
|
||||
|
||||
return obj.owner == request.user
|
||||
|
||||
Now becomes:
|
||||
|
||||
class IsOwner(permissions.BasePermission):
|
||||
"""
|
||||
Custom permission to only allow owners of an object to view or edit it.
|
||||
Model instances are expected to include an `owner` attribute.
|
||||
"""
|
||||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
return obj.owner == request.user
|
||||
|
||||
If you're overriding the `BasePermission` class, the old-style signature will continue to function, and will correctly handle both global and object-level permissions checks, but its use will raise a `PendingDeprecationWarning`.
|
||||
|
||||
Note also that the usage of the internal APIs for permission checking on the `View` class has been cleaned up slightly, and is now documented and subject to the deprecation policy in all future versions.
|
||||
|
||||
### More explicit hyperlink relations behavior
|
||||
|
||||
When using a serializer with a `HyperlinkedRelatedField` or `HyperlinkedIdentityField`, the hyperlinks would previously use absolute URLs if the serializer context included a `'request'` key, and fall back to using relative URLs otherwise. This could lead to non-obvious behavior, as it might not be clear why some serializers generated absolute URLs, and others do not.
|
||||
|
||||
From version 2.2 onwards, serializers with hyperlinked relationships *always* require a `'request'` key to be supplied in the context dictionary. The implicit behavior will continue to function, but its use will raise a `PendingDeprecationWarning`.
|
||||
|
||||
[xordoquy]: https://github.com/xordoquy
|
||||
[django-python-3]: https://docs.djangoproject.com/en/stable/faq/install/#can-i-use-django-with-python-3
|
||||
[porting-python-3]: https://docs.djangoproject.com/en/stable/topics/python3/
|
||||
[python-compat]: https://docs.djangoproject.com/en/stable/releases/1.5/#python-compatibility
|
||||
[django-deprecation-policy]: https://docs.djangoproject.com/en/stable/internals/release-process/#internal-release-deprecation-policy
|
||||
[credits]: http://www.django-rest-framework.org/topics/credits
|
||||
[mailing-list]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[django-rest-framework-docs]: https://github.com/marcgibbons/django-rest-framework-docs
|
||||
[marcgibbons]: https://github.com/marcgibbons/
|
||||
[issues]: https://github.com/encode/django-rest-framework/issues
|
||||
[564]: https://github.com/encode/django-rest-framework/issues/564
|
|
@ -1,264 +0,0 @@
|
|||
# Django REST framework 2.3
|
||||
|
||||
REST framework 2.3 makes it even quicker and easier to build your Web APIs.
|
||||
|
||||
## ViewSets and Routers
|
||||
|
||||
The 2.3 release introduces the [ViewSet][viewset] and [Router][router] classes.
|
||||
|
||||
A viewset is simply a type of class-based view that allows you to group multiple views into a single common class.
|
||||
|
||||
Routers allow you to automatically determine the URLconf for your viewset classes.
|
||||
|
||||
As an example of just how simple REST framework APIs can now be, here's an API written in a single `urls.py` module:
|
||||
|
||||
"""
|
||||
A REST framework API for viewing and editing users and groups.
|
||||
"""
|
||||
from django.conf.urls.defaults import url, include
|
||||
from django.contrib.auth.models import User, Group
|
||||
from rest_framework import viewsets, routers
|
||||
|
||||
|
||||
# ViewSets define the view behavior.
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
model = User
|
||||
|
||||
class GroupViewSet(viewsets.ModelViewSet):
|
||||
model = Group
|
||||
|
||||
|
||||
# Routers provide an easy way of automatically determining the URL conf
|
||||
router = routers.DefaultRouter()
|
||||
router.register(r'users', UserViewSet)
|
||||
router.register(r'groups', GroupViewSet)
|
||||
|
||||
|
||||
# Wire up our API using automatic URL routing.
|
||||
# Additionally, we include login URLs for the browsable API.
|
||||
urlpatterns = [
|
||||
url(r'^', include(router.urls)),
|
||||
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
||||
]
|
||||
|
||||
The best place to get started with ViewSets and Routers is to take a look at the [newest section in the tutorial][part-6], which demonstrates their usage.
|
||||
|
||||
## Simpler views
|
||||
|
||||
This release rationalises the API and implementation of the generic views, dropping the dependency on Django's `SingleObjectMixin` and `MultipleObjectMixin` classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with.
|
||||
|
||||
This improvement is reflected in improved documentation for the `GenericAPIView` base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses.
|
||||
|
||||
## Easier Serializers
|
||||
|
||||
REST framework lets you be totally explicit regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships.
|
||||
|
||||
The ability to specify exactly how you want to represent relationships is powerful, but it also introduces complexity. In order to keep things more simple, REST framework now allows you to include reverse relationships simply by including the field name in the `fields` metadata of the serializer class.
|
||||
|
||||
For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class.
|
||||
|
||||
class BlogSerializer(serializers.ModelSerializer):
|
||||
comments = serializers.PrimaryKeyRelatedField(many=True)
|
||||
|
||||
class Meta:
|
||||
model = Blog
|
||||
fields = ('id', 'title', 'created', 'comments')
|
||||
|
||||
As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship.
|
||||
|
||||
class BlogSerializer(serializers.ModelSerializer):
|
||||
"""
|
||||
Don't need to specify the 'comments' field explicitly anymore.
|
||||
"""
|
||||
class Meta:
|
||||
model = Blog
|
||||
fields = ('id', 'title', 'created', 'comments')
|
||||
|
||||
Similarly, you can now easily include the primary key in hyperlinked relationships, simply by adding the field name to the metadata.
|
||||
|
||||
class BlogSerializer(serializers.HyperlinkedModelSerializer):
|
||||
"""
|
||||
This is a hyperlinked serializer, which default to using
|
||||
a field named 'url' as the primary identifier.
|
||||
Note that we can now easily also add in the 'id' field.
|
||||
"""
|
||||
class Meta:
|
||||
model = Blog
|
||||
fields = ('url', 'id', 'title', 'created', 'comments')
|
||||
|
||||
## More flexible filtering
|
||||
|
||||
The `FILTER_BACKEND` setting has moved to pending deprecation, in favor of a `DEFAULT_FILTER_BACKENDS` setting that takes a *list* of filter backend classes, instead of a single filter backend class.
|
||||
|
||||
The generic view `filter_backend` attribute has also been moved to pending deprecation in favor of a `filter_backends` setting.
|
||||
|
||||
Being able to specify multiple filters will allow for more flexible, powerful behavior. New filter classes to handle searching and ordering of results are planned to be released shortly.
|
||||
|
||||
---
|
||||
|
||||
# API Changes
|
||||
|
||||
## Simplified generic view classes
|
||||
|
||||
The functionality provided by `SingleObjectAPIView` and `MultipleObjectAPIView` base classes has now been moved into the base class `GenericAPIView`. The implementation of this base class is simple enough that providing subclasses for the base classes of detail and list views is somewhat unnecessary.
|
||||
|
||||
Additionally the base generic view no longer inherits from Django's `SingleObjectMixin` or `MultipleObjectMixin` classes, simplifying the implementation, and meaning you don't need to cross-reference across to Django's codebase.
|
||||
|
||||
Using the `SingleObjectAPIView` and `MultipleObjectAPIView` base classes continues to be supported, but will raise a `PendingDeprecationWarning`. You should instead simply use `GenericAPIView` as the base for any generic view subclasses.
|
||||
|
||||
### Removed attributes
|
||||
|
||||
The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unused and have now been entirely removed.
|
||||
|
||||
* context_object_name
|
||||
* get_context_data()
|
||||
* get_context_object_name()
|
||||
|
||||
The following attributes and methods, which were previously present as part of Django's generic view implementations have also been entirely removed.
|
||||
|
||||
* paginator_class
|
||||
* get_paginator()
|
||||
* get_allow_empty()
|
||||
* get_slug_field()
|
||||
|
||||
There may be cases when removing these bits of API might mean you need to write a little more code if your view has highly customized behavior, but generally we believe that providing a coarser-grained API will make the views easier to work with, and is the right trade-off to make for the vast majority of cases.
|
||||
|
||||
Note that the listed attributes and methods have never been a documented part of the REST framework API, and as such are not covered by the deprecation policy.
|
||||
|
||||
### Simplified methods
|
||||
|
||||
The `get_object` and `get_paginate_by` methods no longer take an optional queryset argument. This makes overridden these methods more obvious, and a little more simple.
|
||||
|
||||
Using an optional queryset with these methods continues to be supported, but will raise a `PendingDeprecationWarning`.
|
||||
|
||||
The `paginate_queryset` method no longer takes a `page_size` argument, or returns a four-tuple of pagination information. Instead it simply takes a queryset argument, and either returns a `page` object with an appropriate page size, or returns `None`, if pagination is not configured for the view.
|
||||
|
||||
Using the `page_size` argument is still supported and will trigger the old-style return type, but will raise a `PendingDeprecationWarning`.
|
||||
|
||||
### Deprecated attributes
|
||||
|
||||
The following attributes are used to control queryset lookup, and have all been moved into a pending deprecation state.
|
||||
|
||||
* pk_url_kwarg = 'pk'
|
||||
* slug_url_kwarg = 'slug'
|
||||
* slug_field = 'slug'
|
||||
|
||||
Their usage is replaced with a single attribute:
|
||||
|
||||
* lookup_field = 'pk'
|
||||
|
||||
This attribute is used both as the regex keyword argument in the URL conf, and as the model field to filter against when looking up a model instance. To use non-pk based lookup, simply set the `lookup_field` argument to an alternative field, and ensure that the keyword argument in the url conf matches the field name.
|
||||
|
||||
For example, a view with 'username' based lookup might look like this:
|
||||
|
||||
class UserDetail(generics.RetrieveAPIView):
|
||||
lookup_field = 'username'
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
|
||||
And would have the following entry in the urlconf:
|
||||
|
||||
url(r'^users/(?P<username>\w+)/$', UserDetail.as_view()),
|
||||
|
||||
Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`.
|
||||
|
||||
The `allow_empty` attribute is also deprecated. To use `allow_empty=False` style behavior you should explicitly override `get_queryset` and raise an `Http404` on empty querysets.
|
||||
|
||||
For example:
|
||||
|
||||
class DisallowEmptyQuerysetMixin(object):
|
||||
def get_queryset(self):
|
||||
queryset = super(DisallowEmptyQuerysetMixin, self).get_queryset()
|
||||
if not queryset.exists():
|
||||
raise Http404
|
||||
return queryset
|
||||
|
||||
In our opinion removing lesser-used attributes like `allow_empty` helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-enforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views.
|
||||
|
||||
## Simpler URL lookups
|
||||
|
||||
The `HyperlinkedRelatedField` class now takes a single optional `lookup_field` argument, that replaces the `pk_url_kwarg`, `slug_url_kwarg`, and `slug_field` arguments.
|
||||
|
||||
For example, you might have a field that references it's relationship by a hyperlink based on a slug field:
|
||||
|
||||
account = HyperlinkedRelatedField(read_only=True,
|
||||
lookup_field='slug',
|
||||
view_name='account-detail')
|
||||
|
||||
Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`.
|
||||
|
||||
## FileUploadParser
|
||||
|
||||
2.3 adds a `FileUploadParser` parser class, that supports raw file uploads, in addition to the existing multipart upload support.
|
||||
|
||||
## DecimalField
|
||||
|
||||
2.3 introduces a `DecimalField` serializer field, which returns `Decimal` instances.
|
||||
|
||||
For most cases APIs using model fields will behave as previously, however if you are using a custom renderer, not provided by REST framework, then you may now need to add support for rendering `Decimal` instances to your renderer implementation.
|
||||
|
||||
## ModelSerializers and reverse relationships
|
||||
|
||||
The support for adding reverse relationships to the `fields` option on a `ModelSerializer` class means that the `get_related_field` and `get_nested_field` method signatures have now changed.
|
||||
|
||||
In the unlikely event that you're providing a custom serializer class, and implementing these methods you should note the new call signature for both methods is now `(self, model_field, related_model, to_many)`. For reverse relationships `model_field` will be `None`.
|
||||
|
||||
The old-style signature will continue to function but will raise a `PendingDeprecationWarning`.
|
||||
|
||||
## View names and descriptions
|
||||
|
||||
The mechanics of how the names and descriptions used in the browsable API are generated has been modified and cleaned up somewhat.
|
||||
|
||||
If you've been customizing this behavior, for example perhaps to use `rst` markup for the browsable API, then you'll need to take a look at the implementation to see what updates you need to make.
|
||||
|
||||
Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated.
|
||||
|
||||
---
|
||||
|
||||
# Other notes
|
||||
|
||||
## More explicit style
|
||||
|
||||
The usage of `model` attribute in generic Views is still supported, but it's usage is generally being discouraged throughout the documentation, in favour of the setting the more explicit `queryset` and `serializer_class` attributes.
|
||||
|
||||
For example, the following is now the recommended style for using generic views:
|
||||
|
||||
class AccountListView(generics.RetrieveAPIView):
|
||||
queryset = MyModel.objects.all()
|
||||
serializer_class = MyModelSerializer
|
||||
|
||||
Using an explicit `queryset` and `serializer_class` attributes makes the functioning of the view more clear than using the shortcut `model` attribute.
|
||||
|
||||
It also makes the usage of the `get_queryset()` or `get_serializer_class()` methods more obvious.
|
||||
|
||||
class AccountListView(generics.RetrieveAPIView):
|
||||
serializer_class = MyModelSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
"""
|
||||
Determine the queryset dynamically, depending on the
|
||||
user making the request.
|
||||
|
||||
Note that overriding this method follows on more obviously now
|
||||
that an explicit `queryset` attribute is the usual view style.
|
||||
"""
|
||||
return self.user.accounts
|
||||
|
||||
## Django 1.3 support
|
||||
|
||||
The 2.3.x release series will be the last series to provide compatibility with Django 1.3.
|
||||
|
||||
## Version 2.2 API changes
|
||||
|
||||
All API changes in 2.2 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default.
|
||||
|
||||
## What comes next?
|
||||
|
||||
* Support for read-write nested serializers is almost complete, and due to be released in the next few weeks.
|
||||
* Extra filter backends for searching and ordering of results are planned to be added shortly.
|
||||
|
||||
The next few months should see a renewed focus on addressing outstanding tickets. The 2.4 release is currently planned for around August-September.
|
||||
|
||||
[viewset]: ../api-guide/viewsets.md
|
||||
[router]: ../api-guide/routers.md
|
||||
[part-6]: ../tutorial/6-viewsets-and-routers.md
|
|
@ -1,172 +0,0 @@
|
|||
# Django REST framework 2.4
|
||||
|
||||
The 2.4 release is largely an intermediate step, tying up some outstanding issues prior to the 3.x series.
|
||||
|
||||
## Version requirements
|
||||
|
||||
Support for Django 1.3 has been dropped.
|
||||
The lowest supported version of Django is now 1.4.2.
|
||||
|
||||
The current plan is for REST framework to remain in lockstep with [Django's long-term support policy][lts-releases].
|
||||
|
||||
## Django 1.7 support
|
||||
|
||||
The optional authtoken application now includes support for *both* Django 1.7 schema migrations, *and* for old-style `south` migrations.
|
||||
|
||||
**If you are using authtoken, and you want to continue using `south`, you must upgrade your `south` package to version 1.0.**
|
||||
|
||||
## Deprecation of `.model` view attribute
|
||||
|
||||
The `.model` attribute on view classes is an optional shortcut for either or both of `.serializer_class` and `.queryset`. Its usage results in more implicit, less obvious behavior.
|
||||
|
||||
The documentation has previously stated that usage of the more explicit style is prefered, and we're now taking that one step further and deprecating the usage of the `.model` shortcut.
|
||||
|
||||
Doing so will mean that there are cases of API code where you'll now need to include a serializer class where you previously were just using the `.model` shortcut. However we firmly believe that it is the right trade-off to make.
|
||||
|
||||
Removing the shortcut takes away an unnecessary layer of abstraction, and makes your codebase more explicit without any significant extra complexity. It also results in better consistency, as there's now only one way to set the serializer class and queryset attributes for the view, instead of two.
|
||||
|
||||
The `DEFAULT_MODEL_SERIALIZER_CLASS` API setting is now also deprecated.
|
||||
|
||||
## Updated test runner
|
||||
|
||||
We now have a new test runner for developing against the project,, that uses the excellent [py.test](http://pytest.org) library.
|
||||
|
||||
To use it make sure you have first installed the test requirements.
|
||||
|
||||
pip install -r requirements-test.txt
|
||||
|
||||
Then run the `runtests.py` script.
|
||||
|
||||
./runtests.py
|
||||
|
||||
The new test runner also includes [flake8](https://flake8.readthedocs.io) code linting, which should help keep our coding style consistent.
|
||||
|
||||
#### Test runner flags
|
||||
|
||||
Run using a more concise output style.
|
||||
|
||||
./runtests -q
|
||||
|
||||
Run the tests using a more concise output style, no coverage, no flake8.
|
||||
|
||||
./runtests --fast
|
||||
|
||||
Don't run the flake8 code linting.
|
||||
|
||||
./runtests --nolint
|
||||
|
||||
Only run the flake8 code linting, don't run the tests.
|
||||
|
||||
./runtests --lintonly
|
||||
|
||||
Run the tests for a given test case.
|
||||
|
||||
./runtests MyTestCase
|
||||
|
||||
Run the tests for a given test method.
|
||||
|
||||
./runtests MyTestCase.test_this_method
|
||||
|
||||
Shorter form to run the tests for a given test method.
|
||||
|
||||
./runtests 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.
|
||||
|
||||
## Improved viewset routing
|
||||
|
||||
The `@action` and `@link` decorators were inflexible in that they only allowed additional routes to be added against instance style URLs, not against list style URLs.
|
||||
|
||||
The `@action` and `@link` decorators have now been moved to pending deprecation, and the `@list_route` and `@detail_route` decorators have been introduced.
|
||||
|
||||
Here's an example of using the new decorators. Firstly we have a detail-type route named "set_password" that acts on a single instance, and takes a `pk` argument in the URL. Secondly we have a list-type route named "recent_users" that acts on a queryset, and does not take any arguments in the URL.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
A viewset that provides the standard actions
|
||||
"""
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
|
||||
@detail_route(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.data['password'])
|
||||
user.save()
|
||||
return Response({'status': 'password set'})
|
||||
else:
|
||||
return Response(serializer.errors,
|
||||
status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
@list_route()
|
||||
def recent_users(self, request):
|
||||
recent_users = User.objects.all().order('-last_login')
|
||||
page = self.paginate_queryset(recent_users)
|
||||
serializer = self.get_pagination_serializer(page)
|
||||
return Response(serializer.data)
|
||||
|
||||
For more details, see the [viewsets documentation](../api-guide/viewsets.md).
|
||||
|
||||
## Throttle behavior
|
||||
|
||||
There's one bugfix in 2.4 that's worth calling out, as it will *invalidate existing throttle caches* when you upgrade.
|
||||
|
||||
We've now fixed a typo on the `cache_format` attribute. Previously this was named `"throtte_%(scope)s_%(ident)s"`, it is now `"throttle_%(scope)s_%(ident)s"`.
|
||||
|
||||
If you're concerned about the invalidation you have two options.
|
||||
|
||||
* Manually pre-populate your cache with the fixed version.
|
||||
* Set the `cache_format` attribute on your throttle class in order to retain the previous incorrect spelling.
|
||||
|
||||
## Other features
|
||||
|
||||
There are also a number of other features and bugfixes as [listed in the release notes][2-4-release-notes]. In particular these include:
|
||||
|
||||
[Customizable view name and description functions][view-name-and-description-settings] for use with the browsable API, by using the `VIEW_NAME_FUNCTION` and `VIEW_DESCRIPTION_FUNCTION` settings.
|
||||
|
||||
Smarter [client IP identification for throttling][client-ip-identification], with the addition of the `NUM_PROXIES` setting.
|
||||
|
||||
Added the standardized `Retry-After` header to throttled responses, as per [RFC 6585](http://tools.ietf.org/html/rfc6585). This should now be used in preference to the custom `X-Throttle-Wait-Seconds` header which will be fully deprecated in 3.0.
|
||||
|
||||
## Deprecations
|
||||
|
||||
All API changes in 2.3 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default.
|
||||
|
||||
All API changes in 2.3 that previously raised `DeprecationWarning` have now been removed entirely.
|
||||
|
||||
Furter details on these deprecations is available in the [2.3 announcement][2-3-announcement].
|
||||
|
||||
## Labels and milestones
|
||||
|
||||
Although not strictly part of the 2.4 release it's also worth noting here that we've been working hard towards improving our triage process.
|
||||
|
||||
The [labels that we use in GitHub][github-labels] have been cleaned up, and all existing tickets triaged. Any given ticket should have one and only one label, indicating its current state.
|
||||
|
||||
We've also [started using milestones][github-milestones] in order to track tickets against particular releases.
|
||||
|
||||
---
|
||||
|
||||

|
||||
|
||||
**Above**: *Overview of our current use of labels and milestones in GitHub.*
|
||||
|
||||
---
|
||||
|
||||
We hope both of these changes will help make the management process more clear and obvious and help keep tickets well-organised and relevant.
|
||||
|
||||
## Next steps
|
||||
|
||||
The next planned release will be 3.0, featuring an improved and simplified serializer implementation.
|
||||
|
||||
Once again, many thanks to all the generous [backers and sponsors][kickstarter-sponsors] who've helped make this possible!
|
||||
|
||||
[lts-releases]: https://docs.djangoproject.com/en/stable/internals/release-process/#long-term-support-lts-releases
|
||||
[2-4-release-notes]: release-notes#240
|
||||
[view-name-and-description-settings]: ../api-guide/settings#view-names-and-descriptions
|
||||
[client-ip-identification]: ../api-guide/throttling#how-clients-are-identified
|
||||
[2-3-announcement]: 2.3-announcement
|
||||
[github-labels]: https://github.com/encode/django-rest-framework/issues
|
||||
[github-milestones]: https://github.com/encode/django-rest-framework/milestones
|
||||
[kickstarter-sponsors]: kickstarter-announcement#sponsors
|
|
@ -33,9 +33,9 @@ The best way to deal with CORS in REST framework is to add the required response
|
|||
|
||||
[Otto Yiu][ottoyiu] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
|
||||
|
||||
[cite]: http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html
|
||||
[cite]: https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/
|
||||
[csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
|
||||
[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax
|
||||
[cors]: http://www.w3.org/TR/cors/
|
||||
[cors]: https://www.w3.org/TR/cors/
|
||||
[ottoyiu]: https://github.com/ottoyiu/
|
||||
[django-cors-headers]: https://github.com/ottoyiu/django-cors-headers/
|
||||
|
|
|
@ -253,7 +253,7 @@ The `TokenAuthentication` class can be used to support REST framework's built-in
|
|||
`TokenAuthentication`, as well as OAuth and JWT schemes.
|
||||
|
||||
auth = coreapi.auth.TokenAuthentication(
|
||||
scheme='JWT'
|
||||
scheme='JWT',
|
||||
token='<token>'
|
||||
)
|
||||
client = coreapi.Client(auth=auth)
|
||||
|
@ -269,8 +269,8 @@ For example, using the "Django REST framework JWT" package
|
|||
client = coreapi.Client()
|
||||
schema = client.get('https://api.example.org/')
|
||||
|
||||
action = ['api-token-auth', 'obtain-token']
|
||||
params = {username: "example", email: "example@example.com"}
|
||||
action = ['api-token-auth', 'create']
|
||||
params = {"username": "example", "password": "secret"}
|
||||
result = client.action(schema, action, params)
|
||||
|
||||
auth = coreapi.auth.TokenAuthentication(
|
||||
|
@ -395,7 +395,7 @@ Once the API documentation URLs are installed, you'll be able to include both th
|
|||
/static/rest_framework/js/coreapi-0.1.1.js
|
||||
/docs/schema.js
|
||||
-->
|
||||
{% load staticfiles %}
|
||||
{% load static %}
|
||||
<script src="{% static 'rest_framework/js/coreapi-0.1.1.js' %}"></script>
|
||||
<script src="{% url 'api-docs:schema-js' %}"></script>
|
||||
|
||||
|
@ -521,7 +521,7 @@ You'll either want to include the API schema in your codebase directly, by copyi
|
|||
})
|
||||
|
||||
[heroku-api]: https://devcenter.heroku.com/categories/platform-api
|
||||
[heroku-example]: http://www.coreapi.org/tools-and-resources/example-services/#heroku-json-hyper-schema
|
||||
[core-api]: http://www.coreapi.org/
|
||||
[heroku-example]: https://www.coreapi.org/tools-and-resources/example-services/#heroku-json-hyper-schema
|
||||
[core-api]: https://www.coreapi.org/
|
||||
[schema-generation]: ../api-guide/schemas.md
|
||||
[transport-adaptors]: http://docs.python-requests.org/en/master/user/advanced/#transport-adapters
|
||||
|
|
|
@ -44,7 +44,7 @@ Full example:
|
|||
{% extends "rest_framework/base.html" %}
|
||||
|
||||
{% block bootstrap_theme %}
|
||||
<link rel="stylesheet" href="http://bootswatch.com/flatly/bootstrap.min.css" type="text/css">
|
||||
<link rel="stylesheet" href="https://bootswatch.com/flatly/bootstrap.min.css" type="text/css">
|
||||
{% endblock %}
|
||||
|
||||
{% block bootstrap_navbar_variant %}{% endblock %}
|
||||
|
@ -94,6 +94,8 @@ To add branding and customize the look-and-feel of the login template, create a
|
|||
|
||||
You can add your site name or branding by including the branding block:
|
||||
|
||||
{% extends "rest_framework/login_base.html" %}
|
||||
|
||||
{% block branding %}
|
||||
<h3 style="margin: 0 0 20px;">My Site Name</h3>
|
||||
{% endblock %}
|
||||
|
@ -148,17 +150,15 @@ There are [a variety of packages for autocomplete widgets][autocomplete-packages
|
|||
|
||||
---
|
||||
|
||||
[cite]: http://en.wikiquote.org/wiki/Alfred_North_Whitehead
|
||||
[cite]: https://en.wikiquote.org/wiki/Alfred_North_Whitehead
|
||||
[drfreverse]: ../api-guide/reverse.md
|
||||
[ffjsonview]: https://addons.mozilla.org/en-US/firefox/addon/jsonview/
|
||||
[chromejsonview]: https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc
|
||||
[bootstrap]: http://getbootstrap.com
|
||||
[bootstrap]: https://getbootstrap.com/
|
||||
[cerulean]: ../img/cerulean.png
|
||||
[slate]: ../img/slate.png
|
||||
[bcustomize]: http://getbootstrap.com/2.3.2/customize.html
|
||||
[bswatch]: http://bootswatch.com/
|
||||
[bcomponents]: http://getbootstrap.com/2.3.2/components.html
|
||||
[bcomponentsnav]: http://getbootstrap.com/2.3.2/components.html#navbar
|
||||
[bswatch]: https://bootswatch.com/
|
||||
[bcomponents]: https://getbootstrap.com/2.3.2/components.html
|
||||
[bcomponentsnav]: https://getbootstrap.com/2.3.2/components.html#navbar
|
||||
[autocomplete-packages]: https://www.djangopackages.com/grids/g/auto-complete/
|
||||
[django-autocomplete-light]: https://github.com/yourlabs/django-autocomplete-light
|
||||
[django-autocomplete-light-install]: https://django-autocomplete-light.readthedocs.io/en/master/install.html
|
||||
|
|
|
@ -51,13 +51,15 @@ For example:
|
|||
|
||||
METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'
|
||||
|
||||
class MethodOverrideMiddleware(object):
|
||||
def process_view(self, request, callback, callback_args, callback_kwargs):
|
||||
if request.method != 'POST':
|
||||
return
|
||||
if METHOD_OVERRIDE_HEADER not in request.META:
|
||||
return
|
||||
class MethodOverrideMiddleware:
|
||||
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
if request.method == 'POST' and METHOD_OVERRIDE_HEADER in request.META:
|
||||
request.method = request.META[METHOD_OVERRIDE_HEADER]
|
||||
return self.get_response(request)
|
||||
|
||||
## URL based accept headers
|
||||
|
||||
|
@ -80,8 +82,8 @@ was later [dropped from the spec][html5]. There remains
|
|||
[ongoing discussion][put_delete] about adding support for `PUT` and `DELETE`,
|
||||
as well as how to support content types other than form-encoded data.
|
||||
|
||||
[cite]: http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260
|
||||
[ajax-form]: https://github.com/encode/ajax-form
|
||||
[rails]: http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work
|
||||
[html5]: http://www.w3.org/TR/html5-diff/#changes-2010-06-24
|
||||
[cite]: https://www.amazon.com/RESTful-Web-Services-Leonard-Richardson/dp/0596529260
|
||||
[ajax-form]: https://github.com/tomchristie/ajax-form
|
||||
[rails]: https://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work
|
||||
[html5]: https://www.w3.org/TR/html5-diff/#changes-2010-06-24
|
||||
[put_delete]: http://amundsen.com/examples/put-delete-forms/
|
||||
|
|
|
@ -4,164 +4,139 @@
|
|||
>
|
||||
> — Roy Fielding, [REST APIs must be hypertext driven][cite]
|
||||
|
||||
REST framework provides built-in support for API documentation. There are also a number of great third-party documentation tools available.
|
||||
REST framework provides built-in support for generating OpenAPI schemas, which
|
||||
can be used with tools that allow you to build API documentation.
|
||||
|
||||
## Built-in API documentation
|
||||
There are also a number of great third-party documentation packages available.
|
||||
|
||||
The built-in API documentation includes:
|
||||
## Generating documentation from OpenAPI schemas
|
||||
|
||||
* Documentation of API endpoints.
|
||||
* Automatically generated code samples for each of the available API client libraries.
|
||||
* Support for API interaction.
|
||||
There are a number of packages available that allow you to generate HTML
|
||||
documentation pages from OpenAPI schemas.
|
||||
|
||||
### Installation
|
||||
Two popular options are [Swagger UI][swagger-ui] and [ReDoc][redoc].
|
||||
|
||||
The `coreapi` library is required as a dependancy for the API docs. Make sure
|
||||
to install the latest version. The `pygments` and `markdown` libraries
|
||||
are optional but recommended.
|
||||
Both require little more than the location of your static schema file or
|
||||
dynamic `SchemaView` endpoint.
|
||||
|
||||
To install the API documentation, you'll need to include it in your projects URLconf:
|
||||
### A minimal example with Swagger UI
|
||||
|
||||
from rest_framework.documentation import include_docs_urls
|
||||
Assuming you've followed the example from the schemas documentation for routing
|
||||
a dynamic `SchemaView`, a minimal Django template for using Swagger UI might be
|
||||
this:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Swagger</title>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="swagger-ui"></div>
|
||||
<script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
|
||||
<script>
|
||||
const ui = SwaggerUIBundle({
|
||||
url: "{% url schema_url %}",
|
||||
dom_id: '#swagger-ui',
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIBundle.SwaggerUIStandalonePreset
|
||||
],
|
||||
layout: "BaseLayout"
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Save this in your templates folder as `swagger-ui.html`. Then route a
|
||||
`TemplateView` in your project's URL conf:
|
||||
|
||||
```python
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
url(r'^docs/', include_docs_urls(title='My API title'))
|
||||
# ...
|
||||
# Route TemplateView to serve Swagger UI template.
|
||||
# * Provide `extra_context` with view name of `SchemaView`.
|
||||
path('swagger-ui/', TemplateView.as_view(
|
||||
template_name='swagger-ui.html',
|
||||
extra_context={'schema_url':'openapi-schema'}
|
||||
), name='swagger-ui'),
|
||||
]
|
||||
```
|
||||
|
||||
This will include two different views:
|
||||
See the [Swagger UI documentation][swagger-ui] for advanced usage.
|
||||
|
||||
* `/docs/` - The documentation page itself.
|
||||
* `/docs/schema.js` - A JavaScript resource that exposes the API schema.
|
||||
### A minimal example with ReDoc.
|
||||
|
||||
---
|
||||
Assuming you've followed the example from the schemas documentation for routing
|
||||
a dynamic `SchemaView`, a minimal Django template for using ReDoc might be
|
||||
this:
|
||||
|
||||
**Note**: By default `include_docs_urls` configures the underlying `SchemaView` to generate _public_ schemas.
|
||||
This means that views will not be instantiated with a `request` instance. i.e. Inside the view `self.request` will be `None`.
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>ReDoc</title>
|
||||
<!-- needed for adaptive design -->
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
|
||||
<!-- ReDoc doesn't change outer page styles -->
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<redoc spec-url='{% url schema_url %}'></redoc>
|
||||
<script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"> </script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
To be compatible with this behaviour methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
|
||||
Save this in your templates folder as `redoc.html`. Then route a `TemplateView`
|
||||
in your project's URL conf:
|
||||
|
||||
You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:
|
||||
|
||||
from rest_framework.documentation import include_docs_urls
|
||||
```python
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
# Generate schema with valid `request` instance:
|
||||
url(r'^docs/', include_docs_urls(title='My API title', public=False))
|
||||
# ...
|
||||
# Route TemplateView to serve the ReDoc template.
|
||||
# * Provide `extra_context` with view name of `SchemaView`.
|
||||
path('redoc/', TemplateView.as_view(
|
||||
template_name='redoc.html',
|
||||
extra_context={'schema_url':'openapi-schema'}
|
||||
), name='redoc'),
|
||||
]
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Documenting your views
|
||||
|
||||
You can document your views by including docstrings that describe each of the available actions.
|
||||
For example:
|
||||
|
||||
class UserList(generics.ListAPIView):
|
||||
"""
|
||||
Return a list of all the existing users.
|
||||
"""
|
||||
|
||||
If a view supports multiple methods, you should split your documentation using `method:` style delimiters.
|
||||
|
||||
class UserList(generics.ListCreateAPIView):
|
||||
"""
|
||||
get:
|
||||
Return a list of all the existing users.
|
||||
|
||||
post:
|
||||
Create a new user instance.
|
||||
"""
|
||||
|
||||
When using viewsets, you should use the relevant action names as delimiters.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
retrieve:
|
||||
Return the given user.
|
||||
|
||||
list:
|
||||
Return a list of all the existing users.
|
||||
|
||||
create:
|
||||
Create a new user instance.
|
||||
"""
|
||||
|
||||
|
||||
### `documentation` API Reference
|
||||
|
||||
The `rest_framework.documentation` module provides three helper functions to help configure the interactive API documentation, `include_docs_url` (usage shown above), `get_docs_view` and `get_schemajs_view`.
|
||||
|
||||
`include_docs_url` employs `get_docs_view` and `get_schemajs_view` to generate the url patterns for the documentation page and JavaScript resource that exposes the API schema respectively. They expose the following options for customisation. (`get_docs_view` and `get_schemajs_view` ultimately call `rest_frameworks.schemas.get_schema_view()`, see the Schemas docs for more options there.)
|
||||
|
||||
#### `include_docs_url`
|
||||
|
||||
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Default `None`. May be used to provide a description for the schema definition.
|
||||
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
|
||||
* `public`: Default `True`. Should the schema be considered _public_? If `True` schema is generated without a `request` instance being passed to views.
|
||||
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
|
||||
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
|
||||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`.
|
||||
|
||||
#### `get_docs_view`
|
||||
|
||||
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Default `None`. May be used to provide a description for the schema definition.
|
||||
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
|
||||
* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views.
|
||||
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
|
||||
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
|
||||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`.
|
||||
|
||||
#### `get_schemajs_view`
|
||||
|
||||
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Default `None`. May be used to provide a description for the schema definition.
|
||||
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
|
||||
* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views.
|
||||
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
|
||||
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
|
||||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`.
|
||||
|
||||
---
|
||||
See the [ReDoc documentation][redoc] for advanced usage.
|
||||
|
||||
## Third party packages
|
||||
|
||||
There are a number of mature third-party packages for providing API documentation.
|
||||
|
||||
#### DRF OpenAPI
|
||||
#### drf-yasg - Yet Another Swagger Generator
|
||||
|
||||
[DRF OpenAPI][drf-openapi] bridges the gap between OpenAPI specification and tool chain with the schema exposed
|
||||
out-of-the-box by Django Rest Framework. Its goals are:
|
||||
[drf-yasg][drf-yasg] is a [Swagger][swagger] generation tool implemented without using the schema generation provided
|
||||
by Django Rest Framework.
|
||||
|
||||
* To be dropped into any existing DRF project without any code change necessary.
|
||||
* Provide clear disctinction between request schema and response schema.
|
||||
* Provide a versioning mechanism for each schema. Support defining schema by version range syntax, e.g. >1.0, <=2.0
|
||||
* Support multiple response codes, not just 200
|
||||
* All this information should be bound to view methods, not view classes.
|
||||
It aims to implement as much of the [OpenAPI][open-api] specification as possible - nested schemas, named models,
|
||||
response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code
|
||||
generation tools like `swagger-codegen`.
|
||||
|
||||
It also tries to stay current with the maturing schema generation mechanism provided by DRF.
|
||||
This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`:
|
||||
|
||||
![Screenshot - DRF OpenAPI][image-drf-openapi]
|
||||
|
||||
---
|
||||
|
||||
#### DRF Docs
|
||||
|
||||
[DRF Docs][drfdocs-repo] allows you to document Web APIs made with Django REST Framework and it is authored by Emmanouil Konstantinidis. It's made to work out of the box and its setup should not take more than a couple of minutes. Complete documentation can be found on the [website][drfdocs-website] while there is also a [demo][drfdocs-demo] available for people to see what it looks like. **Live API Endpoints** allow you to utilize the endpoints from within the documentation in a neat way.
|
||||
|
||||
Features include customizing the template with your branding, settings for hiding the docs depending on the environment and more.
|
||||
|
||||
Both this package and Django REST Swagger are fully documented, well supported, and come highly recommended.
|
||||
|
||||
![Screenshot - DRF docs][image-drf-docs]
|
||||
![Screenshot - drf-yasg][image-drf-yasg]
|
||||
|
||||
---
|
||||
|
||||
|
@ -173,7 +148,7 @@ Django REST Swagger supports REST framework versions 2.3 and above.
|
|||
|
||||
Mark is also the author of the [REST Framework Docs][rest-framework-docs] package which offers clean, simple autogenerated documentation for your API but is deprecated and has moved to Django REST Swagger.
|
||||
|
||||
Both this package and DRF docs are fully documented, well supported, and come highly recommended.
|
||||
This package is fully documented, well supported, and comes highly recommended.
|
||||
|
||||
![Screenshot - Django REST Swagger][image-django-rest-swagger]
|
||||
|
||||
|
@ -235,7 +210,7 @@ When working with viewsets, an appropriate suffix is appended to each generated
|
|||
|
||||
The description in the browsable API is generated from the docstring of the view or viewset.
|
||||
|
||||
If the python `markdown` library is installed, then [markdown syntax][markdown] may be used in the docstring, and will be converted to HTML in the browsable API. For example:
|
||||
If the python `Markdown` library is installed, then [markdown syntax][markdown] may be used in the docstring, and will be converted to HTML in the browsable API. For example:
|
||||
|
||||
class AccountListView(views.APIView):
|
||||
"""
|
||||
|
@ -246,7 +221,7 @@ If the python `markdown` library is installed, then [markdown syntax][markdown]
|
|||
[ref]: http://example.com/activating-accounts
|
||||
"""
|
||||
|
||||
Note that when using viewsets the basic docstring is used for all generated views. To provide descriptions for each view, such as for the the list and retrieve views, use docstring sections as described in [Schemas as documentation: Examples][schemas-examples].
|
||||
Note that when using viewsets the basic docstring is used for all generated views. To provide descriptions for each view, such as for the list and retrieve views, use docstring sections as described in [Schemas as documentation: Examples][schemas-examples].
|
||||
|
||||
#### The `OPTIONS` method
|
||||
|
||||
|
@ -254,16 +229,19 @@ REST framework APIs also support programmatically accessible descriptions, using
|
|||
|
||||
When using the generic views, any `OPTIONS` requests will additionally respond with metadata regarding any `POST` or `PUT` actions available, describing which fields are on the serializer.
|
||||
|
||||
You can modify the response behavior to `OPTIONS` requests by overriding the `metadata` view method. For example:
|
||||
You can modify the response behavior to `OPTIONS` requests by overriding the `options` view method and/or by providing a custom Metadata class. For example:
|
||||
|
||||
def metadata(self, request):
|
||||
def options(self, request, *args, **kwargs):
|
||||
"""
|
||||
Don't include the view description in OPTIONS responses.
|
||||
"""
|
||||
data = super(ExampleView, self).metadata(request)
|
||||
meta = self.metadata_class()
|
||||
data = meta.determine_metadata(request, self)
|
||||
data.pop('description')
|
||||
return data
|
||||
|
||||
See [the Metadata docs][metadata-docs] for more details.
|
||||
|
||||
---
|
||||
|
||||
## The hypermedia approach
|
||||
|
@ -274,21 +252,23 @@ In this approach, rather than documenting the available API endpoints up front,
|
|||
|
||||
To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The [REST, Hypermedia & HATEOAS][hypermedia-docs] section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.
|
||||
|
||||
[cite]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
|
||||
[drf-openapi]: https://github.com/limdauto/drf_openapi/
|
||||
[image-drf-openapi]: ../img/drf-openapi.png
|
||||
[drfdocs-repo]: https://github.com/ekonstantinidis/django-rest-framework-docs
|
||||
[drfdocs-website]: http://www.drfdocs.com/
|
||||
[drfdocs-demo]: http://demo.drfdocs.com/
|
||||
[cite]: https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
|
||||
[drf-yasg]: https://github.com/axnsan12/drf-yasg/
|
||||
[image-drf-yasg]: ../img/drf-yasg.png
|
||||
[drfautodocs-repo]: https://github.com/iMakedonsky/drf-autodocs
|
||||
[django-rest-swagger]: https://github.com/marcgibbons/django-rest-swagger
|
||||
[swagger]: https://developers.helloreverb.com/swagger/
|
||||
[swagger]: https://swagger.io/
|
||||
[open-api]: https://openapis.org/
|
||||
[rest-framework-docs]: https://github.com/marcgibbons/django-rest-framework-docs
|
||||
[apiary]: http://apiary.io/
|
||||
[markdown]: http://daringfireball.net/projects/markdown/
|
||||
[apiary]: https://apiary.io/
|
||||
[markdown]: https://daringfireball.net/projects/markdown/syntax
|
||||
[hypermedia-docs]: rest-hypermedia-hateoas.md
|
||||
[image-drf-docs]: ../img/drfdocs.png
|
||||
[image-django-rest-swagger]: ../img/django-rest-swagger.png
|
||||
[image-apiary]: ../img/apiary.png
|
||||
[image-self-describing-api]: ../img/self-describing.png
|
||||
[schemas-examples]: ../api-guide/schemas/#example
|
||||
[metadata-docs]: ../api-guide/metadata/
|
||||
|
||||
[schemas-examples]: ../api-guide/schemas/#examples
|
||||
[swagger-ui]: https://swagger.io/tools/swagger-ui/
|
||||
[redoc]: https://github.com/Rebilly/ReDoc
|
||||
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
# HTML & Forms
|
||||
|
||||
REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.
|
||||
REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can be used as HTML forms and rendered in templates.
|
||||
|
||||
## Rendering HTML
|
||||
|
||||
In order to return HTML responses you'll need to either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`.
|
||||
In order to return HTML responses you'll need to use either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`.
|
||||
|
||||
The `TemplateHTMLRenderer` class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.
|
||||
|
||||
|
|
|
@ -43,7 +43,7 @@ REST framework includes these built-in translations both for standard exception
|
|||
|
||||
Note that the translations only apply to the error strings themselves. The format of error messages, and the keys of field names will remain the same. An example `400 Bad Request` response body might look like this:
|
||||
|
||||
{"detail": {"username": ["Esse campo deve ser unico."]}}
|
||||
{"detail": {"username": ["Esse campo deve ser único."]}}
|
||||
|
||||
If you want to use different string for parts of the response such as `detail` and `non_field_errors` then you can modify this behavior by using a [custom exception handler][custom-exception-handler].
|
||||
|
||||
|
@ -102,7 +102,7 @@ You can find more information on how the language preference is determined in th
|
|||
|
||||
For API clients the most appropriate of these will typically be to use the `Accept-Language` header; Sessions and cookies will not be available unless using session authentication, and generally better practice to prefer an `Accept-Language` header for API clients rather than using language URL prefixes.
|
||||
|
||||
[cite]: http://youtu.be/Wa0VfS2q94Y
|
||||
[cite]: https://youtu.be/Wa0VfS2q94Y
|
||||
[django-translation]: https://docs.djangoproject.com/en/1.7/topics/i18n/translation
|
||||
[custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling
|
||||
[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/
|
||||
|
@ -110,4 +110,3 @@ For API clients the most appropriate of these will typically be to use the `Acce
|
|||
[django-language-preference]: https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#how-django-discovers-language-preference
|
||||
[django-locale-paths]: https://docs.djangoproject.com/en/1.7/ref/settings/#std:setting-LOCALE_PATHS
|
||||
[django-locale-name]: https://docs.djangoproject.com/en/1.7/topics/i18n/#term-locale-name
|
||||
[contributing]: ../../CONTRIBUTING.md
|
||||
|
|
|
@ -1,98 +0,0 @@
|
|||
# Django REST framework 2.0
|
||||
|
||||
> Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result.
|
||||
>
|
||||
> — [Roy Fielding][cite]
|
||||
|
||||
---
|
||||
|
||||
**Announcement:** REST framework 2 released - Tue 30th Oct 2012
|
||||
|
||||
---
|
||||
|
||||
REST framework 2 is an almost complete reworking of the original framework, which comprehensively addresses some of the original design issues.
|
||||
|
||||
Because the latest version should be considered a re-release, rather than an incremental improvement, we've skipped a version, and called this release Django REST framework 2.0.
|
||||
|
||||
This article is intended to give you a flavor of what REST framework 2 is, and why you might want to give it a try.
|
||||
|
||||
## User feedback
|
||||
|
||||
Before we get cracking, let's start with the hard sell, with a few bits of feedback from some early adopters…
|
||||
|
||||
"Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - [Kit La Touche][quote1]
|
||||
|
||||
"Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - [Ian Strachan][quote2]
|
||||
|
||||
"I switched to the 2.0 branch and I don't regret it - fully refactored my code in another ½ day and it's *much* more to my tastes" - [Bruno Desthuilliers][quote3]
|
||||
|
||||
Sounds good, right? Let's get into some details...
|
||||
|
||||
## Serialization
|
||||
|
||||
REST framework 2 includes a totally re-worked serialization engine, that was initially intended as a replacement for Django's existing inflexible fixture serialization, and which meets the following design goals:
|
||||
|
||||
* A declarative serialization API, that mirrors Django's `Forms`/`ModelForms` API.
|
||||
* Structural concerns are decoupled from encoding concerns.
|
||||
* Able to support rendering and parsing to many formats, including both machine-readable representations and HTML forms.
|
||||
* Validation that can be mapped to obvious and comprehensive error responses.
|
||||
* Serializers that support both nested, flat, and partially-nested representations.
|
||||
* Relationships that can be expressed as primary keys, hyperlinks, slug fields, and other custom representations.
|
||||
|
||||
Mapping between the internal state of the system and external representations of that state is the core concern of building Web APIs. Designing serializers that allow the developer to do so in a flexible and obvious way is a deceptively difficult design task, and with the new serialization API we think we've pretty much nailed it.
|
||||
|
||||
## Generic views
|
||||
|
||||
When REST framework was initially released at the start of 2011, the current Django release was version 1.2. REST framework included a backport of Django 1.3's upcoming `View` class, but it didn't take full advantage of the generic view implementations.
|
||||
|
||||
With the new release the generic views in REST framework now tie in with Django's generic views. The end result is that framework is clean, lightweight and easy to use.
|
||||
|
||||
## Requests, Responses & Views
|
||||
|
||||
REST framework 2 includes `Request` and `Response` classes, than are used in place of Django's existing `HttpRequest` and `HttpResponse` classes. Doing so allows logic such as parsing the incoming request or rendering the outgoing response to be supported transparently by the framework.
|
||||
|
||||
The `Request`/`Response` approach leads to a much cleaner API, less logic in the view itself, and a simple, obvious request-response cycle.
|
||||
|
||||
REST framework 2 also allows you to work with both function-based and class-based views. For simple API views all you need is a single `@api_view` decorator, and you're good to go.
|
||||
|
||||
|
||||
## API Design
|
||||
|
||||
Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independently of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions.
|
||||
|
||||
## The Browsable API
|
||||
|
||||
Django REST framework's most unique feature is the way it is able to serve up both machine-readable representations, and a fully browsable HTML representation to the same endpoints.
|
||||
|
||||
Browsable Web APIs are easier to work with, visualize and debug, and generally makes it easier and more frictionless to inspect and work with.
|
||||
|
||||
With REST framework 2, the browsable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with.
|
||||
|
||||
There are also some functionality improvements - actions such as as `POST` and `DELETE` will only display if the user has the appropriate permissions.
|
||||
|
||||
![Browsable API][image]
|
||||
|
||||
**Image above**: An example of the browsable API in REST framework 2
|
||||
|
||||
## Documentation
|
||||
|
||||
As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling.
|
||||
|
||||
We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great.
|
||||
|
||||
## Summary
|
||||
|
||||
In short, we've engineered the hell outta this thing, and we're incredibly proud of the result.
|
||||
|
||||
If you're interested please take a browse around the documentation. [The tutorial][tut] is a great place to get started.
|
||||
|
||||
There's also a [live sandbox version of the tutorial API][sandbox] available for testing.
|
||||
|
||||
[cite]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-724
|
||||
[quote1]: https://twitter.com/kobutsu/status/261689665952833536
|
||||
[quote2]: https://groups.google.com/d/msg/django-rest-framework/heRGHzG6BWQ/ooVURgpwVC0J
|
||||
[quote3]: https://groups.google.com/d/msg/django-rest-framework/flsXbvYqRoY/9lSyntOf5cUJ
|
||||
[image]: ../img/quickstart.png
|
||||
[readthedocs]: https://readthedocs.org/
|
||||
[tut]: ../tutorial/1-serialization.md
|
||||
[sandbox]: http://restframework.herokuapp.com/
|
|
@ -34,15 +34,14 @@ REST framework also includes [serialization] and [parser]/[renderer] components
|
|||
|
||||
What REST framework doesn't do is give you machine readable hypermedia formats such as [HAL][hal], [Collection+JSON][collection], [JSON API][json-api] or HTML [microformats] by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.
|
||||
|
||||
[cite]: http://vimeo.com/channels/restfest/page:2
|
||||
[dissertation]: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
|
||||
[hypertext-driven]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
|
||||
[cite]: https://vimeo.com/channels/restfest/page:2
|
||||
[dissertation]: https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
|
||||
[hypertext-driven]: https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
|
||||
[restful-web-apis]: http://restfulwebapis.org/
|
||||
[building-hypermedia-apis]: http://www.amazon.com/Building-Hypermedia-APIs-HTML5-Node/dp/1449306578
|
||||
[building-hypermedia-apis]: https://www.amazon.com/Building-Hypermedia-APIs-HTML5-Node/dp/1449306578
|
||||
[designing-hypermedia-apis]: http://designinghypermediaapis.com/
|
||||
[restisover]: http://blog.steveklabnik.com/posts/2012-02-23-rest-is-over
|
||||
[readinglist]: http://blog.steveklabnik.com/posts/2012-02-27-hypermedia-api-reading-list
|
||||
[maturitymodel]: http://martinfowler.com/articles/richardsonMaturityModel.html
|
||||
[maturitymodel]: https://martinfowler.com/articles/richardsonMaturityModel.html
|
||||
|
||||
[hal]: http://stateless.co/hal_specification.html
|
||||
[collection]: http://www.amundsen.com/media-types/collection/
|
||||
|
|
|
@ -15,19 +15,19 @@ Nested data structures are easy enough to work with if they're read-only - simpl
|
|||
class ToDoItemSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = ToDoItem
|
||||
fields = ('text', 'is_completed')
|
||||
fields = ['text', 'is_completed']
|
||||
|
||||
class ToDoListSerializer(serializers.ModelSerializer):
|
||||
items = ToDoItemSerializer(many=True, read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = ToDoList
|
||||
fields = ('title', 'items')
|
||||
fields = ['title', 'items']
|
||||
|
||||
Some example output from our serializer.
|
||||
|
||||
{
|
||||
'title': 'Leaving party preperations',
|
||||
'title': 'Leaving party preparations',
|
||||
'items': [
|
||||
{'text': 'Compile playlist', 'is_completed': True},
|
||||
{'text': 'Send invites', 'is_completed': False},
|
||||
|
|
|
@ -8,24 +8,24 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o
|
|||
|
||||
---
|
||||
|
||||
**Note**: The code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox].
|
||||
**Note**: The code for this tutorial is available in the [encode/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox].
|
||||
|
||||
---
|
||||
|
||||
## Setting up a new environment
|
||||
|
||||
Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.
|
||||
Before we do anything else we'll create a new virtual environment, using [venv]. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.
|
||||
|
||||
virtualenv env
|
||||
python3 -m venv env
|
||||
source env/bin/activate
|
||||
|
||||
Now that we're inside a virtualenv environment, we can install our package requirements.
|
||||
Now that we're inside a virtual environment, we can install our package requirements.
|
||||
|
||||
pip install django
|
||||
pip install djangorestframework
|
||||
pip install pygments # We'll be using this for the code highlighting
|
||||
|
||||
**Note:** To exit the virtualenv environment at any time, just type `deactivate`. For more information see the [virtualenv documentation][virtualenv].
|
||||
**Note:** To exit the virtual environment at any time, just type `deactivate`. For more information see the [venv documentation][venv].
|
||||
|
||||
## Getting started
|
||||
|
||||
|
@ -33,7 +33,7 @@ Okay, we're ready to get coding.
|
|||
To get started, let's create a new project to work with.
|
||||
|
||||
cd ~
|
||||
django-admin.py startproject tutorial
|
||||
django-admin startproject tutorial
|
||||
cd tutorial
|
||||
|
||||
Once that's done we can create an app that we'll use to create a simple Web API.
|
||||
|
@ -42,11 +42,11 @@ Once that's done we can create an app that we'll use to create a simple Web API.
|
|||
|
||||
We'll need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. Let's edit the `tutorial/settings.py` file:
|
||||
|
||||
INSTALLED_APPS = (
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
'snippets.apps.SnippetsConfig',
|
||||
)
|
||||
]
|
||||
|
||||
Okay, we're ready to roll.
|
||||
|
||||
|
@ -60,7 +60,7 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni
|
|||
|
||||
LEXERS = [item for item in get_all_lexers() if item[1]]
|
||||
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
|
||||
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
|
||||
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
|
||||
|
||||
|
||||
class Snippet(models.Model):
|
||||
|
@ -72,7 +72,7 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni
|
|||
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
|
||||
|
||||
class Meta:
|
||||
ordering = ('created',)
|
||||
ordering = ['created']
|
||||
|
||||
We'll also need to create an initial migration for our snippet model, and sync the database for the first time.
|
||||
|
||||
|
@ -137,26 +137,26 @@ Okay, once we've got a few imports out of the way, let's create a couple of code
|
|||
snippet = Snippet(code='foo = "bar"\n')
|
||||
snippet.save()
|
||||
|
||||
snippet = Snippet(code='print "hello, world"\n')
|
||||
snippet = Snippet(code='print("hello, world")\n')
|
||||
snippet.save()
|
||||
|
||||
We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.
|
||||
|
||||
serializer = SnippetSerializer(snippet)
|
||||
serializer.data
|
||||
# {'id': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
|
||||
# {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
|
||||
|
||||
At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`.
|
||||
|
||||
content = JSONRenderer().render(serializer.data)
|
||||
content
|
||||
# '{"id": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
|
||||
# b'{"id": 2, "title": "", "code": "print(\\"hello, world\\")\\n", "linenos": false, "language": "python", "style": "friendly"}'
|
||||
|
||||
Deserialization is similar. First we parse a stream into Python native datatypes...
|
||||
|
||||
from django.utils.six import BytesIO
|
||||
import io
|
||||
|
||||
stream = BytesIO(content)
|
||||
stream = io.BytesIO(content)
|
||||
data = JSONParser().parse(stream)
|
||||
|
||||
...then we restore those native datatypes into a fully populated object instance.
|
||||
|
@ -165,7 +165,7 @@ Deserialization is similar. First we parse a stream into Python native datatype
|
|||
serializer.is_valid()
|
||||
# True
|
||||
serializer.validated_data
|
||||
# OrderedDict([('title', ''), ('code', 'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
|
||||
# OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
|
||||
serializer.save()
|
||||
# <Snippet: Snippet object>
|
||||
|
||||
|
@ -175,7 +175,7 @@ We can also serialize querysets instead of model instances. To do so we simply
|
|||
|
||||
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
|
||||
serializer.data
|
||||
# [OrderedDict([('id', 1), ('title', u''), ('code', u'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', u''), ('code', u'print "hello, world"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]
|
||||
# [OrderedDict([('id', 1), ('title', ''), ('code', 'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', ''), ('code', 'print("hello, world")'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]
|
||||
|
||||
## Using ModelSerializers
|
||||
|
||||
|
@ -189,7 +189,7 @@ Open the file `snippets/serializers.py` again, and replace the `SnippetSerialize
|
|||
class SnippetSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Snippet
|
||||
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
|
||||
fields = ['id', 'title', 'code', 'linenos', 'language', 'style']
|
||||
|
||||
One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with `python manage.py shell`, then try the following:
|
||||
|
||||
|
@ -218,7 +218,6 @@ Edit the `snippets/views.py` file, and add the following.
|
|||
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from rest_framework.renderers import JSONRenderer
|
||||
from rest_framework.parsers import JSONParser
|
||||
from snippets.models import Snippet
|
||||
from snippets.serializers import SnippetSerializer
|
||||
|
@ -275,20 +274,20 @@ We'll also need a view which corresponds to an individual snippet, and can be us
|
|||
|
||||
Finally we need to wire these views up. Create the `snippets/urls.py` file:
|
||||
|
||||
from django.conf.urls import url
|
||||
from django.urls import path
|
||||
from snippets import views
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^snippets/$', views.snippet_list),
|
||||
url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
|
||||
path('snippets/', views.snippet_list),
|
||||
path('snippets/<int:pk>/', views.snippet_detail),
|
||||
]
|
||||
|
||||
We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs.
|
||||
|
||||
from django.conf.urls import url, include
|
||||
from django.urls import path, include
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^', include('snippets.urls')),
|
||||
path('', include('snippets.urls')),
|
||||
]
|
||||
|
||||
It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.
|
||||
|
@ -338,7 +337,7 @@ Finally, we can get a list of all of the snippets:
|
|||
{
|
||||
"id": 2,
|
||||
"title": "",
|
||||
"code": "print \"hello, world\"\n",
|
||||
"code": "print(\"hello, world\")\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
|
@ -354,7 +353,7 @@ Or we can get a particular snippet by referencing its id:
|
|||
{
|
||||
"id": 2,
|
||||
"title": "",
|
||||
"code": "print \"hello, world\"\n",
|
||||
"code": "print(\"hello, world\")\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
|
@ -372,8 +371,8 @@ We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].
|
|||
|
||||
[quickstart]: quickstart.md
|
||||
[repo]: https://github.com/encode/rest-framework-tutorial
|
||||
[sandbox]: http://restframework.herokuapp.com/
|
||||
[virtualenv]: http://www.virtualenv.org/en/latest/index.html
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
[venv]: https://docs.python.org/3/library/venv.html
|
||||
[tut-2]: 2-requests-and-responses.md
|
||||
[httpie]: https://github.com/jakubroztocil/httpie#installation
|
||||
[curl]: http://curl.haxx.se
|
||||
[curl]: https://curl.haxx.se/
|
||||
|
|
|
@ -108,13 +108,13 @@ and
|
|||
|
||||
Now update the `snippets/urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs.
|
||||
|
||||
from django.conf.urls import url
|
||||
from django.urls import path
|
||||
from rest_framework.urlpatterns import format_suffix_patterns
|
||||
from snippets import views
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^snippets/$', views.snippet_list),
|
||||
url(r'^snippets/(?P<pk>[0-9]+)$', views.snippet_detail),
|
||||
path('snippets/', views.snippet_list),
|
||||
path('snippets/<int:pk>', views.snippet_detail),
|
||||
]
|
||||
|
||||
urlpatterns = format_suffix_patterns(urlpatterns)
|
||||
|
@ -143,7 +143,7 @@ We can get a list of all of the snippets, as before.
|
|||
{
|
||||
"id": 2,
|
||||
"title": "",
|
||||
"code": "print \"hello, world\"\n",
|
||||
"code": "print(\"hello, world\")\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
|
@ -163,24 +163,24 @@ Or by appending a format suffix:
|
|||
Similarly, we can control the format of the request that we send, using the `Content-Type` header.
|
||||
|
||||
# POST using form data
|
||||
http --form POST http://127.0.0.1:8000/snippets/ code="print 123"
|
||||
http --form POST http://127.0.0.1:8000/snippets/ code="print(123)"
|
||||
|
||||
{
|
||||
"id": 3,
|
||||
"title": "",
|
||||
"code": "print 123",
|
||||
"code": "print(123)",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
}
|
||||
|
||||
# POST using JSON
|
||||
http --json POST http://127.0.0.1:8000/snippets/ code="print 456"
|
||||
http --json POST http://127.0.0.1:8000/snippets/ code="print(456)"
|
||||
|
||||
{
|
||||
"id": 4,
|
||||
"title": "",
|
||||
"code": "print 456",
|
||||
"code": "print(456)",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
|
|
|
@ -64,13 +64,13 @@ That's looking good. Again, it's still pretty similar to the function based vie
|
|||
|
||||
We'll also need to refactor our `snippets/urls.py` slightly now that we're using class-based views.
|
||||
|
||||
from django.conf.urls import url
|
||||
from django.urls import path
|
||||
from rest_framework.urlpatterns import format_suffix_patterns
|
||||
from snippets import views
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^snippets/$', views.SnippetList.as_view()),
|
||||
url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
|
||||
path('snippets/', views.SnippetList.as_view()),
|
||||
path('snippets/<int:pk>/', views.SnippetDetail.as_view()),
|
||||
]
|
||||
|
||||
urlpatterns = format_suffix_patterns(urlpatterns)
|
||||
|
@ -146,5 +146,5 @@ Wow, that's pretty concise. We've gotten a huge amount for free, and our code l
|
|||
|
||||
Next we'll move onto [part 4 of the tutorial][tut-4], where we'll take a look at how we can deal with authentication and permissions for our API.
|
||||
|
||||
[dry]: http://en.wikipedia.org/wiki/Don't_repeat_yourself
|
||||
[dry]: https://en.wikipedia.org/wiki/Don't_repeat_yourself
|
||||
[tut-4]: 4-authentication-and-permissions.md
|
||||
|
|
|
@ -33,8 +33,8 @@ And now we can add a `.save()` method to our model class:
|
|||
representation of the code snippet.
|
||||
"""
|
||||
lexer = get_lexer_by_name(self.language)
|
||||
linenos = self.linenos and 'table' or False
|
||||
options = self.title and {'title': self.title} or {}
|
||||
linenos = 'table' if self.linenos else False
|
||||
options = {'title': self.title} if self.title else {}
|
||||
formatter = HtmlFormatter(style=self.style, linenos=linenos,
|
||||
full=True, **options)
|
||||
self.highlighted = highlight(self.code, lexer, formatter)
|
||||
|
@ -63,7 +63,7 @@ Now that we've got some users to work with, we'd better add representations of t
|
|||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ('id', 'username', 'snippets')
|
||||
fields = ['id', 'username', 'snippets']
|
||||
|
||||
Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it.
|
||||
|
||||
|
@ -85,10 +85,10 @@ Make sure to also import the `UserSerializer` class
|
|||
|
||||
from snippets.serializers import UserSerializer
|
||||
|
||||
Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `urls.py`.
|
||||
Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `snippets/urls.py`.
|
||||
|
||||
url(r'^users/$', views.UserList.as_view()),
|
||||
url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
|
||||
path('users/', views.UserList.as_view()),
|
||||
path('users/<int:pk>/', views.UserDetail.as_view()),
|
||||
|
||||
## Associating Snippets with Users
|
||||
|
||||
|
@ -127,7 +127,7 @@ First add the following import in the views module
|
|||
|
||||
Then, add the following property to **both** the `SnippetList` and `SnippetDetail` view classes.
|
||||
|
||||
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
|
||||
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
|
||||
|
||||
## Adding login to the Browsable API
|
||||
|
||||
|
@ -142,10 +142,10 @@ Add the following import at the top of the file:
|
|||
And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
|
||||
|
||||
urlpatterns += [
|
||||
url(r'^api-auth/', include('rest_framework.urls'),
|
||||
path('api-auth/', include('rest_framework.urls')),
|
||||
]
|
||||
|
||||
The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use.
|
||||
The `'api-auth/'` part of pattern can actually be whatever URL you want to use.
|
||||
|
||||
Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.
|
||||
|
||||
|
@ -178,8 +178,8 @@ In the snippets app, create a new file, `permissions.py`
|
|||
|
||||
Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` view class:
|
||||
|
||||
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
|
||||
IsOwnerOrReadOnly,)
|
||||
permission_classes = [permissions.IsAuthenticatedOrReadOnly,
|
||||
IsOwnerOrReadOnly]
|
||||
|
||||
Make sure to also import the `IsOwnerOrReadOnly` class.
|
||||
|
||||
|
@ -197,7 +197,7 @@ If we're interacting with the API programmatically we need to explicitly provide
|
|||
|
||||
If we try to create a snippet without authenticating, we'll get an error:
|
||||
|
||||
http POST http://127.0.0.1:8000/snippets/ code="print 123"
|
||||
http POST http://127.0.0.1:8000/snippets/ code="print(123)"
|
||||
|
||||
{
|
||||
"detail": "Authentication credentials were not provided."
|
||||
|
@ -205,13 +205,13 @@ If we try to create a snippet without authenticating, we'll get an error:
|
|||
|
||||
We can make a successful request by including the username and password of one of the users we created earlier.
|
||||
|
||||
http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print 789"
|
||||
http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)"
|
||||
|
||||
{
|
||||
"id": 1,
|
||||
"owner": "admin",
|
||||
"title": "foo",
|
||||
"code": "print 789",
|
||||
"code": "print(789)",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
|
|