Merge branch 'master' into remove-trailing-zeros-on-decimal
2
.github/FUNDING.yml
vendored
Normal file
|
@ -0,0 +1,2 @@
|
|||
github: encode
|
||||
custom: https://fund.django-rest-framework.org/topics/funding/
|
10
.github/ISSUE_TEMPLATE/1-issue.md
vendored
Normal file
|
@ -0,0 +1,10 @@
|
|||
---
|
||||
name: Issue
|
||||
about: Please only raise an issue if you've been advised to do so after discussion. Thanks! 🙏
|
||||
---
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Raised initially as discussion #...
|
||||
- [ ] 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.
|
6
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Discussions
|
||||
url: https://github.com/encode/django-rest-framework/discussions
|
||||
about: >
|
||||
The "Discussions" forum is where you want to start. 💖
|
22
.github/stale.yml
vendored
Normal file
|
@ -0,0 +1,22 @@
|
|||
# Documentation: https://github.com/probot/stale
|
||||
|
||||
# Number of days of inactivity before an issue becomes stale
|
||||
daysUntilStale: 60
|
||||
|
||||
# Number of days of inactivity before a stale issue is closed
|
||||
daysUntilClose: 7
|
||||
|
||||
# Comment to post when marking an issue as stale. Set to `false` to disable
|
||||
markComment: >
|
||||
This issue has been automatically marked as stale because it has not had
|
||||
recent activity. It will be closed if no further activity occurs. Thank you
|
||||
for your contributions.
|
||||
|
||||
# Comment to post when closing a stale issue. Set to `false` to disable
|
||||
closeComment: false
|
||||
|
||||
# Limit the number of actions per hour, from 1-30. Default is 30
|
||||
limitPerRun: 1
|
||||
|
||||
# Label to use when marking as stale
|
||||
staleLabel: stale
|
51
.github/workflows/main.yml
vendored
Normal file
|
@ -0,0 +1,51 @@
|
|||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
tests:
|
||||
name: Python ${{ matrix.python-version }}
|
||||
runs-on: ubuntu-20.04
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
python-version:
|
||||
- '3.6'
|
||||
- '3.7'
|
||||
- '3.8'
|
||||
- '3.9'
|
||||
- '3.10'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions/setup-python@v3
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: 'pip'
|
||||
cache-dependency-path: 'requirements/*.txt'
|
||||
|
||||
- name: Upgrade packaging tools
|
||||
run: python -m pip install --upgrade pip setuptools virtualenv wheel
|
||||
|
||||
- name: Install dependencies
|
||||
run: python -m pip install --upgrade codecov tox tox-py
|
||||
|
||||
- name: Run tox targets for ${{ matrix.python-version }}
|
||||
run: tox --py current
|
||||
|
||||
- name: Run extra tox targets
|
||||
if: ${{ matrix.python-version == '3.9' }}
|
||||
run: |
|
||||
python setup.py bdist_wheel
|
||||
rm -r djangorestframework.egg-info # see #6139
|
||||
tox -e base,dist,docs
|
||||
tox -e dist --installpkg ./dist/djangorestframework-*.whl
|
||||
|
||||
- name: Upload coverage
|
||||
run: |
|
||||
codecov -e TOXENV,DJANGO
|
24
.github/workflows/pre-commit.yml
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
name: pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-20.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: 3.9
|
||||
|
||||
- uses: pre-commit/action@v2.0.0
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
6
.gitignore
vendored
|
@ -2,6 +2,8 @@
|
|||
*.db
|
||||
*~
|
||||
.*
|
||||
*.py.bak
|
||||
|
||||
|
||||
/site/
|
||||
/htmlcov/
|
||||
|
@ -13,6 +15,6 @@
|
|||
MANIFEST
|
||||
coverage.*
|
||||
|
||||
!.github
|
||||
!.gitignore
|
||||
!.travis.yml
|
||||
!.isort.cfg
|
||||
!.pre-commit-config.yaml
|
||||
|
|
20
.pre-commit-config.yaml
Normal file
|
@ -0,0 +1,20 @@
|
|||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v3.4.0
|
||||
hooks:
|
||||
- id: check-added-large-files
|
||||
- id: check-case-conflict
|
||||
- id: check-json
|
||||
- id: check-merge-conflict
|
||||
- id: check-symlinks
|
||||
- id: check-toml
|
||||
- repo: https://github.com/pycqa/isort
|
||||
rev: 5.8.0
|
||||
hooks:
|
||||
- id: isort
|
||||
- repo: https://github.com/PyCQA/flake8
|
||||
rev: 3.9.0
|
||||
hooks:
|
||||
- id: flake8
|
||||
additional_dependencies:
|
||||
- flake8-tidy-imports
|
54
.travis.yml
|
@ -1,54 +0,0 @@
|
|||
language: python
|
||||
cache: pip
|
||||
dist: xenial
|
||||
matrix:
|
||||
fast_finish: true
|
||||
include:
|
||||
- { python: "2.7", env: DJANGO=1.11 }
|
||||
|
||||
- { python: "3.4", env: DJANGO=1.11 }
|
||||
- { python: "3.4", env: DJANGO=2.0 }
|
||||
|
||||
- { 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: "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.7", env: TOXENV=base }
|
||||
- { python: "2.7", env: TOXENV=lint }
|
||||
- { python: "2.7", env: TOXENV=docs }
|
||||
|
||||
- python: "3.7"
|
||||
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-venv tox-travis
|
||||
|
||||
script:
|
||||
- tox
|
||||
|
||||
after_success:
|
||||
- pip install codecov
|
||||
- codecov -e TOXENV,DJANGO
|
||||
|
||||
notifications:
|
||||
email: false
|
9
.tx/config
Normal file
|
@ -0,0 +1,9 @@
|
|||
[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
|
206
CONTRIBUTING.md
|
@ -1,207 +1,7 @@
|
|||
# Contributing to REST framework
|
||||
|
||||
> The world can only really be changed one piece at a time. The art is picking that piece.
|
||||
>
|
||||
> — [Tim Berners-Lee][cite]
|
||||
At this point in it's lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes.
|
||||
|
||||
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
|
||||
Apart from minor documentation changes, the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Please only raise an issue or pull request if you've been recommended to do so after discussion.
|
||||
|
||||
## Community
|
||||
|
||||
The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
|
||||
|
||||
If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.
|
||||
|
||||
Other really great ways you can help move the community forward include helping to answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag.
|
||||
|
||||
When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.
|
||||
|
||||
## Code of conduct
|
||||
|
||||
Please keep the tone polite & professional. For some users a discussion on the REST framework mailing list or ticket tracker may be their first engagement with the open source community. First impressions count, so let's try to make everyone feel welcome.
|
||||
|
||||
Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations. (e.g. 'Hey folks,')
|
||||
|
||||
The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines for participating in community forums.
|
||||
|
||||
# Issues
|
||||
|
||||
It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the [discussion group][google-group]. Feature requests, bug reports and other issues should be raised on the GitHub [issue tracker][issues].
|
||||
|
||||
Some tips on good issue reporting:
|
||||
|
||||
* When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
|
||||
* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
|
||||
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
|
||||
* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bug fixes, and great documentation.
|
||||
* Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.
|
||||
|
||||
## Triaging issues
|
||||
|
||||
Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to:
|
||||
|
||||
* Read through the ticket - does it make sense, is it missing any context that would help explain it better?
|
||||
* Is the ticket reported in the correct place, would it be better suited as a discussion on the discussion group?
|
||||
* If the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request?
|
||||
* If the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package?
|
||||
* If a ticket hasn't had much activity and it addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again.
|
||||
|
||||
# Development
|
||||
|
||||
To start developing on Django REST framework, clone the repo:
|
||||
|
||||
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.
|
||||
|
||||
## Testing
|
||||
|
||||
To run the tests, clone the repository, and then:
|
||||
|
||||
# Setup the virtual environment
|
||||
virtualenv env
|
||||
source env/bin/activate
|
||||
pip install django
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Run the tests
|
||||
./runtests.py
|
||||
|
||||
### Test options
|
||||
|
||||
Run using a more concise output style.
|
||||
|
||||
./runtests.py -q
|
||||
|
||||
Run the tests using a more concise output style, no coverage, no flake8.
|
||||
|
||||
./runtests.py --fast
|
||||
|
||||
Don't run the flake8 code linting.
|
||||
|
||||
./runtests.py --nolint
|
||||
|
||||
Only run the flake8 code linting, don't run the tests.
|
||||
|
||||
./runtests.py --lintonly
|
||||
|
||||
Run the tests for a given test case.
|
||||
|
||||
./runtests.py MyTestCase
|
||||
|
||||
Run the tests for a given test method.
|
||||
|
||||
./runtests.py MyTestCase.test_this_method
|
||||
|
||||
Shorter form to run the tests for a given test method.
|
||||
|
||||
./runtests.py test_this_method
|
||||
|
||||
Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
|
||||
|
||||
### Running against multiple environments
|
||||
|
||||
You can also use the excellent [tox][tox] testing tool to run the tests against all supported versions of Python and Django. Install `tox` globally, and then simply run:
|
||||
|
||||
tox
|
||||
|
||||
## Pull requests
|
||||
|
||||
It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.
|
||||
|
||||
It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests.
|
||||
|
||||
It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests.
|
||||
|
||||
GitHub's documentation for working on pull requests is [available here][pull-requests].
|
||||
|
||||
Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of 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.
|
||||
|
||||
## Managing compatibility issues
|
||||
|
||||
Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the `compat.py` module, and should provide a single common interface that the rest of the codebase can use.
|
||||
|
||||
# Documentation
|
||||
|
||||
The documentation for REST framework is built from the [Markdown][markdown] source files in [the docs directory][docs].
|
||||
|
||||
There are many great Markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended.
|
||||
|
||||
## Building the documentation
|
||||
|
||||
To build the documentation, install MkDocs with `pip install mkdocs` and then run the following command.
|
||||
|
||||
mkdocs build
|
||||
|
||||
This will build the documentation into the `site` directory.
|
||||
|
||||
You can build the documentation and open a preview in a browser window by using the `serve` command.
|
||||
|
||||
mkdocs serve
|
||||
|
||||
## Language style
|
||||
|
||||
Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.
|
||||
|
||||
Some other tips:
|
||||
|
||||
* Keep paragraphs reasonably short.
|
||||
* Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.
|
||||
|
||||
## Markdown style
|
||||
|
||||
There are a couple of conventions you should follow when working on the documentation.
|
||||
|
||||
##### 1. Headers
|
||||
|
||||
Headers should use the hash style. For example:
|
||||
|
||||
### Some important topic
|
||||
|
||||
The underline style should not be used. **Don't do this:**
|
||||
|
||||
Some important topic
|
||||
====================
|
||||
|
||||
##### 2. Links
|
||||
|
||||
Links should always use the reference style, with the referenced hyperlinks kept at the end of the document.
|
||||
|
||||
Here is a link to [some other thing][other-thing].
|
||||
|
||||
More text...
|
||||
|
||||
[other-thing]: http://example.com/other/thing
|
||||
|
||||
This style helps keep the documentation source consistent and readable.
|
||||
|
||||
If you are hyperlinking to another REST framework document, you should use a relative link, and link to the `.md` suffix. For example:
|
||||
|
||||
[authentication]: ../api-guide/authentication.md
|
||||
|
||||
Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.
|
||||
|
||||
##### 3. Notes
|
||||
|
||||
If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:
|
||||
|
||||
---
|
||||
|
||||
**Note:** A useful documentation note.
|
||||
|
||||
---
|
||||
|
||||
|
||||
[cite]: https://www.w3.org/People/Berners-Lee/FAQ.html
|
||||
[code-of-conduct]: https://www.djangoproject.com/conduct/
|
||||
[google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[so-filter]: https://stackexchange.com/filters/66475/rest-framework
|
||||
[issues]: https://github.com/encode/django-rest-framework/issues?state=open
|
||||
[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]: https://daringfireball.net/projects/markdown/basics
|
||||
[docs]: https://github.com/encode/django-rest-framework/tree/master/docs
|
||||
[mou]: http://mouapp.com/
|
||||
The [Contributing guide in the documentation](https://www.django-rest-framework.org/community/contributing/) gives some more information on our process and code of conduct.
|
||||
|
|
|
@ -1,14 +0,0 @@
|
|||
## Checklist
|
||||
|
||||
- [ ] 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](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.)
|
||||
|
||||
## Steps to reproduce
|
||||
|
||||
## Expected behavior
|
||||
|
||||
## Actual behavior
|
|
@ -1,6 +1,7 @@
|
|||
include README.md
|
||||
include LICENSE.md
|
||||
recursive-include rest_framework/static *.js *.css *.png *.ico *.eot *.svg *.ttf *.woff *.woff2
|
||||
recursive-include tests/ *
|
||||
recursive-include rest_framework/static *.js *.css *.map *.png *.ico *.eot *.svg *.ttf *.woff *.woff2
|
||||
recursive-include rest_framework/templates *.html schema.js
|
||||
recursive-include rest_framework/locale *.mo
|
||||
global-exclude __pycache__
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
*Note*: Before submitting this pull request, please review our [contributing guidelines](https://github.com/encode/django-rest-framework/blob/master/CONTRIBUTING.md#pull-requests).
|
||||
*Note*: Before submitting this pull request, please review our [contributing guidelines](https://www.django-rest-framework.org/community/contributing/#pull-requests).
|
||||
|
||||
## Description
|
||||
|
||||
|
|
90
README.md
|
@ -1,6 +1,6 @@
|
|||
# [Django REST framework][docs]
|
||||
|
||||
[![build-status-image]][travis]
|
||||
[![build-status-image]][build-status]
|
||||
[![coverage-status-image]][codecov]
|
||||
[![pypi-version]][pypi]
|
||||
|
||||
|
@ -21,13 +21,14 @@ The initial aim is to provide a single full-time position on REST framework.
|
|||
|
||||
[![][sentry-img]][sentry-url]
|
||||
[![][stream-img]][stream-url]
|
||||
[![][rollbar-img]][rollbar-url]
|
||||
[![][cadre-img]][cadre-url]
|
||||
[![][kloudless-img]][kloudless-url]
|
||||
[![][release-history-img]][release-history-url]
|
||||
[![][lightson-img]][lightson-url]
|
||||
[![][spacinov-img]][spacinov-url]
|
||||
[![][retool-img]][retool-url]
|
||||
[![][bitio-img]][bitio-url]
|
||||
[![][posthog-img]][posthog-url]
|
||||
[![][cryptapi-img]][cryptapi-url]
|
||||
[![][fezto-img]][fezto-url]
|
||||
|
||||
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Rollbar][rollbar-url], [Cadre][cadre-url], [Kloudless][kloudless-url], [Release History][release-history-url], and [Lights On Software][lightson-url].
|
||||
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Spacinov][spacinov-url], [Retool][retool-url], [bit.io][bitio-url], [PostHog][posthog-url], [CryptAPI][cryptapi-url], and [FEZTO][fezto-url].
|
||||
|
||||
---
|
||||
|
||||
|
@ -53,8 +54,8 @@ There is a live example API for testing purposes, [available here][sandbox].
|
|||
|
||||
# Requirements
|
||||
|
||||
* Python (2.7, 3.4, 3.5, 3.6, 3.7)
|
||||
* Django (1.11, 2.0, 2.1, 2.2)
|
||||
* Python 3.6+
|
||||
* Django 4.1, 4.0, 3.2, 3.1, 3.0
|
||||
|
||||
We **highly recommend** and only officially support the latest patch release of
|
||||
each Python and Django series.
|
||||
|
@ -66,11 +67,12 @@ Install using `pip`...
|
|||
pip install djangorestframework
|
||||
|
||||
Add `'rest_framework'` to your `INSTALLED_APPS` setting.
|
||||
|
||||
INSTALLED_APPS = (
|
||||
...
|
||||
'rest_framework',
|
||||
)
|
||||
```python
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
]
|
||||
```
|
||||
|
||||
# Example
|
||||
|
||||
|
@ -88,15 +90,16 @@ Startup up a new project like so...
|
|||
Now edit the `example/urls.py` module in your project:
|
||||
|
||||
```python
|
||||
from django.conf.urls import url, include
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import serializers, viewsets, routers
|
||||
from django.urls import include, path
|
||||
from rest_framework import routers, serializers, viewsets
|
||||
|
||||
|
||||
# Serializers define the API representation.
|
||||
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ('url', 'username', 'email', 'is_staff')
|
||||
fields = ['url', 'username', 'email', 'is_staff']
|
||||
|
||||
|
||||
# ViewSets define the view behavior.
|
||||
|
@ -109,12 +112,11 @@ class UserViewSet(viewsets.ModelViewSet):
|
|||
router = routers.DefaultRouter()
|
||||
router.register(r'users', UserViewSet)
|
||||
|
||||
|
||||
# Wire up our API using automatic URL routing.
|
||||
# Additionally, we include login URLs for the browsable API.
|
||||
urlpatterns = [
|
||||
url(r'^', include(router.urls)),
|
||||
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
||||
path('', include(router.urls)),
|
||||
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
|
||||
]
|
||||
```
|
||||
|
||||
|
@ -123,16 +125,16 @@ 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,
|
||||
# or allow read-only access for unauthenticated users.
|
||||
'DEFAULT_PERMISSION_CLASSES': [
|
||||
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
|
||||
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
|
||||
]
|
||||
}
|
||||
```
|
||||
|
@ -169,48 +171,44 @@ Or to create a new user:
|
|||
|
||||
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.
|
||||
For questions and support, use the [REST framework discussion group][group], or `#restframework` on libera.chat IRC.
|
||||
|
||||
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**.
|
||||
Please see the [security policy][security-policy].
|
||||
|
||||
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.
|
||||
|
||||
[build-status-image]: https://secure.travis-ci.org/encode/django-rest-framework.svg?branch=master
|
||||
[travis]: https://travis-ci.org/encode/django-rest-framework?branch=master
|
||||
[build-status-image]: https://github.com/encode/django-rest-framework/actions/workflows/main.yml/badge.svg
|
||||
[build-status]: https://github.com/encode/django-rest-framework/actions/workflows/main.yml
|
||||
[coverage-status-image]: https://img.shields.io/codecov/c/github/encode/django-rest-framework/master.svg
|
||||
[codecov]: https://codecov.io/github/encode/django-rest-framework?branch=master
|
||||
[pypi-version]: https://img.shields.io/pypi/v/djangorestframework.svg
|
||||
[pypi]: https://pypi.org/project/djangorestframework/
|
||||
[twitter]: https://twitter.com/_tomchristie
|
||||
[twitter]: https://twitter.com/starletdreaming
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
|
||||
[funding]: https://fund.django-rest-framework.org/topics/funding/
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
|
||||
[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
|
||||
[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
|
||||
[release-history-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/release-history.png
|
||||
[lightson-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/lightson-readme.png
|
||||
[spacinov-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/spacinov-readme.png
|
||||
[retool-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/retool-readme.png
|
||||
[bitio-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/bitio-readme.png
|
||||
[posthog-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/posthog-readme.png
|
||||
[cryptapi-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cryptapi-readme.png
|
||||
[fezto-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/fezto-readme.png
|
||||
|
||||
[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
|
||||
[rollbar-url]: https://rollbar.com/
|
||||
[cadre-url]: https://cadre.com/
|
||||
[load-impact-url]: https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf
|
||||
[kloudless-url]: https://hubs.ly/H0f30Lf0
|
||||
[release-history-url]: https://releasehistory.io
|
||||
[lightson-url]: https://lightsonsoftware.com
|
||||
[stream-url]: https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage
|
||||
[spacinov-url]: https://www.spacinov.com/
|
||||
[retool-url]: https://retool.com/?utm_source=djangorest&utm_medium=sponsorship
|
||||
[bitio-url]: https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship
|
||||
[posthog-url]: https://posthog.com?utm_source=drf&utm_medium=sponsorship&utm_campaign=open-source-sponsorship
|
||||
[cryptapi-url]: https://cryptapi.io
|
||||
[fezto-url]: https://www.fezto.xyz/?utm_source=DjangoRESTFramework
|
||||
|
||||
[oauth1-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth
|
||||
[oauth2-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit
|
||||
|
@ -225,4 +223,4 @@ Send a description of the issue via email to [rest-framework-security@googlegrou
|
|||
[image]: https://www.django-rest-framework.org/img/quickstart.png
|
||||
|
||||
[docs]: https://www.django-rest-framework.org/
|
||||
[security-mail]: mailto:rest-framework-security@googlegroups.com
|
||||
[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
|
||||
|
||||
Security issues are handled under the supervision of the [Django security team](https://www.djangoproject.com/foundation/teams/#security-team).
|
||||
|
||||
**Please report security issues by emailing security@djangoproject.com**.
|
||||
|
||||
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
|
@ -1,4 +1,7 @@
|
|||
source: authentication.py
|
||||
---
|
||||
source:
|
||||
- authentication.py
|
||||
---
|
||||
|
||||
# Authentication
|
||||
|
||||
|
@ -8,9 +11,9 @@ source: authentication.py
|
|||
|
||||
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted.
|
||||
|
||||
REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.
|
||||
REST framework provides several authentication schemes out of the box, and also allows you to implement custom schemes.
|
||||
|
||||
Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.
|
||||
Authentication always runs at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.
|
||||
|
||||
The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class.
|
||||
|
||||
|
@ -20,7 +23,7 @@ The `request.auth` property is used for any additional authentication informatio
|
|||
|
||||
**Note:** Don't forget that **authentication by itself won't allow or disallow an incoming request**, it simply identifies the credentials that the request was made with.
|
||||
|
||||
For information on how to setup the permission polices for your API please see the [permissions documentation][permission].
|
||||
For information on how to set up the permission policies for your API please see the [permissions documentation][permission].
|
||||
|
||||
---
|
||||
|
||||
|
@ -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,25 +55,25 @@ 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 = {
|
||||
'user': unicode(request.user), # `django.contrib.auth.User` instance.
|
||||
'auth': unicode(request.auth), # None
|
||||
'user': str(request.user), # `django.contrib.auth.User` instance.
|
||||
'auth': str(request.auth), # None
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
|
||||
@api_view(['GET'])
|
||||
@authentication_classes((SessionAuthentication, BasicAuthentication))
|
||||
@permission_classes((IsAuthenticated,))
|
||||
@authentication_classes([SessionAuthentication, BasicAuthentication])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def example_view(request, format=None):
|
||||
content = {
|
||||
'user': unicode(request.user), # `django.contrib.auth.User` instance.
|
||||
'auth': unicode(request.auth), # None
|
||||
'user': str(request.user), # `django.contrib.auth.User` instance.
|
||||
'auth': str(request.auth), # None
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
|
@ -117,20 +120,26 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
|
|||
|
||||
## TokenAuthentication
|
||||
|
||||
---
|
||||
|
||||
**Note:** The token authentication provided by Django REST framework is a fairly simple implementation.
|
||||
|
||||
For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the [Django REST Knox][django-rest-knox] third party package.
|
||||
|
||||
---
|
||||
|
||||
This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
|
||||
|
||||
To use the `TokenAuthentication` scheme you'll need to [configure the authentication classes](#setting-the-authentication-scheme) to include `TokenAuthentication`, and additionally include `rest_framework.authtoken` in your `INSTALLED_APPS` setting:
|
||||
|
||||
INSTALLED_APPS = (
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework.authtoken'
|
||||
)
|
||||
]
|
||||
|
||||
---
|
||||
Make sure to run `manage.py migrate` after changing your settings.
|
||||
|
||||
**Note:** Make sure to run `manage.py migrate` after changing your settings. The `rest_framework.authtoken` app provides Django database migrations.
|
||||
|
||||
---
|
||||
The `rest_framework.authtoken` app provides Django database migrations.
|
||||
|
||||
You'll also need to create tokens for your users.
|
||||
|
||||
|
@ -143,7 +152,7 @@ For clients to authenticate, the token key should be included in the `Authorizat
|
|||
|
||||
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
|
||||
|
||||
**Note:** If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable.
|
||||
*If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable.*
|
||||
|
||||
If successfully authenticated, `TokenAuthentication` provides the following credentials.
|
||||
|
||||
|
@ -164,9 +173,9 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
|
|||
|
||||
---
|
||||
|
||||
#### Generating Tokens
|
||||
### Generating Tokens
|
||||
|
||||
##### By using signals
|
||||
#### By using signals
|
||||
|
||||
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
|
||||
|
||||
|
@ -190,13 +199,13 @@ If you've already created some users, you can generate tokens for all existing u
|
|||
for user in User.objects.all():
|
||||
Token.objects.get_or_create(user=user)
|
||||
|
||||
##### By exposing an api endpoint
|
||||
#### By exposing an api endpoint
|
||||
|
||||
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
|
||||
|
||||
from rest_framework.authtoken import views
|
||||
urlpatterns += [
|
||||
url(r'^api-token-auth/', views.obtain_auth_token)
|
||||
path('api-token-auth/', views.obtain_auth_token)
|
||||
]
|
||||
|
||||
Note that the URL part of the pattern can be whatever you want to use.
|
||||
|
@ -207,7 +216,7 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
|
|||
|
||||
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.
|
||||
|
||||
By default there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
|
||||
By default, there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
|
||||
and include them using the `throttle_classes` attribute.
|
||||
|
||||
If you need a customized version of the `obtain_auth_token` view, you can do so by subclassing the `ObtainAuthToken` view class, and using that in your url conf instead.
|
||||
|
@ -235,19 +244,19 @@ For example, you may return additional user information beyond the `token` value
|
|||
And in your `urls.py`:
|
||||
|
||||
urlpatterns += [
|
||||
url(r'^api-token-auth/', CustomAuthToken.as_view())
|
||||
path('api-token-auth/', CustomAuthToken.as_view())
|
||||
]
|
||||
|
||||
|
||||
##### With Django admin
|
||||
#### With Django admin
|
||||
|
||||
It is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
||||
It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
||||
|
||||
`your_app/admin.py`:
|
||||
|
||||
from rest_framework.authtoken.admin import TokenAdmin
|
||||
|
||||
TokenAdmin.raw_id_fields = ('user',)
|
||||
TokenAdmin.raw_id_fields = ['user']
|
||||
|
||||
|
||||
#### Using Django manage.py command
|
||||
|
@ -276,11 +285,11 @@ If successfully authenticated, `SessionAuthentication` provides the following cr
|
|||
|
||||
Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response.
|
||||
|
||||
If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
|
||||
If you're using an AJAX-style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
|
||||
|
||||
**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
|
||||
|
||||
CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.
|
||||
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behavior is not suitable for login views, which should always have CSRF validation applied.
|
||||
|
||||
|
||||
## RemoteUserAuthentication
|
||||
|
@ -290,7 +299,7 @@ environment variable.
|
|||
|
||||
To use it, you must have `django.contrib.auth.backends.RemoteUserBackend` (or a subclass) in your
|
||||
`AUTHENTICATION_BACKENDS` setting. By default, `RemoteUserBackend` creates `User` objects for usernames that don't
|
||||
already exist. To change this and other behaviour, consult the
|
||||
already exist. To change this and other behavior, consult the
|
||||
[Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/).
|
||||
|
||||
If successfully authenticated, `RemoteUserAuthentication` provides the following credentials:
|
||||
|
@ -298,10 +307,10 @@ If successfully authenticated, `RemoteUserAuthentication` provides the following
|
|||
* `request.user` will be a Django `User` instance.
|
||||
* `request.auth` will be `None`.
|
||||
|
||||
Consult your web server's documentation for information about configuring an authentication method, e.g.:
|
||||
Consult your web server's documentation for information about configuring an authentication method, for example:
|
||||
|
||||
* [Apache Authentication How-To](https://httpd.apache.org/docs/2.4/howto/auth.html)
|
||||
* [NGINX (Restricting Access)](https://www.nginx.com/resources/admin-guide/#restricting_access)
|
||||
* [NGINX (Restricting Access)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)
|
||||
|
||||
|
||||
# Custom authentication
|
||||
|
@ -313,7 +322,7 @@ In some circumstances instead of returning `None`, you may want to raise an `Aut
|
|||
Typically the approach you should take is:
|
||||
|
||||
* If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked.
|
||||
* If authentication is attempted but fails, raise a `AuthenticationFailed` exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.
|
||||
* If authentication is attempted but fails, raise an `AuthenticationFailed` exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.
|
||||
|
||||
You *may* also override the `.authenticate_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
|
||||
|
||||
|
@ -321,21 +330,21 @@ 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 django.contrib.auth.models import User
|
||||
from rest_framework import authentication
|
||||
from rest_framework import exceptions
|
||||
|
||||
class ExampleAuthentication(authentication.BaseAuthentication):
|
||||
def authenticate(self, request):
|
||||
username = request.META.get('X_USERNAME')
|
||||
username = request.META.get('HTTP_X_USERNAME')
|
||||
if not username:
|
||||
return None
|
||||
|
||||
|
@ -350,13 +359,17 @@ The following example will authenticate any incoming request as the user given b
|
|||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages are also available.
|
||||
The following third-party packages are also available.
|
||||
|
||||
## django-rest-knox
|
||||
|
||||
[Django-rest-knox][django-rest-knox] library provides models and views to handle token-based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).
|
||||
|
||||
## Django OAuth Toolkit
|
||||
|
||||
The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support, and works with Python 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 [jazzband][jazzband] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
|
||||
|
||||
#### Installation & configuration
|
||||
### Installation & configuration
|
||||
|
||||
Install using `pip`.
|
||||
|
||||
|
@ -364,15 +377,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.
|
||||
|
@ -381,9 +394,9 @@ For more details see the [Django REST framework - Getting started][django-oauth-
|
|||
|
||||
The [Django REST framework OAuth][django-rest-framework-oauth] package provides both OAuth1 and OAuth2 support for REST framework.
|
||||
|
||||
This package was previously included directly in REST framework but is now supported and maintained as a third party package.
|
||||
This package was previously included directly in the REST framework but is now supported and maintained as a third-party package.
|
||||
|
||||
#### Installation & configuration
|
||||
### Installation & configuration
|
||||
|
||||
Install the package using `pip`.
|
||||
|
||||
|
@ -405,23 +418,35 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
|
|||
|
||||
## Djoser
|
||||
|
||||
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.
|
||||
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.
|
||||
|
||||
## django-rest-auth
|
||||
## django-rest-auth / dj-rest-auth
|
||||
|
||||
[Django-rest-auth][django-rest-auth] library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.
|
||||
This library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.
|
||||
|
||||
## django-rest-framework-social-oauth2
|
||||
|
||||
[Django-rest-framework-social-oauth2][django-rest-framework-social-oauth2] library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to "in-house" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.
|
||||
There are currently two forks of this project.
|
||||
|
||||
## django-rest-knox
|
||||
* [Django-rest-auth][django-rest-auth] is the original project, [but is not currently receiving updates](https://github.com/Tivix/django-rest-auth/issues/568).
|
||||
* [Dj-rest-auth][dj-rest-auth] is a newer fork of the project.
|
||||
|
||||
[Django-rest-knox][django-rest-knox] library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).
|
||||
## drf-social-oauth2
|
||||
|
||||
[Drf-social-oauth2][drf-social-oauth2] is a framework that helps you authenticate with major social oauth2 vendors, such as Facebook, Google, Twitter, Orcid, etc. It generates tokens in a JWTed way with an easy setup.
|
||||
|
||||
## drfpasswordless
|
||||
|
||||
[drfpasswordless][drfpasswordless] adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's 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.
|
||||
[drfpasswordless][drfpasswordless] adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.
|
||||
|
||||
## django-rest-authemail
|
||||
|
||||
[django-rest-authemail][django-rest-authemail] provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully functional example project and detailed instructions are included.
|
||||
|
||||
## Django-Rest-Durin
|
||||
|
||||
[Django-Rest-Durin][django-rest-durin] is built with the idea to have one library that does token auth for multiple Web/CLI/Mobile API clients via one interface but allows different token configuration for each API Client that consumes the API. It provides support for multiple tokens per user via custom models, views, permissions that work with Django-Rest-Framework. The token expiration time can be different per API client and is customizable via the Django Admin Interface.
|
||||
|
||||
More information can be found in the [Documentation](https://django-rest-durin.readthedocs.io/en/latest/index.html).
|
||||
|
||||
[cite]: https://jacobian.org/writing/rest-worst-practices/
|
||||
[http401]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
|
||||
|
@ -439,7 +464,7 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
|
|||
[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
|
||||
[oauth-1.0a]: https://oauth.net/core/1.0a/
|
||||
[django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
|
||||
[evonove]: https://github.com/evonove/
|
||||
[jazzband]: https://github.com/jazzband/
|
||||
[oauthlib]: https://github.com/idan/oauthlib
|
||||
[djangorestframework-simplejwt]: https://github.com/davesque/django-rest-framework-simplejwt
|
||||
[etoccalino]: https://github.com/etoccalino/
|
||||
|
@ -453,6 +478,9 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
|
|||
[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
|
||||
[dj-rest-auth]: https://github.com/jazzband/dj-rest-auth
|
||||
[drf-social-oauth2]: https://github.com/wagnerdelima/drf-social-oauth2
|
||||
[django-rest-knox]: https://github.com/James1345/django-rest-knox
|
||||
[drfpasswordless]: https://github.com/aaronn/django-rest-framework-passwordless
|
||||
[django-rest-authemail]: https://github.com/celiao/django-rest-authemail
|
||||
[django-rest-durin]: https://github.com/eshaan7/django-rest-durin
|
||||
|
|
|
@ -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,17 +13,21 @@ provided in Django.
|
|||
|
||||
Django provides a [`method_decorator`][decorator] to use
|
||||
decorators with class based views. This can be used with
|
||||
other cache decorators such as [`cache_page`][page] and
|
||||
[`vary_on_cookie`][cookie].
|
||||
other cache decorators such as [`cache_page`][page],
|
||||
[`vary_on_cookie`][cookie] and [`vary_on_headers`][headers].
|
||||
|
||||
```python
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.cache import cache_page
|
||||
from django.views.decorators.vary import vary_on_cookie, vary_on_headers
|
||||
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework import viewsets
|
||||
|
||||
class UserViewSet(viewsets.Viewset):
|
||||
|
||||
# Cache requested url for each user for 2 hours
|
||||
class UserViewSet(viewsets.ViewSet):
|
||||
# With cookie: cache requested url for each user for 2 hours
|
||||
@method_decorator(cache_page(60*60*2))
|
||||
@method_decorator(vary_on_cookie)
|
||||
def list(self, request, format=None):
|
||||
|
@ -32,8 +36,19 @@ class UserViewSet(viewsets.Viewset):
|
|||
}
|
||||
return Response(content)
|
||||
|
||||
class PostView(APIView):
|
||||
|
||||
class ProfileView(APIView):
|
||||
# With auth: cache requested url for each user for 2 hours
|
||||
@method_decorator(cache_page(60*60*2))
|
||||
@method_decorator(vary_on_headers("Authorization",))
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
'user_feed': request.user.get_user_feed()
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
|
||||
class PostView(APIView):
|
||||
# Cache page for the requested url
|
||||
@method_decorator(cache_page(60*60*2))
|
||||
def get(self, request, format=None):
|
||||
|
@ -49,4 +64,5 @@ class PostView(APIView):
|
|||
|
||||
[page]: https://docs.djangoproject.com/en/dev/topics/cache/#the-per-view-cache
|
||||
[cookie]: https://docs.djangoproject.com/en/dev/topics/http/decorators/#django.views.decorators.vary.vary_on_cookie
|
||||
[headers]: https://docs.djangoproject.com/en/dev/topics/http/decorators/#django.views.decorators.vary.vary_on_headers
|
||||
[decorator]: https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-the-class
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: negotiation.py
|
||||
---
|
||||
source:
|
||||
- negotiation.py
|
||||
---
|
||||
|
||||
# Content negotiation
|
||||
|
||||
|
@ -79,7 +82,7 @@ The default content negotiation class may be set globally, using the `DEFAULT_CO
|
|||
|
||||
You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class-based views.
|
||||
|
||||
from myapp.negotiation import IgnoreClientContentNegotiation
|
||||
from myapp.negotiation import IgnoreClientContentNegotiation
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: exceptions.py
|
||||
---
|
||||
source:
|
||||
- exceptions.py
|
||||
---
|
||||
|
||||
# Exceptions
|
||||
|
||||
|
@ -35,7 +38,7 @@ Might receive an error response indicating that the `DELETE` method is not allow
|
|||
|
||||
Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the `NON_FIELD_ERRORS_KEY` setting.
|
||||
|
||||
Any example validation error might look like this:
|
||||
An example validation error might look like this:
|
||||
|
||||
HTTP/1.1 400 Bad Request
|
||||
Content-Type: application/json
|
||||
|
@ -219,7 +222,7 @@ By default this exception results in a response with the HTTP status code "429 T
|
|||
The `ValidationError` exception is slightly different from the other `APIException` classes:
|
||||
|
||||
* The `detail` argument is mandatory, not optional.
|
||||
* The `detail` argument may be a list or dictionary of error details, and may also be a nested data structure.
|
||||
* The `detail` argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the `validate()` method of a serializer. For example. `raise serializers.ValidationError({'name': 'Please enter a valid name.'})`
|
||||
* By convention you should import the serializers module and use a fully qualified `ValidationError` style, in order to differentiate it from Django's built-in validation error. For example. `raise serializers.ValidationError('This field must be an integer value.')`
|
||||
|
||||
The `ValidationError` class should be used for serializer and field validation, and by validator classes. It is also raised when calling `serializer.is_valid` with the `raise_exception` keyword argument:
|
||||
|
@ -257,6 +260,15 @@ Set as `handler400`:
|
|||
|
||||
handler400 = 'rest_framework.exceptions.bad_request'
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third-party packages are also available.
|
||||
|
||||
## DRF Standardized Errors
|
||||
|
||||
The [drf-standardized-errors][drf-standardized-errors] package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.
|
||||
|
||||
[cite]: https://doughellmann.com/blog/2009/06/19/python-exception-handling-techniques/
|
||||
[authentication]: authentication.md
|
||||
[django-custom-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
|
||||
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: fields.py
|
||||
---
|
||||
source:
|
||||
- fields.py
|
||||
---
|
||||
|
||||
# Serializer fields
|
||||
|
||||
|
@ -39,17 +42,29 @@ Set to false if this field is not required to be present during deserialization.
|
|||
|
||||
Setting this to `False` also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.
|
||||
|
||||
Defaults to `True`.
|
||||
Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer) default value will be `False` if you have specified `blank=True` or `default` or `null=True` at your field in your `Model`.
|
||||
|
||||
### `default`
|
||||
|
||||
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
|
||||
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.
|
||||
|
||||
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
|
||||
|
||||
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).
|
||||
May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a `requires_context = True` attribute, then the serializer field will be passed as an argument.
|
||||
|
||||
When serializing the instance, default will be used if the the object attribute or dictionary key is not present in the instance.
|
||||
For example:
|
||||
|
||||
class CurrentUserDefault:
|
||||
"""
|
||||
May be applied as a `default=...` value on a serializer field.
|
||||
Returns the current user.
|
||||
"""
|
||||
requires_context = True
|
||||
|
||||
def __call__(self, serializer_field):
|
||||
return serializer_field.context['request'].user
|
||||
|
||||
When serializing the instance, default will be used if the object attribute or dictionary key is not present in the instance.
|
||||
|
||||
Note that setting a `default` value implies that the field is not required. Including both the `default` and `required` keyword arguments is invalid and will raise an error.
|
||||
|
||||
|
@ -63,7 +78,14 @@ Defaults to `False`
|
|||
|
||||
### `source`
|
||||
|
||||
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. 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.
|
||||
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`.
|
||||
|
||||
When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal. Beware of possible n+1 problems when using source attribute if you are accessing a relational orm model. For example:
|
||||
|
||||
class CommentSerializer(serializers.Serializer):
|
||||
email = serializers.EmailField(source="user.email")
|
||||
|
||||
This case would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related].
|
||||
|
||||
The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
|
||||
|
||||
|
@ -129,7 +151,7 @@ Prior to Django 2.1 `models.BooleanField` fields were always `blank=True`. Thus
|
|||
since Django 2.1 default `serializers.BooleanField` instances will be generated
|
||||
without the `required` kwarg (i.e. equivalent to `required=True`) whereas with
|
||||
previous versions of Django, default `BooleanField` instances will be generated
|
||||
with a `required=False` option. If you want to control this behaviour manually,
|
||||
with a `required=False` option. If you want to control this behavior manually,
|
||||
explicitly declare the `BooleanField` on the serializer class, or use the
|
||||
`extra_kwargs` option to set the `required` flag.
|
||||
|
||||
|
@ -137,14 +159,6 @@ Corresponds to `django.db.models.fields.BooleanField`.
|
|||
|
||||
**Signature:** `BooleanField()`
|
||||
|
||||
## NullBooleanField
|
||||
|
||||
A boolean representation that also accepts `None` as a valid value.
|
||||
|
||||
Corresponds to `django.db.models.fields.NullBooleanField`.
|
||||
|
||||
**Signature:** `NullBooleanField()`
|
||||
|
||||
---
|
||||
|
||||
# String fields
|
||||
|
@ -157,10 +171,10 @@ Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.T
|
|||
|
||||
**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)`
|
||||
|
||||
- `max_length` - Validates that the input contains no more than this number of characters.
|
||||
- `min_length` - Validates that the input contains no fewer than this number of characters.
|
||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
|
||||
* `max_length` - Validates that the input contains no more than this number of characters.
|
||||
* `min_length` - Validates that the input contains no fewer than this number of characters.
|
||||
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
* `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
|
||||
|
||||
The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.
|
||||
|
||||
|
@ -208,11 +222,11 @@ A field that ensures the input is a valid UUID string. The `to_internal_value` m
|
|||
|
||||
**Signature:** `UUIDField(format='hex_verbose')`
|
||||
|
||||
- `format`: Determines the representation format of the uuid value
|
||||
- `'hex_verbose'` - The cannoncical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
- `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
|
||||
- `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
|
||||
- `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
* `format`: Determines the representation format of the uuid value
|
||||
* `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
* `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
|
||||
* `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
|
||||
* `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value`
|
||||
|
||||
## FilePathField
|
||||
|
@ -223,11 +237,11 @@ Corresponds to `django.forms.fields.FilePathField`.
|
|||
|
||||
**Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)`
|
||||
|
||||
- `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
|
||||
- `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
|
||||
- `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
|
||||
- `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
|
||||
- `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
|
||||
* `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
|
||||
* `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
|
||||
* `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
|
||||
* `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
|
||||
* `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
|
||||
|
||||
## IPAddressField
|
||||
|
||||
|
@ -237,8 +251,8 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen
|
|||
|
||||
**Signature**: `IPAddressField(protocol='both', unpack_ipv4=False, **options)`
|
||||
|
||||
- `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
|
||||
- `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
|
||||
* `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
|
||||
* `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
|
||||
|
||||
---
|
||||
|
||||
|
@ -252,8 +266,8 @@ Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.
|
|||
|
||||
**Signature**: `IntegerField(max_value=None, min_value=None)`
|
||||
|
||||
- `max_value` Validate that the number provided is no greater than this value.
|
||||
- `min_value` Validate that the number provided is no less than this value.
|
||||
* `max_value` Validate that the number provided is no greater than this value.
|
||||
* `min_value` Validate that the number provided is no less than this value.
|
||||
|
||||
## FloatField
|
||||
|
||||
|
@ -263,8 +277,8 @@ Corresponds to `django.db.models.fields.FloatField`.
|
|||
|
||||
**Signature**: `FloatField(max_value=None, min_value=None)`
|
||||
|
||||
- `max_value` Validate that the number provided is no greater than this value.
|
||||
- `min_value` Validate that the number provided is no less than this value.
|
||||
* `max_value` Validate that the number provided is no greater than this value.
|
||||
* `min_value` Validate that the number provided is no less than this value.
|
||||
|
||||
## DecimalField
|
||||
|
||||
|
@ -274,14 +288,14 @@ Corresponds to `django.db.models.fields.DecimalField`.
|
|||
|
||||
**Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)`
|
||||
|
||||
- `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
|
||||
- `decimal_places` The number of decimal places to store with the number.
|
||||
- `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
|
||||
- `max_value` Validate that the number provided is no greater than this value.
|
||||
- `min_value` Validate that the number provided is no less than this value.
|
||||
- `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
|
||||
- `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
|
||||
- `normalize_output` Will normalize the decimal value when serialized. This will strip all trailing zeroes and change the value's precision to the minimum required precision to be able to represent the value without loosing data. Defaults to `False`.
|
||||
* `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
|
||||
* `decimal_places` The number of decimal places to store with the number.
|
||||
* `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
|
||||
* `max_value` Validate that the number provided is no greater than this value.
|
||||
* `min_value` Validate that the number provided is no less than this value.
|
||||
* `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
|
||||
* `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
|
||||
* `normalize_output` Will normalize the decimal value when serialized. This will strip all trailing zeroes and change the value's precision to the minimum required precision to be able to represent the value without loosing data. Defaults to `False`.
|
||||
|
||||
#### Example usage
|
||||
|
||||
|
@ -293,10 +307,6 @@ And to validate numbers up to anything less than one billion with a resolution o
|
|||
|
||||
serializers.DecimalField(max_digits=19, decimal_places=10)
|
||||
|
||||
This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer.
|
||||
|
||||
If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise.
|
||||
|
||||
---
|
||||
|
||||
# Date and time fields
|
||||
|
@ -311,7 +321,7 @@ Corresponds to `django.db.models.fields.DateTimeField`.
|
|||
|
||||
* `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.
|
||||
* `default_timezone` - A `tzinfo` subclass (`zoneinfo` or `pytz`) prepresenting 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.
|
||||
|
||||
|
@ -357,7 +367,7 @@ Corresponds to `django.db.models.fields.TimeField`
|
|||
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `TIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `time` objects should be returned by `to_representation`. In this case the time encoding will be determined by the renderer.
|
||||
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
|
||||
|
||||
#### `TimeField` format strings
|
||||
#### `TimeField` format strings
|
||||
|
||||
Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`)
|
||||
|
||||
|
@ -371,8 +381,8 @@ The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu
|
|||
|
||||
**Signature:** `DurationField(max_value=None, min_value=None)`
|
||||
|
||||
- `max_value` Validate that the duration provided is no greater than this value.
|
||||
- `min_value` Validate that the duration provided is no less than this value.
|
||||
* `max_value` Validate that the duration provided is no greater than this value.
|
||||
* `min_value` Validate that the duration provided is no less than this value.
|
||||
|
||||
---
|
||||
|
||||
|
@ -386,10 +396,10 @@ Used by `ModelSerializer` to automatically generate fields if the corresponding
|
|||
|
||||
**Signature:** `ChoiceField(choices)`
|
||||
|
||||
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
|
||||
Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
|
||||
|
||||
|
@ -399,10 +409,10 @@ A field that can accept a set of zero, one or many values, chosen from a limited
|
|||
|
||||
**Signature:** `MultipleChoiceField(choices)`
|
||||
|
||||
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
|
||||
As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
|
||||
|
||||
|
@ -423,9 +433,9 @@ Corresponds to `django.forms.fields.FileField`.
|
|||
|
||||
**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
||||
|
||||
- `max_length` - Designates the maximum length for the file name.
|
||||
- `allow_empty_file` - Designates if empty files are allowed.
|
||||
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
* `max_length` - Designates the maximum length for the file name.
|
||||
* `allow_empty_file` - Designates if empty files are allowed.
|
||||
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
|
||||
## ImageField
|
||||
|
||||
|
@ -435,9 +445,9 @@ Corresponds to `django.forms.fields.ImageField`.
|
|||
|
||||
**Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
||||
|
||||
- `max_length` - Designates the maximum length for the file name.
|
||||
- `allow_empty_file` - Designates if empty files are allowed.
|
||||
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
* `max_length` - Designates the maximum length for the file name.
|
||||
* `allow_empty_file` - Designates if empty files are allowed.
|
||||
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
|
||||
Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained.
|
||||
|
||||
|
@ -449,11 +459,12 @@ 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.
|
||||
- `min_length` - Validates that the list contains no fewer than this number of elements.
|
||||
- `max_length` - Validates that the list contains no more than this number of elements.
|
||||
* `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
|
||||
* `allow_empty` - Designates if empty lists are allowed.
|
||||
* `min_length` - Validates that the list contains no fewer than this number of elements.
|
||||
* `max_length` - Validates that the list contains no more than this number of elements.
|
||||
|
||||
For example, to validate a list of integers you might use something like the following:
|
||||
|
||||
|
@ -472,9 +483,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.
|
||||
* `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:
|
||||
|
||||
|
@ -489,9 +501,10 @@ You can also use the declarative style, as with `ListField`. For example:
|
|||
|
||||
A preconfigured `DictField` that is compatible with Django's postgres `HStoreField`.
|
||||
|
||||
**Signature**: `HStoreField(child=<A_FIELD_INSTANCE>)`
|
||||
**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.
|
||||
* `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.
|
||||
|
||||
|
@ -499,9 +512,10 @@ Note that the child field **must** be an instance of `CharField`, as the hstore
|
|||
|
||||
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`.
|
||||
* `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`.
|
||||
|
||||
---
|
||||
|
||||
|
@ -520,7 +534,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
|
||||
|
||||
|
@ -552,7 +566,7 @@ This is a read-only field. It gets its value by calling a method on the serializ
|
|||
|
||||
**Signature**: `SerializerMethodField(method_name=None)`
|
||||
|
||||
- `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
|
||||
* `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
|
||||
|
||||
The serializer method referred to by the `method_name` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
|
||||
|
||||
|
@ -565,6 +579,7 @@ The serializer method referred to by the `method_name` argument should accept a
|
|||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = '__all__'
|
||||
|
||||
def get_days_since_joined(self, obj):
|
||||
return (now() - obj.date_joined).days
|
||||
|
@ -577,9 +592,7 @@ If you want to create a custom field, you'll need to subclass `Field` and then o
|
|||
|
||||
The `.to_representation()` method is called to convert the initial datatype into a primitive, serializable datatype.
|
||||
|
||||
The `to_internal_value()` method is called to restore a primitive datatype into its internal python representation. This method should raise a `serializers.ValidationError` if the data is invalid.
|
||||
|
||||
Note that the `WritableField` class that was present in version 2.x no longer exists. You should subclass `Field` and override `to_internal_value()` if the field supports data input.
|
||||
The `.to_internal_value()` method is called to restore a primitive datatype into its internal python representation. This method should raise a `serializers.ValidationError` if the data is invalid.
|
||||
|
||||
## Examples
|
||||
|
||||
|
@ -587,7 +600,7 @@ Note that the `WritableField` class that was present in version 2.x no longer ex
|
|||
|
||||
Let's look at an example of serializing a class that represents an RGB color value:
|
||||
|
||||
class Color(object):
|
||||
class Color:
|
||||
"""
|
||||
A color represented in the RGB colorspace.
|
||||
"""
|
||||
|
@ -630,7 +643,7 @@ 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__)
|
||||
|
||||
|
@ -654,7 +667,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):
|
||||
|
@ -707,7 +720,7 @@ the coordinate pair:
|
|||
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 serialiser
|
||||
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.
|
||||
|
||||
|
@ -719,7 +732,7 @@ to the desired output.
|
|||
>>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2)
|
||||
>>> out_serializer = DataPointSerializer(instance)
|
||||
>>> out_serializer.data
|
||||
ReturnDict([('label', 'testing'), ('coordinates', {'x': 1, 'y': 2})])
|
||||
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
|
||||
|
@ -740,7 +753,7 @@ suitable for updating our target object. With `source='*'`, the return from
|
|||
('y_coordinate', 4),
|
||||
('x_coordinate', 3)])
|
||||
|
||||
For completeness lets do the same thing again but with the nested serialiser
|
||||
For completeness lets do the same thing again but with the nested serializer
|
||||
approach suggested above:
|
||||
|
||||
class NestedCoordinateSerializer(serializers.Serializer):
|
||||
|
@ -759,17 +772,17 @@ Here the mapping between the target and source attribute pairs (`x` and
|
|||
`x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField`
|
||||
declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`.
|
||||
|
||||
Our new `DataPointSerializer` exhibits the same behaviour as the custom field
|
||||
Our new `DataPointSerializer` exhibits the same behavior as the custom field
|
||||
approach.
|
||||
|
||||
Serialising:
|
||||
Serializing:
|
||||
|
||||
>>> out_serializer = DataPointSerializer(instance)
|
||||
>>> out_serializer.data
|
||||
ReturnDict([('label', 'testing'),
|
||||
('coordinates', OrderedDict([('x', 1), ('y', 2)]))])
|
||||
|
||||
Deserialising:
|
||||
Deserializing:
|
||||
|
||||
>>> in_serializer = DataPointSerializer(data=data)
|
||||
>>> in_serializer.is_valid()
|
||||
|
@ -796,8 +809,8 @@ But we also get the built-in validation for free:
|
|||
{'x': ['A valid integer is required.'],
|
||||
'y': ['A valid integer is required.']})])
|
||||
|
||||
For this reason, the nested serialiser approach would be the first to try. You
|
||||
would use the custom field approach when the nested serialiser becomes infeasible
|
||||
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.
|
||||
|
||||
|
||||
|
@ -819,7 +832,7 @@ the [djangorestframework-recursive][djangorestframework-recursive] package provi
|
|||
|
||||
## django-rest-framework-gis
|
||||
|
||||
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
|
||||
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
|
||||
|
||||
## django-rest-framework-hstore
|
||||
|
||||
|
@ -838,3 +851,4 @@ The [django-rest-framework-hstore][django-rest-framework-hstore] package provide
|
|||
[django-hstore]: https://github.com/djangonauts/django-hstore
|
||||
[python-decimal-rounding-modes]: https://docs.python.org/3/library/decimal.html#rounding-modes
|
||||
[django-current-timezone]: https://docs.djangoproject.com/en/stable/topics/i18n/timezones/#default-time-zone-and-current-time-zone
|
||||
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: filters.py
|
||||
---
|
||||
source:
|
||||
- filters.py
|
||||
---
|
||||
|
||||
# Filtering
|
||||
|
||||
|
@ -42,7 +45,7 @@ Another style of filtering might involve restricting the queryset based on some
|
|||
|
||||
For example if your URL config contained an entry like this:
|
||||
|
||||
url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
|
||||
re_path('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
|
||||
|
||||
You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
|
||||
|
||||
|
@ -72,7 +75,7 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
|
|||
by filtering against a `username` query parameter in the URL.
|
||||
"""
|
||||
queryset = Purchase.objects.all()
|
||||
username = self.request.query_params.get('username', None)
|
||||
username = self.request.query_params.get('username')
|
||||
if username is not None:
|
||||
queryset = queryset.filter(purchaser__username=username)
|
||||
return queryset
|
||||
|
@ -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
|
||||
|
||||
|
@ -139,17 +142,25 @@ 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`
|
||||
To use `DjangoFilterBackend`, first install `django-filter`.
|
||||
|
||||
pip install django-filter
|
||||
|
||||
Then add `'django_filters'` to Django's `INSTALLED_APPS`:
|
||||
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'django_filters',
|
||||
...
|
||||
]
|
||||
|
||||
You should now either add the filter backend to your settings:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
|
||||
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
|
||||
}
|
||||
|
||||
Or add the filter backend to an individual View or ViewSet.
|
||||
|
@ -158,15 +169,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 `filterset_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against.
|
||||
|
||||
class ProductList(generics.ListAPIView):
|
||||
queryset = Product.objects.all()
|
||||
serializer_class = ProductSerializer
|
||||
filter_backends = (DjangoFilterBackend,)
|
||||
filterset_fields = ('category', 'in_stock')
|
||||
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:
|
||||
|
||||
|
@ -192,8 +203,8 @@ The `SearchFilter` class will only be applied if the view has a `search_fields`
|
|||
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:
|
||||
|
||||
|
@ -201,7 +212,11 @@ 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']
|
||||
|
||||
For [JSONField][JSONField] and [HStoreField][HStoreField] fields you can filter based on nested values within the data structure using the same double-underscore notation:
|
||||
|
||||
search_fields = ['data__breed', 'data__owner__other_pets__0__name']
|
||||
|
||||
By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.
|
||||
|
||||
|
@ -209,24 +224,24 @@ The search behavior may be restricted by prepending various characters to the `s
|
|||
|
||||
* '^' Starts-with search.
|
||||
* '=' Exact matches.
|
||||
* '@' Full-text search. (Currently only supported Django's MySQL backend.)
|
||||
* '@' Full-text search. (Currently only supported Django's [PostgreSQL backend][postgres-search].)
|
||||
* '$' Regex search.
|
||||
|
||||
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)
|
||||
return ['title']
|
||||
return super().get_search_fields(view, request)
|
||||
|
||||
For more details, see the [Django documentation][search-django-admin].
|
||||
|
||||
|
@ -259,8 +274,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.
|
||||
|
||||
|
@ -271,7 +286,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
|
||||
|
@ -283,61 +298,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.
|
||||
|
||||
---
|
||||
|
||||
**Note:** This filter has been deprecated as of version 3.9 and moved to the 3rd-party [`djangorestframework-guardian` package][django-rest-framework-guardian].
|
||||
|
||||
---
|
||||
|
||||
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.
|
||||
|
@ -367,7 +335,7 @@ Generic filters may also present an interface in the browsable API. To do so you
|
|||
|
||||
The method should return a rendered HTML string.
|
||||
|
||||
## Pagination & schemas
|
||||
## Filtering & schemas
|
||||
|
||||
You can also make the filter controls available to the schema autogeneration
|
||||
that REST framework provides, by implementing a `get_schema_fields()` method. This method should have the following signature:
|
||||
|
@ -399,12 +367,11 @@ The [djangorestframework-word-filter][django-rest-framework-word-search-filter]
|
|||
[cite]: https://docs.djangoproject.com/en/stable/topics/db/queries/#retrieving-specific-objects-with-filters
|
||||
[django-filter-docs]: https://django-filter.readthedocs.io/en/latest/index.html
|
||||
[django-filter-drf-docs]: https://django-filter.readthedocs.io/en/latest/guide/rest_framework.html
|
||||
[guardian]: https://django-guardian.readthedocs.io/
|
||||
[view-permissions]: https://django-guardian.readthedocs.io/en/latest/userguide/assign.html
|
||||
[view-permissions-blogpost]: https://blog.nyaruka.com/adding-a-view-permission-to-django-models
|
||||
[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-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
|
||||
[django-rest-framework-word-search-filter]: https://github.com/trollknurr/django-rest-framework-word-search-filter
|
||||
[django-url-filter]: https://github.com/miki725/django-url-filter
|
||||
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
|
||||
[HStoreField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#hstorefield
|
||||
[JSONField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#jsonfield
|
||||
[postgres-search]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/search/
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: urlpatterns.py
|
||||
---
|
||||
source:
|
||||
- urlpatterns.py
|
||||
---
|
||||
|
||||
# Format suffixes
|
||||
|
||||
|
@ -20,8 +23,8 @@ Returns a URL pattern list which includes format suffix patterns appended to eac
|
|||
Arguments:
|
||||
|
||||
* **urlpatterns**: Required. A URL pattern list.
|
||||
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
|
||||
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
|
||||
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
|
||||
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
|
||||
|
||||
Example:
|
||||
|
||||
|
@ -29,16 +32,16 @@ Example:
|
|||
from blog import views
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^/$', views.apt_root),
|
||||
url(r'^comments/$', views.comment_list),
|
||||
url(r'^comments/(?P<pk>[0-9]+)/$', views.comment_detail)
|
||||
path('', views.apt_root),
|
||||
path('comments/', views.comment_list),
|
||||
path('comments/<int:pk>/', views.comment_detail)
|
||||
]
|
||||
|
||||
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
|
||||
|
||||
When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example:
|
||||
|
||||
@api_view(('GET', 'POST'))
|
||||
@api_view(['GET', 'POST'])
|
||||
def comment_list(request, format=None):
|
||||
# do stuff...
|
||||
|
||||
|
@ -59,7 +62,7 @@ Also note that `format_suffix_patterns` does not support descending into `includ
|
|||
|
||||
If using the `i18n_patterns` function provided by Django, as well as `format_suffix_patterns` you should make sure that the `i18n_patterns` function is applied as the final, or outermost function. For example:
|
||||
|
||||
url patterns = [
|
||||
urlpatterns = [
|
||||
…
|
||||
]
|
||||
|
||||
|
|
|
@ -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`
|
||||
|
@ -42,7 +45,7 @@ For more complex cases you might also want to override various methods on the vi
|
|||
|
||||
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something like the following entry:
|
||||
|
||||
url(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
|
||||
path('users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
|
||||
|
||||
---
|
||||
|
||||
|
@ -62,7 +65,7 @@ The following attributes control the basic view behavior.
|
|||
|
||||
* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. If you are overriding a view method, it is important that you call `get_queryset()` instead of accessing this property directly, as `queryset` will get evaluated once, and those results will be cached for all subsequent requests.
|
||||
* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method.
|
||||
* `lookup_field` - The model field that should be used to for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
|
||||
* `lookup_field` - The model field that should be used for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
|
||||
* `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`.
|
||||
|
||||
**Pagination**:
|
||||
|
@ -93,6 +96,12 @@ For example:
|
|||
user = self.request.user
|
||||
return user.accounts.all()
|
||||
|
||||
---
|
||||
|
||||
**Note:** If the `serializer_class` used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related].
|
||||
|
||||
---
|
||||
|
||||
#### `get_object(self)`
|
||||
|
||||
Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.
|
||||
|
@ -120,12 +129,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)
|
||||
|
@ -172,8 +181,6 @@ You can also use these hooks to provide additional validation, by raising a `Val
|
|||
raise ValidationError('You have already signed up')
|
||||
serializer.save(user=self.request.user)
|
||||
|
||||
**Note**: These methods replace the old-style version 2.x `pre_save`, `post_save`, `pre_delete` and `post_delete` methods, which are no longer available.
|
||||
|
||||
**Other methods**:
|
||||
|
||||
You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`.
|
||||
|
@ -210,7 +217,7 @@ If the request data provided for creating the object was invalid, a `400 Bad Req
|
|||
|
||||
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
|
||||
|
||||
If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`.
|
||||
If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise, it will return a `404 Not Found`.
|
||||
|
||||
## UpdateModelMixin
|
||||
|
||||
|
@ -318,7 +325,7 @@ Often you'll want to use the existing generic views, but use some slightly custo
|
|||
|
||||
For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:
|
||||
|
||||
class MultipleFieldLookupMixin(object):
|
||||
class MultipleFieldLookupMixin:
|
||||
"""
|
||||
Apply this mixin to any view or viewset to get multiple field filtering
|
||||
based on a `lookup_fields` attribute, instead of the default single field filtering.
|
||||
|
@ -328,7 +335,7 @@ For example, if you need to lookup objects based on multiple fields in the URL c
|
|||
queryset = self.filter_queryset(queryset) # Apply any filter backends
|
||||
filter = {}
|
||||
for field in self.lookup_fields:
|
||||
if self.kwargs[field]: # Ignore empty fields.
|
||||
if self.kwargs.get(field): # Ignore empty fields.
|
||||
filter[field] = self.kwargs[field]
|
||||
obj = get_object_or_404(queryset, **filter) # Lookup the object
|
||||
self.check_object_permissions(self.request, obj)
|
||||
|
@ -339,7 +346,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 +382,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 +394,5 @@ 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
|
||||
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: metadata.py
|
||||
---
|
||||
source:
|
||||
- metadata.py
|
||||
---
|
||||
|
||||
# Metadata
|
||||
|
||||
|
@ -68,7 +71,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.
|
||||
|
||||
@action(methods=['GET'], detail=False)
|
||||
def schema(self, request):
|
||||
def api_schema(self, request):
|
||||
meta = self.metadata_class()
|
||||
data = meta.determine_metadata(request, self)
|
||||
return Response(data)
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: pagination.py
|
||||
---
|
||||
source:
|
||||
- pagination.py
|
||||
---
|
||||
|
||||
# Pagination
|
||||
|
||||
|
@ -75,7 +78,7 @@ This pagination style accepts a single number page number in the request query p
|
|||
|
||||
HTTP 200 OK
|
||||
{
|
||||
"count": 1023
|
||||
"count": 1023,
|
||||
"next": "https://api.example.org/accounts/?page=5",
|
||||
"previous": "https://api.example.org/accounts/?page=3",
|
||||
"results": [
|
||||
|
@ -123,7 +126,7 @@ This pagination style mirrors the syntax used when looking up multiple database
|
|||
|
||||
HTTP 200 OK
|
||||
{
|
||||
"count": 1023
|
||||
"count": 1023,
|
||||
"next": "https://api.example.org/accounts/?limit=100&offset=500",
|
||||
"previous": "https://api.example.org/accounts/?limit=100&offset=300",
|
||||
"results": [
|
||||
|
@ -215,16 +218,16 @@ To set these attributes you should override the `CursorPagination` class, and th
|
|||
|
||||
# Custom pagination styles
|
||||
|
||||
To create a custom pagination serializer class you should subclass `pagination.BasePagination` and override the `paginate_queryset(self, queryset, request, view=None)` and `get_paginated_response(self, data)` methods:
|
||||
To create a custom pagination serializer class, you should inherit the subclass `pagination.BasePagination`, override the `paginate_queryset(self, queryset, request, view=None)`, and `get_paginated_response(self, data)` methods:
|
||||
|
||||
* The `paginate_queryset` method is passed the initial queryset and should return an iterable object that contains only the data in the requested page.
|
||||
* The `get_paginated_response` method is passed the serialized page data and should return a `Response` instance.
|
||||
* The `paginate_queryset` method is passed to the initial queryset and should return an iterable object. That object contains only the data in the requested page.
|
||||
* The `get_paginated_response` method is passed to the serialized page data and should return a `Response` instance.
|
||||
|
||||
Note that the `paginate_queryset` method may set state on the pagination instance, that may later be used by the `get_paginated_response` method.
|
||||
|
||||
## Example
|
||||
|
||||
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
|
||||
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
|
||||
|
||||
class CustomPagination(pagination.PageNumberPagination):
|
||||
def get_paginated_response(self, data):
|
||||
|
@ -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,7 +312,7 @@ 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 described 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 REST API documentation][github-traversing-with-pagination].
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/topics/pagination/
|
||||
[link-header]: ../img/link-header-pagination.png
|
||||
|
@ -321,3 +322,4 @@ The [`django-rest-framework-link-header-pagination` package][drf-link-header-pag
|
|||
[drf-link-header-pagination]: https://github.com/tbeadle/django-rest-framework-link-header-pagination
|
||||
[disqus-cursor-api]: https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api
|
||||
[float_cursor_pagination_example]: https://gist.github.com/keturn/8bc88525a183fd41c73ffb729b8865be#file-fpcursorpagination-py
|
||||
[github-traversing-with-pagination]: https://docs.github.com/en/rest/guides/traversing-with-pagination
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: parsers.py
|
||||
---
|
||||
source:
|
||||
- parsers.py
|
||||
---
|
||||
|
||||
# Parsers
|
||||
|
||||
|
@ -12,7 +15,7 @@ REST framework includes a number of built in Parser classes, that allow you to a
|
|||
|
||||
## How the parser is determined
|
||||
|
||||
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
|
||||
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
|
||||
|
||||
---
|
||||
|
||||
|
@ -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.
|
||||
|
@ -70,7 +73,7 @@ Or, if you're using the `@api_view` decorator with function based views.
|
|||
|
||||
## JSONParser
|
||||
|
||||
Parses `JSON` request content.
|
||||
Parses `JSON` request content. `request.data` will be populated with a dictionary of data.
|
||||
|
||||
**.media_type**: `application/json`
|
||||
|
||||
|
@ -84,7 +87,7 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
|
|||
|
||||
## MultiPartParser
|
||||
|
||||
Parses multipart HTML form content, which supports file uploads. Both `request.data` will be populated with a `QueryDict`.
|
||||
Parses multipart HTML form content, which supports file uploads. `request.data` and `request.FILES` will be populated with a `QueryDict` and `MultiValueDict` respectively.
|
||||
|
||||
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
|
||||
|
||||
|
@ -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']
|
||||
|
@ -122,7 +125,7 @@ If it is called without a `filename` URL keyword argument, then the client must
|
|||
# urls.py
|
||||
urlpatterns = [
|
||||
# ...
|
||||
url(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
|
||||
re_path(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
|
||||
]
|
||||
|
||||
---
|
||||
|
@ -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
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: permissions.py
|
||||
---
|
||||
source:
|
||||
- permissions.py
|
||||
---
|
||||
|
||||
# Permissions
|
||||
|
||||
|
@ -21,9 +24,9 @@ A slightly less strict style of permission would be to allow full access to auth
|
|||
Permissions in REST framework are always defined as a list of permission classes.
|
||||
|
||||
Before running the main body of the view each permission in the list is checked.
|
||||
If any permission check fails an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run.
|
||||
If any permission check fails, an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run.
|
||||
|
||||
When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
|
||||
When the permission checks fail, either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
|
||||
|
||||
* The request was successfully authenticated, but permission was denied. *— An HTTP 403 Forbidden response will be returned.*
|
||||
* The request was not successfully authenticated, and the highest priority authentication class *does not* use `WWW-Authenticate` headers. *— An HTTP 403 Forbidden response will be returned.*
|
||||
|
@ -51,7 +54,7 @@ For example:
|
|||
---
|
||||
|
||||
**Note**: With the exception of `DjangoObjectPermissions`, the provided
|
||||
permission classes in `rest_framework.permssions` **do not** implement the
|
||||
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
|
||||
|
@ -67,21 +70,23 @@ For performance reasons the generic views will not automatically apply object le
|
|||
|
||||
Often when you're using object level permissions you'll also want to [filter the queryset][filtering] appropriately, to ensure that users only have visibility onto instances that they are permitted to view.
|
||||
|
||||
Because the `get_object()` method is not called, object level permissions from the `has_object_permission()` method **are not applied** when creating objects. In order to restrict object creation you need to implement the permission check either in your Serializer class or override the `perform_create()` method of your ViewSet class.
|
||||
|
||||
## Setting the permission policy
|
||||
|
||||
The default permission policy may be set globally, using the `DEFAULT_PERMISSION_CLASSES` setting. For example.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PERMISSION_CLASSES': (
|
||||
'DEFAULT_PERMISSION_CLASSES': [
|
||||
'rest_framework.permissions.IsAuthenticated',
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
If not specified, this setting defaults to allowing unrestricted access:
|
||||
|
||||
'DEFAULT_PERMISSION_CLASSES': (
|
||||
'DEFAULT_PERMISSION_CLASSES': [
|
||||
'rest_framework.permissions.AllowAny',
|
||||
)
|
||||
]
|
||||
|
||||
You can also set the authentication policy on a per-view, or per-viewset basis,
|
||||
using the `APIView` class-based views.
|
||||
|
@ -91,7 +96,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 = {
|
||||
|
@ -106,14 +111,14 @@ 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'
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
__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.
|
||||
__Note:__ when you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in the __settings.py__ file.
|
||||
|
||||
Provided they inherit from `rest_framework.permissions.BasePermission`, permissions can be composed using standard Python bitwise operators. For example, `IsAuthenticatedOrReadOnly` could be written:
|
||||
|
||||
|
@ -126,7 +131,7 @@ Provided they inherit from `rest_framework.permissions.BasePermission`, permissi
|
|||
return request.method in SAFE_METHODS
|
||||
|
||||
class ExampleView(APIView):
|
||||
permission_classes = (IsAuthenticated|ReadOnly,)
|
||||
permission_classes = [IsAuthenticated|ReadOnly]
|
||||
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
|
@ -166,22 +171,16 @@ This permission is suitable if you want to your API to allow read permissions to
|
|||
|
||||
## DjangoModelPermissions
|
||||
|
||||
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property set. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned.
|
||||
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property or `get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned. The appropriate model is determined by checking `get_queryset().model` or `queryset.model`.
|
||||
|
||||
* `POST` requests require the user to have the `add` permission on the model.
|
||||
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
|
||||
* `DELETE` requests require the user to have the `delete` permission on the model.
|
||||
|
||||
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
|
||||
The default behavior can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
|
||||
|
||||
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
|
||||
|
||||
#### Using with views that do not include a `queryset` attribute.
|
||||
|
||||
If you're using this permission with a view that uses an overridden `get_queryset()` method there may not be a `queryset` attribute on the view. In this case we suggest also marking the view with a sentinel queryset, so that this class can determine the required permissions. For example:
|
||||
|
||||
queryset = User.objects.none() # Required for DjangoModelPermissions
|
||||
|
||||
## DjangoModelPermissionsOrAnonReadOnly
|
||||
|
||||
Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API.
|
||||
|
@ -228,7 +227,7 @@ If you need to test if a request is a read operation or a write operation, you s
|
|||
|
||||
---
|
||||
|
||||
Custom permissions will raise a `PermissionDenied` exception if the test fails. To change the error message associated with the exception, implement a `message` attribute directly on your custom permission. Otherwise the `default_detail` attribute from `PermissionDenied` will be used.
|
||||
Custom permissions will raise a `PermissionDenied` exception if the test fails. To change the error message associated with the exception, implement a `message` attribute directly on your custom permission. Otherwise the `default_detail` attribute from `PermissionDenied` will be used. Similarly, to change the code identifier associated with the exception, implement a `code` attribute directly on your custom permission - otherwise the `default_code` attribute from `PermissionDenied` will be used.
|
||||
|
||||
from rest_framework import permissions
|
||||
|
||||
|
@ -240,19 +239,19 @@ Custom permissions will raise a `PermissionDenied` exception if the test fails.
|
|||
|
||||
## Examples
|
||||
|
||||
The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted.
|
||||
The following is an example of a permission class that checks the incoming request's IP address against a blocklist, and denies the request if the IP has been blocked.
|
||||
|
||||
from rest_framework import permissions
|
||||
|
||||
class BlacklistPermission(permissions.BasePermission):
|
||||
class BlocklistPermission(permissions.BasePermission):
|
||||
"""
|
||||
Global permission check for blacklisted IPs.
|
||||
Global permission check for blocked IPs.
|
||||
"""
|
||||
|
||||
def has_permission(self, request, view):
|
||||
ip_addr = request.META['REMOTE_ADDR']
|
||||
blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
|
||||
return not blacklisted
|
||||
blocked = Blocklist.objects.filter(ip_addr=ip_addr).exists()
|
||||
return not blocked
|
||||
|
||||
As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example:
|
||||
|
||||
|
@ -275,12 +274,40 @@ Note that the generic views will check the appropriate object level permissions,
|
|||
|
||||
Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the [filtering documentation][filtering] for more details.
|
||||
|
||||
# Overview of access restriction methods
|
||||
|
||||
REST framework offers three different methods to customize access restrictions on a case-by-case basis. These apply in different scenarios and have different effects and limitations.
|
||||
|
||||
* `queryset`/`get_queryset()`: Limits the general visibility of existing objects from the database. The queryset limits which objects will be listed and which objects can be modified or deleted. The `get_queryset()` method can apply different querysets based on the current action.
|
||||
* `permission_classes`/`get_permissions()`: General permission checks based on the current action, request and targeted object. Object level permissions can only be applied to retrieve, modify and deletion actions. Permission checks for list and create will be applied to the entire object type. (In case of list: subject to restrictions in the queryset.)
|
||||
* `serializer_class`/`get_serializer()`: Instance level restrictions that apply to all objects on input and output. The serializer may have access to the request context. The `get_serializer()` method can apply different serializers based on the current action.
|
||||
|
||||
The following table lists the access restriction methods and the level of control they offer over which actions.
|
||||
|
||||
| | `queryset` | `permission_classes` | `serializer_class` |
|
||||
|------------------------------------|------------|----------------------|--------------------|
|
||||
| Action: list | global | global | object-level* |
|
||||
| Action: create | no | global | object-level |
|
||||
| Action: retrieve | global | object-level | object-level |
|
||||
| Action: update | global | object-level | object-level |
|
||||
| Action: partial_update | global | object-level | object-level |
|
||||
| Action: destroy | global | object-level | no |
|
||||
| Can reference action in decision | no** | yes | no** |
|
||||
| Can reference request in decision | no** | yes | yes |
|
||||
|
||||
\* A Serializer class should not raise PermissionDenied in a list action, or the entire list would not be returned. <br>
|
||||
\** The `get_*()` methods have access to the current view and can return different Serializer or QuerySet instances based on the request or action.
|
||||
|
||||
---
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages are also available.
|
||||
|
||||
## DRF - Access Policy
|
||||
|
||||
The [Django REST - Access Policy][drf-access-policy] package provides a way to define complex access rules in declarative policy classes that are attached to view sets or function-based views. The policies are defined in JSON in a format similar to AWS' Identity & Access Management policies.
|
||||
|
||||
## Composed Permissions
|
||||
|
||||
The [Composed Permissions][composed-permissions] package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.
|
||||
|
@ -299,12 +326,17 @@ The [Django Rest Framework Roles][django-rest-framework-roles] package makes it
|
|||
|
||||
## Django REST Framework API Key
|
||||
|
||||
The [Django REST Framework API Key][djangorestframework-api-key] package provides the ability to authorize clients based on customizable API key headers. This package is targeted at situations in which regular user-based authentication (e.g. `TokenAuthentication`) is not suitable, e.g. allowing non-human clients to safely use your API. API keys are generated and validated through cryptographic methods and can be created and revoked from the Django admin interface at anytime.
|
||||
The [Django REST Framework API Key][djangorestframework-api-key] package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. _machines_) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.
|
||||
|
||||
## Django Rest Framework Role Filters
|
||||
|
||||
The [Django Rest Framework Role Filters][django-rest-framework-role-filters] package provides simple filtering over multiple types of roles.
|
||||
|
||||
## Django Rest Framework PSQ
|
||||
|
||||
The [Django Rest Framework PSQ][drf-psq] package is an extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.
|
||||
|
||||
|
||||
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
|
||||
[authentication]: authentication.md
|
||||
[throttling]: throttling.md
|
||||
|
@ -315,8 +347,10 @@ The [Django Rest Framework Role Filters][django-rest-framework-role-filters] pac
|
|||
[filtering]: filtering.md
|
||||
[composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions
|
||||
[rest-condition]: https://github.com/caxap/rest_condition
|
||||
[dry-rest-permissions]: https://github.com/Helioscene/dry-rest-permissions
|
||||
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
|
||||
[django-rest-framework-roles]: https://github.com/computer-lab/django-rest-framework-roles
|
||||
[djangorestframework-api-key]: https://github.com/florimondmanca/djangorestframework-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
|
||||
[drf-psq]: https://github.com/drf-psq/drf-psq
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: relations.py
|
||||
---
|
||||
source:
|
||||
- relations.py
|
||||
---
|
||||
|
||||
# Serializer relations
|
||||
|
||||
|
@ -14,6 +17,37 @@ Relational fields are used to represent model relationships. They can be applie
|
|||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
**Note:** REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of `select_related` and `prefetch_related` since it would be too much magic. A serializer with a field spanning an orm relation through its source attribute could require an additional database hit to fetch related objects from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer.
|
||||
|
||||
For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched:
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = serializers.SlugRelatedField(
|
||||
many=True,
|
||||
read_only=True,
|
||||
slug_field='title'
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
# For each album object, tracks should be fetched from database
|
||||
qs = Album.objects.all()
|
||||
print(AlbumSerializer(qs, many=True).data)
|
||||
|
||||
If `AlbumSerializer` is used to serialize a fairly large queryset with `many=True` then it could be a serious performance problem. Optimizing the queryset passed to `AlbumSerializer` with:
|
||||
|
||||
qs = Album.objects.prefetch_related('tracks')
|
||||
# No additional database hits required
|
||||
print(AlbumSerializer(qs, many=True).data)
|
||||
|
||||
would solve the issue.
|
||||
|
||||
---
|
||||
|
||||
#### Inspecting relationships.
|
||||
|
||||
When using the `ModelSerializer` class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style.
|
||||
|
@ -43,7 +77,7 @@ 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 __str__(self):
|
||||
|
@ -53,16 +87,16 @@ In order to explain the various types of relational fields, we'll use a couple o
|
|||
|
||||
`StringRelatedField` may be used to represent the target of the relationship using its `__str__` method.
|
||||
|
||||
For example, the following serializer.
|
||||
For example, the following serializer:
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = serializers.StringRelatedField(many=True)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ('album_name', 'artist', 'tracks')
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
Would serialize to the following representation.
|
||||
Would serialize to the following representation:
|
||||
|
||||
{
|
||||
'album_name': 'Things We Lost In The Fire',
|
||||
|
@ -92,7 +126,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:
|
||||
|
||||
|
@ -132,7 +166,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:
|
||||
|
||||
|
@ -184,7 +218,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:
|
||||
|
||||
|
@ -212,14 +246,14 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e
|
|||
|
||||
## HyperlinkedIdentityField
|
||||
|
||||
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
|
||||
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
|
||||
|
||||
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
|
||||
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ('album_name', 'artist', 'track_listing')
|
||||
fields = ['album_name', 'artist', 'track_listing']
|
||||
|
||||
Would serialize to a representation like this:
|
||||
|
||||
|
@ -242,7 +276,9 @@ This field is always read-only.
|
|||
|
||||
# Nested relationships
|
||||
|
||||
Nested relationships can be expressed by using serializers as fields.
|
||||
As opposed to previously discussed _references_ to another entity, the referred entity can instead also be embedded or _nested_
|
||||
in the representation of the object that refers to it.
|
||||
Such nested relationships can be expressed by using serializers as fields.
|
||||
|
||||
If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field.
|
||||
|
||||
|
@ -253,14 +289,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:
|
||||
|
||||
|
@ -286,19 +322,19 @@ Would serialize to a nested representation like this:
|
|||
|
||||
## Writable nested serializers
|
||||
|
||||
By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create `create()` and/or `update()` methods in order to explicitly specify how the child relationships should be saved.
|
||||
By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create `create()` and/or `update()` methods in order to explicitly specify how the child relationships should be saved:
|
||||
|
||||
class TrackSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Track
|
||||
fields = ('order', 'title', 'duration')
|
||||
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')
|
||||
|
@ -332,13 +368,13 @@ output representation should be generated from the model instance.
|
|||
|
||||
To implement a custom relational field, you should override `RelatedField`, and implement the `.to_representation(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. The `value` argument will typically be a model instance.
|
||||
|
||||
If you want to implement a read-write relational field, you must also implement the `.to_internal_value(self, data)` method.
|
||||
If you want to implement a read-write relational field, you must also implement the [`.to_internal_value(self, data)` method][to_internal_value].
|
||||
|
||||
To provide a dynamic queryset based on the `context`, you can also override `.get_queryset(self)` instead of specifying `.queryset` on the class or when initializing the field.
|
||||
|
||||
## Example
|
||||
|
||||
For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration.
|
||||
For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration:
|
||||
|
||||
import time
|
||||
|
||||
|
@ -352,9 +388,9 @@ 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.
|
||||
This custom field would then serialize to the following representation:
|
||||
|
||||
{
|
||||
'album_name': 'Sometimes I Wish We Were an Eagle',
|
||||
|
@ -458,8 +494,8 @@ This behavior is intended to prevent a template from being unable to render in a
|
|||
|
||||
There are two keyword arguments you can use to control this behavior:
|
||||
|
||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`.
|
||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`.
|
||||
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
|
||||
You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`.
|
||||
|
||||
|
@ -477,7 +513,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:
|
||||
|
||||
|
@ -489,7 +525,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.
|
||||
|
||||
|
@ -530,7 +566,7 @@ And the following two models, which may have associated tags:
|
|||
text = models.CharField(max_length=1000)
|
||||
tags = GenericRelation(TaggedItem)
|
||||
|
||||
We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized.
|
||||
We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized:
|
||||
|
||||
class TaggedObjectRelatedField(serializers.RelatedField):
|
||||
"""
|
||||
|
@ -576,6 +612,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
|
||||
|
@ -596,3 +634,6 @@ The [rest-framework-generic-relations][drf-nested-relations] library provides re
|
|||
[generic-relations]: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/#id1
|
||||
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
|
||||
[drf-nested-relations]: https://github.com/Ian-Foote/rest-framework-generic-relations
|
||||
[django-intermediary-manytomany]: https://docs.djangoproject.com/en/stable/topics/db/models/#intermediary-manytomany
|
||||
[dealing-with-nested-objects]: https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
|
||||
[to_internal_value]: https://www.django-rest-framework.org/api-guide/serializers/#to_internal_valueself-data
|
||||
|
|
|
@ -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.
|
||||
|
@ -100,6 +103,16 @@ Unlike other renderers, the data passed to the `Response` does not need to be se
|
|||
|
||||
The TemplateHTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context.
|
||||
|
||||
---
|
||||
|
||||
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the `TemplateHTMLRenderer` to render it. For example:
|
||||
|
||||
```
|
||||
response.data = {'results': response.data}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
The template name is determined by (in order of preference):
|
||||
|
||||
1. An explicit `template_name` argument passed to the response.
|
||||
|
@ -113,7 +126,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()
|
||||
|
@ -139,8 +152,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)
|
||||
|
@ -179,7 +192,7 @@ By default the response content will be rendered with the highest priority rende
|
|||
def get_default_renderer(self, view):
|
||||
return JSONRenderer()
|
||||
|
||||
## AdminRenderer
|
||||
## AdminRenderer
|
||||
|
||||
Renders data into HTML for an admin-like display:
|
||||
|
||||
|
@ -244,7 +257,7 @@ This renderer is used for rendering HTML multipart form data. **It is not suita
|
|||
|
||||
# Custom renderers
|
||||
|
||||
To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, media_type=None, renderer_context=None)` method.
|
||||
To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, accepted_media_type=None, renderer_context=None)` method.
|
||||
|
||||
The method should return a bytestring, which will be used as the body of the HTTP response.
|
||||
|
||||
|
@ -254,7 +267,7 @@ The arguments passed to the `.render()` method are:
|
|||
|
||||
The request data, as set by the `Response()` instantiation.
|
||||
|
||||
### `media_type=None`
|
||||
### `accepted_media_type=None`
|
||||
|
||||
Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.
|
||||
|
||||
|
@ -270,7 +283,7 @@ By default this will include the following keys: `view`, `request`, `response`,
|
|||
|
||||
The following is an example plaintext renderer that will return a response with the `data` parameter as the content of the response.
|
||||
|
||||
from django.utils.encoding import smart_unicode
|
||||
from django.utils.encoding import smart_text
|
||||
from rest_framework import renderers
|
||||
|
||||
|
||||
|
@ -278,8 +291,8 @@ The following is an example plaintext renderer that will return a response with
|
|||
media_type = 'text/plain'
|
||||
format = 'txt'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
return data.encode(self.charset)
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return smart_text(data, encoding=self.charset)
|
||||
|
||||
## Setting the character set
|
||||
|
||||
|
@ -290,7 +303,7 @@ By default renderer classes are assumed to be using the `UTF-8` encoding. To us
|
|||
format = 'txt'
|
||||
charset = 'iso-8859-1'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return data.encode(self.charset)
|
||||
|
||||
Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the `Response` class, with the `charset` attribute set on the renderer used to determine the encoding.
|
||||
|
@ -305,7 +318,7 @@ In some cases you may also want to set the `render_style` attribute to `'binary'
|
|||
charset = None
|
||||
render_style = 'binary'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return data
|
||||
|
||||
---
|
||||
|
@ -319,14 +332,14 @@ You can do some pretty flexible things using REST framework's renderers. Some e
|
|||
* Specify multiple types of HTML representation for API clients to use.
|
||||
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
|
||||
|
||||
## Varying behaviour by media type
|
||||
## Varying behavior by media type
|
||||
|
||||
In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
|
||||
|
||||
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 +411,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 +432,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,42 +461,42 @@ 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)
|
||||
## Microsoft Excel: XLSX (Binary Spreadsheet Endpoints)
|
||||
|
||||
XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-renderer-xlsx][drf-renderer-xlsx], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
|
||||
XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-excel][drf-excel], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
|
||||
|
||||
#### Installation & configuration
|
||||
|
||||
Install using pip.
|
||||
|
||||
$ pip install drf-renderer-xlsx
|
||||
$ pip install drf-excel
|
||||
|
||||
Modify your REST framework settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
...
|
||||
|
||||
'DEFAULT_RENDERER_CLASSES': (
|
||||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
'drf_renderer_xlsx.renderers.XLSXRenderer',
|
||||
),
|
||||
'drf_excel.renderers.XLSXRenderer',
|
||||
],
|
||||
}
|
||||
|
||||
To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the `Content-Disposition` header. If no filename is provided, it will default to `export.xlsx`. For example:
|
||||
|
||||
from rest_framework.viewsets import ReadOnlyModelViewSet
|
||||
from drf_renderer_xlsx.mixins import XLSXFileMixin
|
||||
from drf_renderer_xlsx.renderers import XLSXRenderer
|
||||
from drf_excel.mixins import XLSXFileMixin
|
||||
from drf_excel.renderers import XLSXRenderer
|
||||
|
||||
from .models import MyExampleModel
|
||||
from .serializers import MyExampleSerializer
|
||||
|
@ -491,7 +504,7 @@ To avoid having a file streamed without a filename (which the browser will often
|
|||
class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
|
||||
queryset = MyExampleModel.objects.all()
|
||||
serializer_class = MyExampleSerializer
|
||||
renderer_classes = (XLSXRenderer,)
|
||||
renderer_classes = [XLSXRenderer]
|
||||
filename = 'my_export.xlsx'
|
||||
|
||||
## CSV
|
||||
|
@ -500,7 +513,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
|||
|
||||
## UltraJSON
|
||||
|
||||
[UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Jacob Haslehurst][hzy] maintains the [drf-ujson-renderer][drf-ujson-renderer] package which implements JSON rendering using the UJSON package.
|
||||
[UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Adam Mertz][Amertz08] maintains [drf_ujson2][drf_ujson2], a fork of the now unmaintained [drf-ujson-renderer][drf-ujson-renderer], which implements JSON rendering using the UJSON package.
|
||||
|
||||
## CamelCase JSON
|
||||
|
||||
|
@ -515,7 +528,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
|||
[Rest Framework Latex] provides a renderer that outputs PDFs using Laulatex. It is maintained by [Pebble (S/F Software)][mypebble].
|
||||
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/stable/template-response/#the-rendering-process
|
||||
[cite]: https://docs.djangoproject.com/en/stable/ref/template-response/#the-rendering-process
|
||||
[conneg]: content-negotiation.md
|
||||
[html-and-forms]: ../topics/html-and-forms.md
|
||||
[browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
|
||||
|
@ -534,9 +547,9 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
|||
[messagepack]: https://msgpack.org/
|
||||
[juanriaza]: https://github.com/juanriaza
|
||||
[mjumbewu]: https://github.com/mjumbewu
|
||||
[flipperpa]: https://githuc.com/flipperpa
|
||||
[flipperpa]: https://github.com/flipperpa
|
||||
[wharton]: https://github.com/wharton
|
||||
[drf-renderer-xlsx]: https://github.com/wharton/drf-renderer-xlsx
|
||||
[drf-excel]: https://github.com/wharton/drf-excel
|
||||
[vbabiy]: https://github.com/vbabiy
|
||||
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
|
||||
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
|
||||
|
@ -544,8 +557,9 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
|||
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
|
||||
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
|
||||
[ultrajson]: https://github.com/esnme/ultrajson
|
||||
[hzy]: https://github.com/hzy
|
||||
[Amertz08]: https://github.com/Amertz08
|
||||
[drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer
|
||||
[drf_ujson2]: https://github.com/Amertz08/drf_ujson2
|
||||
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
|
||||
[Django REST Pandas]: https://github.com/wq/django-rest-pandas
|
||||
[Pandas]: https://pandas.pydata.org/
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: request.py
|
||||
---
|
||||
source:
|
||||
- request.py
|
||||
---
|
||||
|
||||
# Requests
|
||||
|
||||
|
@ -20,7 +23,7 @@ REST framework's Request objects provide flexible request parsing that allows yo
|
|||
|
||||
* It includes all parsed content, including *file and non-file* inputs.
|
||||
* It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests.
|
||||
* It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.
|
||||
* It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming [JSON data] similarly to how you handle incoming [form data].
|
||||
|
||||
For more details see the [parsers documentation].
|
||||
|
||||
|
@ -46,7 +49,7 @@ If a client sends a request with a content-type that cannot be parsed then a `Un
|
|||
|
||||
# Content negotiation
|
||||
|
||||
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different 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 behavior such as selecting a different serialization schemes for different media types.
|
||||
|
||||
## .accepted_renderer
|
||||
|
||||
|
@ -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 instead assume that the request object does not have a `.user` or `.auth` property. The authenticator will need to be fixed.
|
||||
**Note:** You may see a `WrappedAttributeError` raised when calling the `.user` or `.auth` properties. These errors originate from an authenticator as a standard `AttributeError`, however it's necessary that they be re-raised as a different exception type in order to prevent them from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from the authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. The authenticator will need to be fixed.
|
||||
|
||||
---
|
||||
|
||||
|
@ -133,5 +136,7 @@ Note that due to implementation reasons the `Request` class does not inherit fro
|
|||
|
||||
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
|
||||
[parsers documentation]: parsers.md
|
||||
[JSON data]: parsers.md#jsonparser
|
||||
[form data]: parsers.md#formparser
|
||||
[authentication documentation]: authentication.md
|
||||
[browser enhancements documentation]: ../topics/browser-enhancements.md
|
||||
|
|
|
@ -1,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
|
||||
|
||||
|
@ -29,16 +32,16 @@ You should **include the request as a keyword argument** to the function, for ex
|
|||
|
||||
from rest_framework.reverse import reverse
|
||||
from rest_framework.views import APIView
|
||||
from django.utils.timezone import now
|
||||
from django.utils.timezone import now
|
||||
|
||||
class APIRootView(APIView):
|
||||
def get(self, request):
|
||||
year = now().year
|
||||
data = {
|
||||
...
|
||||
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
||||
class APIRootView(APIView):
|
||||
def get(self, request):
|
||||
year = now().year
|
||||
data = {
|
||||
...
|
||||
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
||||
}
|
||||
return Response(data)
|
||||
return Response(data)
|
||||
|
||||
## reverse_lazy
|
||||
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: routers.py
|
||||
---
|
||||
source:
|
||||
- routers.py
|
||||
---
|
||||
|
||||
# Routers
|
||||
|
||||
|
@ -60,7 +63,7 @@ For example, you can append `router.urls` to a list of existing views...
|
|||
router.register(r'accounts', AccountViewSet)
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
|
||||
path('forgot-password/', ForgotPasswordFormView.as_view()),
|
||||
]
|
||||
|
||||
urlpatterns += router.urls
|
||||
|
@ -68,22 +71,22 @@ For example, you can append `router.urls` to a list of existing views...
|
|||
Alternatively you can use Django's `include` function, like so...
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
|
||||
url(r'^', include(router.urls)),
|
||||
path('forgot-password', ForgotPasswordFormView.as_view()),
|
||||
path('', include(router.urls)),
|
||||
]
|
||||
|
||||
You may use `include` with an application namespace:
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
|
||||
url(r'^api/', include((router.urls, 'app_name'))),
|
||||
path('forgot-password/', ForgotPasswordFormView.as_view()),
|
||||
path('api/', include((router.urls, 'app_name'))),
|
||||
]
|
||||
|
||||
Or both an application and instance namespace:
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
|
||||
url(r'^api/', include((router.urls, 'app_name'), namespace='instance_name')),
|
||||
path('forgot-password/', ForgotPasswordFormView.as_view()),
|
||||
path('api/', include((router.urls, 'app_name'), namespace='instance_name')),
|
||||
]
|
||||
|
||||
See Django's [URL namespaces docs][url-namespace-docs] and the [`include` API reference][include-api-reference] for more details.
|
||||
|
@ -335,5 +338,5 @@ The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions
|
|||
[drf-extensions-nested-viewsets]: https://chibisov.github.io/drf-extensions/docs/#nested-routes
|
||||
[drf-extensions-collection-level-controllers]: https://chibisov.github.io/drf-extensions/docs/#collection-level-controllers
|
||||
[drf-extensions-customizable-endpoint-names]: https://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name
|
||||
[url-namespace-docs]: https://docs.djangoproject.com/en/1.11/topics/http/urls/#url-namespaces
|
||||
[include-api-reference]: https://docs.djangoproject.com/en/2.0/ref/urls/#include
|
||||
[url-namespace-docs]: https://docs.djangoproject.com/en/4.0/topics/http/urls/#url-namespaces
|
||||
[include-api-reference]: https://docs.djangoproject.com/en/4.0/ref/urls/#include
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: serializers.py
|
||||
---
|
||||
source:
|
||||
- serializers.py
|
||||
---
|
||||
|
||||
# Serializers
|
||||
|
||||
|
@ -18,7 +21,7 @@ Let's start by creating a simple object we can use for example purposes:
|
|||
|
||||
from datetime import datetime
|
||||
|
||||
class Comment(object):
|
||||
class Comment:
|
||||
def __init__(self, email, content, created=None):
|
||||
self.email = email
|
||||
self.content = content
|
||||
|
@ -113,7 +116,7 @@ Calling `.save()` will either create a new instance, or update an existing insta
|
|||
# .save() will update the existing `comment` instance.
|
||||
serializer = CommentSerializer(comment, data=data)
|
||||
|
||||
Both the `.create()` and `.update()` methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.
|
||||
Both the `.create()` and `.update()` methods are optional. You can implement either none, one, or both of them, depending on the use-case for your serializer class.
|
||||
|
||||
#### Passing additional attributes to `.save()`
|
||||
|
||||
|
@ -158,7 +161,7 @@ Each key in the dictionary will be the field name, and the values will be lists
|
|||
|
||||
When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.
|
||||
|
||||
#### Raising an exception on invalid data
|
||||
#### Raising an exception on invalid data
|
||||
|
||||
The `.is_valid()` method takes an optional `raise_exception` flag that will cause it to raise a `serializers.ValidationError` exception if there are validation errors.
|
||||
|
||||
|
@ -235,10 +238,12 @@ Serializer classes can also include reusable validators that are applied to the
|
|||
|
||||
class Meta:
|
||||
# Each room only has one event per day.
|
||||
validators = UniqueTogetherValidator(
|
||||
queryset=Event.objects.all(),
|
||||
fields=['room_number', 'date']
|
||||
)
|
||||
validators = [
|
||||
UniqueTogetherValidator(
|
||||
queryset=Event.objects.all(),
|
||||
fields=['room_number', 'date']
|
||||
)
|
||||
]
|
||||
|
||||
For more information see the [validators documentation](validators.md).
|
||||
|
||||
|
@ -246,7 +251,7 @@ For more information see the [validators documentation](validators.md).
|
|||
|
||||
When passing an initial object or queryset to a serializer instance, the object will be made available as `.instance`. If no initial object is passed then the `.instance` attribute will be `None`.
|
||||
|
||||
When passing data to a serializer instance, the unmodified data will be made available as `.initial_data`. If the data keyword argument is not passed then the `.initial_data` attribute will not exist.
|
||||
When passing data to a serializer instance, the unmodified data will be made available as `.initial_data`. If the `data` keyword argument is not passed then the `.initial_data` attribute will not exist.
|
||||
|
||||
## Partial updates
|
||||
|
||||
|
@ -277,7 +282,7 @@ If a nested representation may optionally accept the `None` value you should pas
|
|||
content = serializers.CharField(max_length=200)
|
||||
created = serializers.DateTimeField()
|
||||
|
||||
Similarly if a nested representation should be a list of items, you should pass the `many=True` flag to the nested serialized.
|
||||
Similarly if a nested representation should be a list of items, you should pass the `many=True` flag to the nested serializer.
|
||||
|
||||
class CommentSerializer(serializers.Serializer):
|
||||
user = UserSerializer(required=False)
|
||||
|
@ -308,7 +313,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')
|
||||
|
@ -330,7 +335,7 @@ Here's an example for an `.update()` method on our previous `UserSerializer` cla
|
|||
def update(self, instance, validated_data):
|
||||
profile_data = validated_data.pop('profile')
|
||||
# Unless the application properly enforces that this field is
|
||||
# always set, the follow could raise a `DoesNotExist`, which
|
||||
# always set, the following could raise a `DoesNotExist`, which
|
||||
# would need to be handled.
|
||||
profile = instance.profile
|
||||
|
||||
|
@ -379,8 +384,8 @@ This manager class now more nicely encapsulates that user instances and profile
|
|||
def create(self, validated_data):
|
||||
return User.objects.create(
|
||||
username=validated_data['username'],
|
||||
email=validated_data['email']
|
||||
is_premium_member=validated_data['profile']['is_premium_member']
|
||||
email=validated_data['email'],
|
||||
is_premium_member=validated_data['profile']['is_premium_member'],
|
||||
has_support_contract=validated_data['profile']['has_support_contract']
|
||||
)
|
||||
|
||||
|
@ -438,7 +443,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 +472,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 +490,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 +507,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.
|
||||
|
@ -519,6 +524,7 @@ You can add extra fields to a `ModelSerializer` or override the default fields b
|
|||
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ['url', 'groups']
|
||||
|
||||
Extra fields can correspond to any property or callable on the model.
|
||||
|
||||
|
@ -531,8 +537,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 +566,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 +578,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.
|
||||
|
@ -586,15 +594,15 @@ The ModelSerializer class also exposes an API that you can override in order to
|
|||
|
||||
Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.
|
||||
|
||||
### `.serializer_field_mapping`
|
||||
### `serializer_field_mapping`
|
||||
|
||||
A mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class.
|
||||
A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
|
||||
|
||||
### `.serializer_related_field`
|
||||
### `serializer_related_field`
|
||||
|
||||
This property should be the serializer field class, that is used for relational fields by default.
|
||||
|
||||
For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`.
|
||||
For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`.
|
||||
|
||||
For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`.
|
||||
|
||||
|
@ -614,21 +622,21 @@ Defaults to `serializers.ChoiceField`
|
|||
|
||||
The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`.
|
||||
|
||||
### `.build_standard_field(self, field_name, model_field)`
|
||||
### `build_standard_field(self, field_name, model_field)`
|
||||
|
||||
Called to generate a serializer field that maps to a standard model field.
|
||||
|
||||
The default implementation returns a serializer class based on the `serializer_field_mapping` attribute.
|
||||
|
||||
### `.build_relational_field(self, field_name, relation_info)`
|
||||
### `build_relational_field(self, field_name, relation_info)`
|
||||
|
||||
Called to generate a serializer field that maps to a relational model field.
|
||||
|
||||
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.
|
||||
|
||||
### `.build_nested_field(self, field_name, relation_info, nested_depth)`
|
||||
### `build_nested_field(self, field_name, relation_info, nested_depth)`
|
||||
|
||||
Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set.
|
||||
|
||||
|
@ -638,17 +646,17 @@ The `nested_depth` will be the value of the `depth` option, minus one.
|
|||
|
||||
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
||||
|
||||
### `.build_property_field(self, field_name, model_class)`
|
||||
### `build_property_field(self, field_name, model_class)`
|
||||
|
||||
Called to generate a serializer field that maps to a property or zero-argument method on the model class.
|
||||
|
||||
The default implementation returns a `ReadOnlyField` class.
|
||||
|
||||
### `.build_url_field(self, field_name, model_class)`
|
||||
### `build_url_field(self, field_name, model_class)`
|
||||
|
||||
Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class.
|
||||
|
||||
### `.build_unknown_field(self, field_name, model_class)`
|
||||
### `build_unknown_field(self, field_name, model_class)`
|
||||
|
||||
Called when the field name did not map to any model field or model property.
|
||||
The default implementation raises an error, although subclasses may customize this behavior.
|
||||
|
@ -668,7 +676,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 +708,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 +730,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']
|
||||
|
||||
---
|
||||
|
||||
|
@ -748,6 +756,14 @@ The following argument can also be passed to a `ListSerializer` field or a seria
|
|||
|
||||
This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
||||
|
||||
### `max_length`
|
||||
|
||||
This is `None` by default, but can be set to a positive integer if you want to validates that the list contains no more than this number of elements.
|
||||
|
||||
### `min_length`
|
||||
|
||||
This is `None` by default, but can be set to a positive integer if you want to validates that the list contains no fewer than this number of elements.
|
||||
|
||||
### Customizing `ListSerializer` behavior
|
||||
|
||||
There *are* a few use cases when you might want to customize the `ListSerializer` behavior. For example:
|
||||
|
@ -870,7 +886,7 @@ Because this class provides the same interface as the `Serializer` class, you ca
|
|||
|
||||
The only difference you'll notice when doing so is the `BaseSerializer` classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.
|
||||
|
||||
##### Read-only `BaseSerializer` classes
|
||||
#### Read-only `BaseSerializer` classes
|
||||
|
||||
To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model:
|
||||
|
||||
|
@ -882,10 +898,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:
|
||||
|
@ -894,7 +910,7 @@ We can now use this class to serialize single `HighScore` instances:
|
|||
def high_score(request, pk):
|
||||
instance = HighScore.objects.get(pk=pk)
|
||||
serializer = HighScoreSerializer(instance)
|
||||
return Response(serializer.data)
|
||||
return Response(serializer.data)
|
||||
|
||||
Or use it to serialize multiple instances:
|
||||
|
||||
|
@ -902,9 +918,9 @@ Or use it to serialize multiple instances:
|
|||
def all_high_scores(request):
|
||||
queryset = HighScore.objects.order_by('-score')
|
||||
serializer = HighScoreSerializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
return Response(serializer.data)
|
||||
|
||||
##### Read-write `BaseSerializer` classes
|
||||
#### Read-write `BaseSerializer` classes
|
||||
|
||||
To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `serializers.ValidationError` if the supplied data is in an incorrect format.
|
||||
|
||||
|
@ -933,17 +949,17 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
|
|||
'player_name': 'May not be more than 10 characters.'
|
||||
})
|
||||
|
||||
# Return the validated values. This will be available as
|
||||
# the `.validated_data` property.
|
||||
# Return the validated values. This will be available as
|
||||
# the `.validated_data` property.
|
||||
return {
|
||||
'score': int(score),
|
||||
'player_name': player_name
|
||||
}
|
||||
|
||||
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):
|
||||
|
@ -953,17 +969,18 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
|
|||
|
||||
The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.
|
||||
|
||||
The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
|
||||
The following class is an example of a generic serializer that can handle coercing arbitrary complex objects into primitive representations.
|
||||
|
||||
class ObjectSerializer(serializers.BaseSerializer):
|
||||
"""
|
||||
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 +1003,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,11 +1021,11 @@ 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 modify the representation style. For example:
|
||||
May be overridden in order to modify the representation style. For example:
|
||||
|
||||
def to_representation(self, instance):
|
||||
"""Convert `username` to lowercase."""
|
||||
|
@ -1015,7 +1033,7 @@ May be overridden in order modify the representation style. For example:
|
|||
ret['username'] = ret['username'].lower()
|
||||
return ret
|
||||
|
||||
#### ``.to_internal_value(self, data)``
|
||||
#### ``to_internal_value(self, data)``
|
||||
|
||||
Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
|
||||
|
||||
|
@ -1078,7 +1096,7 @@ For example, if you wanted to be able to set which fields should be used by a se
|
|||
fields = kwargs.pop('fields', None)
|
||||
|
||||
# Instantiate the superclass normally
|
||||
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
if fields is not None:
|
||||
# Drop any fields that are not specified in the `fields` argument.
|
||||
|
@ -1092,7 +1110,7 @@ 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))
|
||||
{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}
|
||||
|
@ -1169,6 +1187,11 @@ The [html-json-forms][html-json-forms] package provides an algorithm and seriali
|
|||
|
||||
The [drf-writable-nested][drf-writable-nested] package provides writable nested model serializer which allows to create/update models with nested related data.
|
||||
|
||||
## DRF Encrypt Content
|
||||
|
||||
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
|
||||
|
||||
|
||||
[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/
|
||||
|
@ -1190,3 +1213,4 @@ The [drf-writable-nested][drf-writable-nested] package provides writable nested
|
|||
[drf-serializer-extensions]: https://github.com/evenicoulddoit/django-rest-framework-serializer-extensions
|
||||
[djangorestframework-queryfields]: https://djangorestframework-queryfields.readthedocs.io/
|
||||
[drf-writable-nested]: https://github.com/beda-software/drf-writable-nested
|
||||
[drf-encrypt-content]: https://github.com/oguzhancelikarslan/drf-encrypt-content
|
||||
|
|
|
@ -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
|
||||
|
@ -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
|
||||
|
||||
|
@ -98,7 +101,7 @@ Default: `'rest_framework.negotiation.DefaultContentNegotiation'`
|
|||
|
||||
A view inspector class that will be used for schema generation.
|
||||
|
||||
Default: `'rest_framework.schemas.AutoSchema'`
|
||||
Default: `'rest_framework.schemas.openapi.AutoSchema'`
|
||||
|
||||
---
|
||||
|
||||
|
@ -106,32 +109,19 @@ Default: `'rest_framework.schemas.AutoSchema'`
|
|||
|
||||
*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
|
||||
|
||||
|
@ -139,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 has been removed.**
|
||||
|
||||
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`.
|
||||
|
@ -235,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'
|
||||
)
|
||||
]
|
||||
|
||||
---
|
||||
|
||||
|
@ -404,7 +374,7 @@ This should be a function with the following signature:
|
|||
|
||||
If the view instance inherits `ViewSet`, it may have been initialized with several optional arguments:
|
||||
|
||||
* `name`: A name expliticly provided to a view in the viewset. Typically, this value should be used as-is when provided.
|
||||
* `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.
|
||||
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: status.py
|
||||
---
|
||||
source:
|
||||
- status.py
|
||||
---
|
||||
|
||||
# Status Codes
|
||||
|
||||
|
@ -20,13 +23,13 @@ The full set of HTTP status codes included in the `status` module is listed belo
|
|||
The module also includes a set of helper functions for testing if a status code is in a given range.
|
||||
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APITestCase
|
||||
from rest_framework.test import APITestCase
|
||||
|
||||
class ExampleTestCase(APITestCase):
|
||||
def test_url_root(self):
|
||||
url = reverse('index')
|
||||
response = self.client.get(url)
|
||||
self.assertTrue(status.is_success(response.status_code))
|
||||
class ExampleTestCase(APITestCase):
|
||||
def test_url_root(self):
|
||||
url = reverse('index')
|
||||
response = self.client.get(url)
|
||||
self.assertTrue(status.is_success(response.status_code))
|
||||
|
||||
|
||||
For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616]
|
||||
|
@ -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
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: test.py
|
||||
---
|
||||
source:
|
||||
- test.py
|
||||
---
|
||||
|
||||
# Testing
|
||||
|
||||
|
@ -218,7 +221,7 @@ If you're using `RequestsClient` you'll want to ensure that test setup, and resu
|
|||
## Headers & Authentication
|
||||
|
||||
Custom headers and authentication credentials can be provided in the same way
|
||||
as [when using a standard `requests.Session` instance](http://docs.python-requests.org/en/master/user/advanced/#session-objects).
|
||||
as [when using a standard `requests.Session` instance][session_objects].
|
||||
|
||||
from requests.auth import HTTPBasicAuth
|
||||
|
||||
|
@ -231,7 +234,7 @@ If you're using `SessionAuthentication` then you'll need to include a CSRF token
|
|||
for any `POST`, `PUT`, `PATCH` or `DELETE` requests.
|
||||
|
||||
You can do so by following the same flow that a JavaScript based client would use.
|
||||
First make a `GET` request in order to obtain a CRSF token, then present that
|
||||
First, make a `GET` request in order to obtain a CSRF token, then present that
|
||||
token in the following request.
|
||||
|
||||
For example...
|
||||
|
@ -256,7 +259,7 @@ With careful usage both the `RequestsClient` and the `CoreAPIClient` provide
|
|||
the ability to write test cases that can run either in development, or be run
|
||||
directly against your staging server or production environment.
|
||||
|
||||
Using this style to create basic tests of a few core piece of functionality is
|
||||
Using this style to create basic tests of a few core pieces of functionality is
|
||||
a powerful way to validate your live service. Doing so may require some careful
|
||||
attention to setup and teardown to ensure that the tests run in a way that they
|
||||
do not directly affect customer data.
|
||||
|
@ -296,7 +299,7 @@ similar way as with `RequestsClient`.
|
|||
|
||||
# API Test cases
|
||||
|
||||
REST framework includes the following test case classes, that mirror the existing Django test case classes, but use `APIClient` instead of Django's default `Client`.
|
||||
REST framework includes the following test case classes, that mirror the existing [Django's test case classes][provided_test_case_classes], but use `APIClient` instead of Django's default `Client`.
|
||||
|
||||
* `APISimpleTestCase`
|
||||
* `APITransactionTestCase`
|
||||
|
@ -399,15 +402,17 @@ 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]: https://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper
|
||||
[client]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#the-test-client
|
||||
[requestfactory]: https://docs.djangoproject.com/en/stable/topics/testing/advanced/#django.test.client.RequestFactory
|
||||
[configuration]: #configuration
|
||||
[refresh_from_db_docs]: https://docs.djangoproject.com/en/1.11/ref/models/instances/#django.db.models.Model.refresh_from_db
|
||||
[refresh_from_db_docs]: https://docs.djangoproject.com/en/stable/ref/models/instances/#django.db.models.Model.refresh_from_db
|
||||
[session_objects]: https://requests.readthedocs.io/en/master/user/advanced/#session-objects
|
||||
[provided_test_case_classes]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#provided-test-case-classes
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: throttling.py
|
||||
---
|
||||
source:
|
||||
- throttling.py
|
||||
---
|
||||
|
||||
# Throttling
|
||||
|
||||
|
@ -16,6 +19,10 @@ Multiple throttles can also be used if you want to impose both burst throttling
|
|||
|
||||
Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.
|
||||
|
||||
**The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins. In addition to this, the built-in throttling implementations are implemented using Django's cache framework, and use non-atomic operations to determine the request rate, which may sometimes result in some fuzziness.
|
||||
|
||||
The application-level throttling provided by REST framework is intended for implementing policies such as different business tiers and basic protections against service over-use.**
|
||||
|
||||
## How throttling is determined
|
||||
|
||||
As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
|
||||
|
@ -28,10 +35,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'
|
||||
|
@ -43,12 +50,12 @@ The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `mi
|
|||
You can also set the throttling policy on a per-view or per-viewset basis,
|
||||
using the `APIView` class-based views.
|
||||
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.throttling import UserRateThrottle
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.views import APIView
|
||||
|
||||
class ExampleView(APIView):
|
||||
throttle_classes = (UserRateThrottle,)
|
||||
throttle_classes = [UserRateThrottle]
|
||||
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
|
@ -56,7 +63,7 @@ using the `APIView` class-based views.
|
|||
}
|
||||
return Response(content)
|
||||
|
||||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
If you're using the `@api_view` decorator with function based views you can use the following decorator.
|
||||
|
||||
@api_view(['GET'])
|
||||
@throttle_classes([UserRateThrottle])
|
||||
|
@ -66,7 +73,17 @@ Or, if you're using the `@api_view` decorator with function based views.
|
|||
}
|
||||
return Response(content)
|
||||
|
||||
## How clients are identified
|
||||
It's also possible to set throttle classes for routes that are created using the `@action` decorator.
|
||||
Throttle classes set in this way will override any viewset level class settings.
|
||||
|
||||
@action(detail=True, methods=["post"], throttle_classes=[UserRateThrottle])
|
||||
def example_adhoc_method(request, pk=None):
|
||||
content = {
|
||||
'status': 'request was permitted'
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
## How clients are identified
|
||||
|
||||
The `X-Forwarded-For` HTTP header and `REMOTE_ADDR` WSGI variable are used to uniquely identify client IP addresses for throttling. If the `X-Forwarded-For` header is present then it will be used, otherwise the value of the `REMOTE_ADDR` variable from the WSGI environment will be used.
|
||||
|
||||
|
@ -74,7 +91,7 @@ If you need to strictly identify unique client IP addresses, you'll need to firs
|
|||
|
||||
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
|
||||
|
||||
|
@ -89,6 +106,12 @@ If you need to use a cache other than `'default'`, you can do so by creating a c
|
|||
|
||||
You'll need to remember to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute.
|
||||
|
||||
## A note on concurrency
|
||||
|
||||
The built-in throttle implementations are open to [race conditions][race], so under high concurrency they may allow a few extra requests through.
|
||||
|
||||
If your project relies on guaranteeing the number of requests during concurrent requests, you will need to implement your own throttle class. See [issue #5181][gh5181] for more details.
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
@ -126,10 +149,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'
|
||||
|
@ -161,9 +184,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'
|
||||
|
@ -194,6 +217,8 @@ The following is an example of a rate throttle, that will randomly throttle 1 in
|
|||
|
||||
[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
|
||||
[gh5181]: https://github.com/encode/django-rest-framework/issues/5181
|
||||
[race]: https://en.wikipedia.org/wiki/Race_condition#Data_race
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: validators.py
|
||||
---
|
||||
source:
|
||||
- validators.py
|
||||
---
|
||||
|
||||
# Validators
|
||||
|
||||
|
@ -17,7 +20,7 @@ Validation in Django REST framework serializers is handled a little differently
|
|||
With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
|
||||
|
||||
* It introduces a proper separation of concerns, making your code behavior more obvious.
|
||||
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
|
||||
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
|
||||
* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.
|
||||
|
||||
When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using `Serializer` classes instead, then you need to define the validation rules explicitly.
|
||||
|
@ -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.
|
||||
|
||||
---
|
||||
|
||||
|
@ -207,7 +208,7 @@ by specifying an empty list for the serializer `Meta.validators` attribute.
|
|||
|
||||
By default "unique together" validation enforces that all fields be
|
||||
`required=True`. In some cases, you might want to explicit apply
|
||||
`required=False` to one of the fields, in which case the desired behaviour
|
||||
`required=False` to one of the fields, in which case the desired behavior
|
||||
of the validation is ambiguous.
|
||||
|
||||
In this case you will typically need to exclude the validator from the
|
||||
|
@ -217,11 +218,11 @@ 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')
|
||||
fields = ['client', 'date', 'amount']
|
||||
extra_kwargs = {'client': {'required': False}}
|
||||
validators = [] # Remove a default "unique together" constraint.
|
||||
|
||||
|
@ -237,7 +238,7 @@ In the case of update operations on *nested* serializers there's no way of
|
|||
applying this exclusion, because the instance is not available.
|
||||
|
||||
Again, you'll probably want to explicitly remove the validator from the
|
||||
serializer class, and write the code the for the validation constraint
|
||||
serializer class, and write the code for the validation constraint
|
||||
explicitly, in a `.validate()` method, or in the view.
|
||||
|
||||
## Debugging complex cases
|
||||
|
@ -281,7 +282,7 @@ to your `Serializer` subclass. This is documented in the
|
|||
|
||||
To write a class-based validator, use the `__call__` method. Class-based validators are useful as they allow you to parameterize and reuse behavior.
|
||||
|
||||
class MultipleOf(object):
|
||||
class MultipleOf:
|
||||
def __init__(self, base):
|
||||
self.base = base
|
||||
|
||||
|
@ -290,13 +291,17 @@ To write a class-based validator, use the `__call__` method. Class-based validat
|
|||
message = 'This field must be a multiple of %d.' % self.base
|
||||
raise serializers.ValidationError(message)
|
||||
|
||||
#### Using `set_context()`
|
||||
#### Accessing the context
|
||||
|
||||
In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a `set_context` method on a class-based validator.
|
||||
In some advanced cases you might want a validator to be passed the serializer
|
||||
field it is being used with as additional context. You can do so by setting
|
||||
a `requires_context = True` attribute on the validator. The `__call__` method
|
||||
will then be called with the `serializer_field`
|
||||
or `serializer` as an additional argument.
|
||||
|
||||
def set_context(self, serializer_field):
|
||||
# Determine if this is an update or a create operation.
|
||||
# In `__call__` we can then use that information to modify the validation behavior.
|
||||
self.is_update = serializer_field.parent.instance is not None
|
||||
requires_context = True
|
||||
|
||||
def __call__(self, value, serializer_field):
|
||||
...
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/ref/validators/
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: versioning.py
|
||||
---
|
||||
source:
|
||||
- versioning.py
|
||||
---
|
||||
|
||||
# Versioning
|
||||
|
||||
|
@ -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.
|
||||
|
|
|
@ -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):
|
||||
"""
|
||||
|
@ -142,6 +145,7 @@ REST framework also allows you to work with regular function based views. It pr
|
|||
The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
|
||||
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.response import Response
|
||||
|
||||
@api_view()
|
||||
def hello_world(request):
|
||||
|
@ -149,7 +153,7 @@ The core of this functionality is the `api_view` decorator, which takes a list o
|
|||
|
||||
This view will use the default renderers, parsers, authentication classes etc specified in the [settings].
|
||||
|
||||
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behaviour, specify which methods the view allows, like so:
|
||||
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so:
|
||||
|
||||
@api_view(['GET', 'POST'])
|
||||
def hello_world(request):
|
||||
|
@ -166,7 +170,7 @@ To override the default settings, REST framework provides a set of additional de
|
|||
from rest_framework.throttling import UserRateThrottle
|
||||
|
||||
class OncePerDayUserThrottle(UserRateThrottle):
|
||||
rate = '1/day'
|
||||
rate = '1/day'
|
||||
|
||||
@api_view(['GET'])
|
||||
@throttle_classes([OncePerDayUserThrottle])
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
source: viewsets.py
|
||||
---
|
||||
source:
|
||||
- viewsets.py
|
||||
---
|
||||
|
||||
# ViewSets
|
||||
|
||||
|
@ -113,7 +116,7 @@ During dispatch, the following attributes are available on the `ViewSet`.
|
|||
* `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`.
|
||||
* `description` - the display description for the individual view of a viewset.
|
||||
|
||||
You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
||||
You may inspect these attributes to adjust behavior based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
||||
|
||||
def get_permissions(self):
|
||||
"""
|
||||
|
@ -122,7 +125,7 @@ You may inspect these attributes to adjust behaviour based on the current action
|
|||
if self.action == 'list':
|
||||
permission_classes = [IsAuthenticated]
|
||||
else:
|
||||
permission_classes = [IsAdmin]
|
||||
permission_classes = [IsAdminUser]
|
||||
return [permission() for permission in permission_classes]
|
||||
|
||||
## Marking extra actions for routing
|
||||
|
@ -149,7 +152,7 @@ A more complete example of extra actions:
|
|||
user = self.get_object()
|
||||
serializer = PasswordSerializer(data=request.data)
|
||||
if serializer.is_valid():
|
||||
user.set_password(serializer.data['password'])
|
||||
user.set_password(serializer.validated_data['password'])
|
||||
user.save()
|
||||
return Response({'status': 'password set'})
|
||||
else:
|
||||
|
@ -168,11 +171,6 @@ A more complete example of extra actions:
|
|||
serializer = self.get_serializer(recent_users, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
The decorator can additionally take extra arguments that will be set for the routed view only. For example:
|
||||
|
||||
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])
|
||||
def set_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
The `action` decorator will route `GET` requests by default, but may also accept other HTTP methods by setting the `methods` argument. For example:
|
||||
|
||||
|
@ -180,7 +178,14 @@ The `action` decorator will route `GET` requests by default, but may also accept
|
|||
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/$`
|
||||
|
||||
The decorator allows you to override any viewset-level configuration such as `permission_classes`, `serializer_class`, `filter_backends`...:
|
||||
|
||||
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])
|
||||
def set_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
The two new actions will then be available at the urls `^users/{pk}/set_password/$` and `^users/{pk}/unset_password/$`. Use the `url_path` and `url_name` parameters to change the URL segment and the reverse URL name of the action.
|
||||
|
||||
To view all extra actions, call the `.get_extra_actions()` method.
|
||||
|
||||
|
@ -242,7 +247,7 @@ In order to use a `GenericViewSet` class you'll override the class and either mi
|
|||
|
||||
The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
|
||||
|
||||
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
|
||||
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
|
||||
|
||||
#### Example
|
||||
|
||||
|
@ -314,5 +319,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]: https://guides.rubyonrails.org/routing.html
|
||||
[cite]: https://guides.rubyonrails.org/action_controller_overview.html
|
||||
[routers]: routers.md
|
||||
|
|
|
@ -24,7 +24,7 @@ Notable features of this new release include:
|
|||
* Support for overriding how validation errors are handled by your API.
|
||||
* A metadata API that allows you to customize how `OPTIONS` requests are handled by your API.
|
||||
* A more compact JSON output with unicode style encoding turned on by default.
|
||||
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
|
||||
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
|
||||
|
||||
Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two [Kickstarter stretch goals](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.
|
||||
|
||||
|
@ -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,7 +384,7 @@ 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.
|
||||
|
||||
|
@ -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__'):
|
||||
|
@ -632,7 +632,7 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel
|
|||
|
||||
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
|
||||
|
||||
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...
|
||||
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behavior in a way that did not simply lookup the field value from the object. For example...
|
||||
|
||||
def field_to_native(self, obj, field_name):
|
||||
"""A custom read-only field that returns the class name."""
|
||||
|
@ -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.
|
||||
|
|
|
@ -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:
|
||||
|
||||
|
|
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]: funding.md
|
117
docs/community/3.11-announcement.md
Normal file
|
@ -0,0 +1,117 @@
|
|||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
# Django REST framework 3.11
|
||||
|
||||
The 3.11 release adds support for Django 3.0.
|
||||
|
||||
* Our supported Python versions are now: 3.5, 3.6, 3.7, and 3.8.
|
||||
* Our supported Django versions are now: 1.11, 2.0, 2.1, 2.2, and 3.0.
|
||||
|
||||
This release will be the last to support Python 3.5 or Django 1.11.
|
||||
|
||||
## OpenAPI Schema Generation Improvements
|
||||
|
||||
The OpenAPI schema generation continues to mature. Some highlights in 3.11
|
||||
include:
|
||||
|
||||
* Automatic mapping of Django REST Framework renderers and parsers into OpenAPI
|
||||
request and response media-types.
|
||||
* Improved mapping JSON schema mapping types, for example in HStoreFields, and
|
||||
with large integer values.
|
||||
* Porting of the old CoreAPI parsing of docstrings to form OpenAPI operation
|
||||
descriptions.
|
||||
|
||||
In this example view operation descriptions for the `get` and `post` methods will
|
||||
be extracted from the class docstring:
|
||||
|
||||
```python
|
||||
class DocStringExampleListView(APIView):
|
||||
"""
|
||||
get: A description of my GET operation.
|
||||
post: A description of my POST operation.
|
||||
"""
|
||||
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
...
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
...
|
||||
```
|
||||
|
||||
## Validator / Default Context
|
||||
|
||||
In some circumstances a Validator class or a Default class may need to access the serializer field with which it is called, or the `.context` with which the serializer was instantiated. In particular:
|
||||
|
||||
* Uniqueness validators need to be able to determine the name of the field to which they are applied, in order to run an appropriate database query.
|
||||
* The `CurrentUserDefault` needs to be able to determine the context with which the serializer was instantiated, in order to return the current user instance.
|
||||
|
||||
Previous our approach to this was that implementations could include a `set_context` method, which would be called prior to validation. However this approach had issues with potential race conditions. We have now move this approach into a pending deprecation state. It will continue to function, but will be escalated to a deprecated state in 3.12, and removed entirely in 3.13.
|
||||
|
||||
Instead, validators or defaults which require the serializer context, should include a `requires_context = True` attribute on the class.
|
||||
|
||||
The `__call__` method should then include an additional `serializer_field` argument.
|
||||
|
||||
Validator implementations will look like this:
|
||||
|
||||
```python
|
||||
class CustomValidator:
|
||||
requires_context = True
|
||||
|
||||
def __call__(self, value, serializer_field):
|
||||
...
|
||||
```
|
||||
|
||||
Default implementations will look like this:
|
||||
|
||||
```python
|
||||
class CustomDefault:
|
||||
requires_context = True
|
||||
|
||||
def __call__(self, serializer_field):
|
||||
...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Funding
|
||||
|
||||
REST framework is a *collaboratively funded project*. If you use
|
||||
REST framework commercially we strongly encourage you to invest in its
|
||||
continued development by **[signing up for a paid plan][funding]**.
|
||||
|
||||
*Every single sign-up helps us make REST framework long-term financially sustainable.*
|
||||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
<li><a href="https://software.esg-usa.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/esg-new-logo.png)">ESG</a></li>
|
||||
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
|
||||
<li><a href="https://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
|
||||
<li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless-plus-text.png)">Kloudless</a></li>
|
||||
<li><a href="https://lightsonsoftware.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/lightson-dark.png)">Lights On Software</a></li>
|
||||
<li><a href="https://retool.com/?utm_source=djangorest&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/retool-sidebar.png)">Retool</a></li>
|
||||
</ul>
|
||||
<div style="clear: both; padding-bottom: 20px;"></div>
|
||||
|
||||
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), and [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship).*
|
||||
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
169
docs/community/3.12-announcement.md
Normal file
|
@ -0,0 +1,169 @@
|
|||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
# Django REST framework 3.12
|
||||
|
||||
REST framework 3.12 brings a handful of refinements to the OpenAPI schema
|
||||
generation, plus support for Django's new database-agnostic `JSONField`,
|
||||
and some improvements to the `SearchFilter` class.
|
||||
|
||||
## Grouping operations with tags.
|
||||
|
||||
Open API schemas will now automatically include tags, based on the first element
|
||||
in the URL path.
|
||||
|
||||
For example...
|
||||
|
||||
Method | Path | Tags
|
||||
--------------------------------|-----------------|-------------
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']`
|
||||
`GET`, `POST` | `/users/` | `['users']`
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']`
|
||||
`GET`, `POST` | `/orders/` | `['orders']`
|
||||
|
||||
The tags used for a particular view may also be overridden...
|
||||
|
||||
```python
|
||||
class MyOrders(APIView):
|
||||
schema = AutoSchema(tags=['users', 'orders'])
|
||||
...
|
||||
```
|
||||
|
||||
See [the schema documentation](https://www.django-rest-framework.org/api-guide/schemas/#grouping-operations-with-tags) for more information.
|
||||
|
||||
## Customizing the operation ID.
|
||||
|
||||
REST framework automatically determines operation IDs to use in OpenAPI
|
||||
schemas. The latest version provides more control for overriding the behaviour
|
||||
used to generate the operation IDs.
|
||||
|
||||
See [the schema documentation](https://www.django-rest-framework.org/api-guide/schemas/#operationid) for more information.
|
||||
|
||||
## Support for OpenAPI components.
|
||||
|
||||
In order to output more graceful OpenAPI schemes, REST framework 3.12 now
|
||||
defines components in the schema, and then references them inside request
|
||||
and response objects. This is in contrast with the previous approach, which
|
||||
fully expanded the request and response bodies for each operation.
|
||||
|
||||
The names used for a component default to using the serializer class name, [but
|
||||
may be overridden if needed](https://www.django-rest-framework.org/api-guide/schemas/#components
|
||||
)...
|
||||
|
||||
```python
|
||||
class MyOrders(APIView):
|
||||
schema = AutoSchema(component_name="OrderDetails")
|
||||
```
|
||||
|
||||
## More Public API
|
||||
|
||||
Many methods on the `AutoSchema` class have now been promoted to public API,
|
||||
allowing you to more fully customize the schema generation. The following methods
|
||||
are now available for overriding...
|
||||
|
||||
* `get_path_parameters`
|
||||
* `get_pagination_parameters`
|
||||
* `get_filter_parameters`
|
||||
* `get_request_body`
|
||||
* `get_responses`
|
||||
* `get_serializer`
|
||||
* `get_paginator`
|
||||
* `map_serializer`
|
||||
* `map_field`
|
||||
* `map_choice_field`
|
||||
* `map_field_validators`
|
||||
* `allows_filters`.
|
||||
|
||||
See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#per-view-customization)
|
||||
for details on using custom `AutoSchema` subclasses.
|
||||
|
||||
## Support for JSONField.
|
||||
|
||||
Django 3.1 deprecated the existing `django.contrib.postgres.fields.JSONField`
|
||||
in favour of a new database-agnositic `JSONField`.
|
||||
|
||||
REST framework 3.12 now supports this new model field, and `ModelSerializer`
|
||||
classes will correctly map the model field.
|
||||
|
||||
## SearchFilter improvements
|
||||
|
||||
There are a couple of significant improvements to the `SearchFilter` class.
|
||||
|
||||
### Nested searches against JSONField and HStoreField
|
||||
|
||||
The class now supports nested search within `JSONField` and `HStoreField`, using
|
||||
the double underscore notation for traversing which element of the field the
|
||||
search should apply to.
|
||||
|
||||
```python
|
||||
class SitesSearchView(generics.ListAPIView):
|
||||
"""
|
||||
An API view to return a list of archaeological sites, optionally filtered
|
||||
by a search against the site name or location. (Location searches are
|
||||
matched against the region and country names.)
|
||||
"""
|
||||
queryset = Sites.objects.all()
|
||||
serializer_class = SitesSerializer
|
||||
filter_backends = [filters.SearchFilter]
|
||||
search_fields = ['site_name', 'location__region', 'location__country']
|
||||
```
|
||||
|
||||
### Searches against annotate fields
|
||||
|
||||
Django allows querysets to create additional virtual fields, using the `.annotate`
|
||||
method. We now support searching against annotate fields.
|
||||
|
||||
```python
|
||||
class PublisherSearchView(generics.ListAPIView):
|
||||
"""
|
||||
Search for publishers, optionally filtering the search against the average
|
||||
rating of all their books.
|
||||
"""
|
||||
queryset = Publisher.objects.annotate(avg_rating=Avg('book__rating'))
|
||||
serializer_class = PublisherSerializer
|
||||
filter_backends = [filters.SearchFilter]
|
||||
search_fields = ['avg_rating']
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Funding
|
||||
|
||||
REST framework is a *collaboratively funded project*. If you use
|
||||
REST framework commercially we strongly encourage you to invest in its
|
||||
continued development by **[signing up for a paid plan][funding]**.
|
||||
|
||||
*Every single sign-up helps us make REST framework long-term financially sustainable.*
|
||||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
<li><a href="https://software.esg-usa.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/esg-new-logo.png)">ESG</a></li>
|
||||
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
|
||||
<li><a href="https://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
|
||||
<li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless-plus-text.png)">Kloudless</a></li>
|
||||
<li><a href="https://lightsonsoftware.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/lightson-dark.png)">Lights On Software</a></li>
|
||||
<li><a href="https://retool.com/?utm_source=djangorest&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/retool-sidebar.png)">Retool</a></li>
|
||||
</ul>
|
||||
<div style="clear: both; padding-bottom: 20px;"></div>
|
||||
|
||||
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), and [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship).*
|
||||
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
55
docs/community/3.13-announcement.md
Normal file
|
@ -0,0 +1,55 @@
|
|||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
# Django REST framework 3.13
|
||||
|
||||
## Django 4.0 support
|
||||
|
||||
The latest release now fully supports Django 4.0.
|
||||
|
||||
Our requirements are now:
|
||||
|
||||
* Python 3.6+
|
||||
* Django 4.0, 3.2, 3.1, 2.2 (LTS)
|
||||
|
||||
## Fields arguments are now keyword-only
|
||||
|
||||
When instantiating fields on serializers, you should always use keyword arguments,
|
||||
such as `serializers.CharField(max_length=200)`. This has always been the case,
|
||||
and all the examples that we have in the documentation use keyword arguments,
|
||||
rather than positional arguments.
|
||||
|
||||
From REST framework 3.13 onwards, this is now *explicitly enforced*.
|
||||
|
||||
The most feasible cases where users might be accidentally omitting the keyword arguments
|
||||
are likely in the composite fields, `ListField` and `DictField`. For instance...
|
||||
|
||||
```python
|
||||
aliases = serializers.ListField(serializers.CharField())
|
||||
```
|
||||
|
||||
They must now use the more explicit keyword argument style...
|
||||
|
||||
```python
|
||||
aliases = serializers.ListField(child=serializers.CharField())
|
||||
```
|
||||
|
||||
This change has been made because using positional arguments here *does not* result in the expected behaviour.
|
||||
|
||||
See Pull Request [#7632](https://github.com/encode/django-rest-framework/pull/7632) for more details.
|
62
docs/community/3.14-announcement.md
Normal file
|
@ -0,0 +1,62 @@
|
|||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
# Django REST framework 3.14
|
||||
|
||||
## Django 4.1 support
|
||||
|
||||
The latest release now fully supports Django 4.1, and drops support for Django 2.2.
|
||||
|
||||
Our requirements are now:
|
||||
|
||||
* Python 3.6+
|
||||
* Django 4.1, 4.0, 3.2, 3.1, 3.0
|
||||
|
||||
## `raise_exceptions` argument for `is_valid` is now keyword-only.
|
||||
|
||||
Calling `serializer_instance.is_valid(True)` is no longer acceptable syntax.
|
||||
If you'd like to use the `raise_exceptions` argument, you must use it as a
|
||||
keyword argument.
|
||||
|
||||
See Pull Request [#7952](https://github.com/encode/django-rest-framework/pull/7952) for more details.
|
||||
|
||||
## `ManyRelatedField` supports returning the default when the source attribute doesn't exist.
|
||||
|
||||
Previously, if you used a serializer field with `many=True` with a dot notated source field
|
||||
that didn't exist, it would raise an `AttributeError`. Now it will return the default or be
|
||||
skipped depending on the other arguments.
|
||||
|
||||
See Pull Request [#7574](https://github.com/encode/django-rest-framework/pull/7574) for more details.
|
||||
|
||||
|
||||
## Make Open API `get_reference` public.
|
||||
|
||||
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
|
||||
|
||||
## Change semantic of OR of two permission classes.
|
||||
|
||||
When OR-ing two permissions, the request has to pass either class's `has_permission() and has_object_permission()`.
|
||||
|
||||
Previously, both class's `has_permission()` was ignored when OR-ing two permissions together.
|
||||
|
||||
See Pull Request [#7522](https://github.com/encode/django-rest-framework/pull/7522) for more details.
|
||||
|
||||
## Minor fixes and improvements
|
||||
|
||||
There are a number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing.
|
|
@ -64,7 +64,7 @@ These are a little subtle and probably won't affect most users, but are worth un
|
|||
|
||||
### ManyToMany fields and blank=True
|
||||
|
||||
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
||||
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
||||
|
||||
As a follow-up to this we are now able to properly mirror the behavior of Django's `ModelForm` with respect to how many-to-many fields are validated.
|
||||
|
||||
|
|
|
@ -38,7 +38,7 @@ The AJAX based support for the browsable API means that there are a number of in
|
|||
|
||||
* To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.
|
||||
* The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class][accept-headers].
|
||||
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
|
||||
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
|
||||
|
||||
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.
|
||||
|
||||
|
|
|
@ -89,7 +89,7 @@ Name | Support | PyPI pa
|
|||
---------------------------------|-------------------------------------|--------------------------------
|
||||
[Core JSON][core-json] | Schema generation & client support. | Built-in support in `coreapi`.
|
||||
[Swagger / OpenAPI][swagger] | Schema generation & client support. | The `openapi-codec` package.
|
||||
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
|
||||
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
|
||||
[API Blueprint][api-blueprint] | Not yet available. | Not yet available.
|
||||
|
||||
---
|
||||
|
|
|
@ -69,7 +69,7 @@ schema_view = get_schema_view(
|
|||
)
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^swagger/$', schema_view),
|
||||
path('swagger/', schema_view),
|
||||
...
|
||||
]
|
||||
```
|
||||
|
@ -198,8 +198,8 @@ Make sure to include the view before your router urls. For example:
|
|||
schema_view = get_schema_view(title='Example API')
|
||||
|
||||
urlpatterns = [
|
||||
url('^$', schema_view),
|
||||
url(r'^', include(router.urls)),
|
||||
path('', schema_view),
|
||||
path('', include(router.urls)),
|
||||
]
|
||||
|
||||
### Schema path representations
|
||||
|
|
|
@ -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.
|
||||
|
||||
|
@ -73,7 +73,7 @@ To install the API documentation, you'll need to include it in your projects URL
|
|||
|
||||
urlpatterns = [
|
||||
...
|
||||
url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))
|
||||
path('docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))
|
||||
]
|
||||
|
||||
Once installed you should see something a little like this:
|
||||
|
|
|
@ -89,7 +89,7 @@ for a complete listing.
|
|||
|
||||
We're currently working towards moving to using [OpenAPI][openapi] as our default schema output. We'll also be revisiting our API documentation generation and client libraries.
|
||||
|
||||
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
|
||||
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
|
||||
|
||||
[funding]: funding.md
|
||||
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886
|
||||
|
|
|
@ -62,6 +62,7 @@ Here's an example of adding an OpenAPI schema to the URL conf:
|
|||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework.renderers import JSONOpenAPIRenderer
|
||||
from django.urls import path
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
|
@ -70,7 +71,7 @@ schema_view = get_schema_view(
|
|||
)
|
||||
|
||||
urlpatterns = [
|
||||
url('^schema.json$', schema_view),
|
||||
path('schema.json', schema_view),
|
||||
...
|
||||
]
|
||||
```
|
||||
|
@ -109,7 +110,7 @@ You can now compose permission classes using the and/or operators, `&` and `|`.
|
|||
For example...
|
||||
|
||||
```python
|
||||
permission_classes = [IsAuthenticated & (ReadOnly | IsAdmin)]
|
||||
permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)]
|
||||
```
|
||||
|
||||
If you're using custom permission classes then make sure that you are subclassing
|
||||
|
|
|
@ -6,6 +6,12 @@
|
|||
|
||||
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
|
||||
|
||||
---
|
||||
|
||||
**Note**: At this point in it's lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes.
|
||||
|
||||
---
|
||||
|
||||
## Community
|
||||
|
||||
The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
|
||||
|
@ -26,14 +32,13 @@ The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines f
|
|||
|
||||
# Issues
|
||||
|
||||
It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the [discussion group][google-group]. Feature requests, bug reports and other issues should be raised on the GitHub [issue tracker][issues].
|
||||
Our contribution process is that the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Please only raise an issue or pull request if you've been recommended to do so after discussion.
|
||||
|
||||
Some tips on good issue reporting:
|
||||
Some tips on good potential issue reporting:
|
||||
|
||||
* When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
|
||||
* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
|
||||
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
|
||||
* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.
|
||||
* Search the GitHub project page for related items, and make sure you're running the latest version of REST framework before reporting an issue.
|
||||
* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation. At this point in it's lifespan we consider Django REST framework to be essentially feature-complete.
|
||||
* Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.
|
||||
|
||||
## Triaging issues
|
||||
|
@ -54,20 +59,28 @@ To start developing on Django REST framework, first create a Fork from the
|
|||
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
|
||||
git clone https://github.com/YOUR-USERNAME/django-rest-framework
|
||||
|
||||
See GitHub's [_Fork a Repo_][how-to-fork] Guide for more help.
|
||||
|
||||
Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.
|
||||
You can check your contributions against these conventions each time you commit using the [pre-commit](https://pre-commit.com/) hooks, which we also run on CI.
|
||||
To set them up, first ensure you have the pre-commit tool installed, for example:
|
||||
|
||||
python -m pip install pre-commit
|
||||
|
||||
Then run:
|
||||
|
||||
pre-commit install
|
||||
|
||||
## Testing
|
||||
|
||||
To run the tests, clone the repository, and then:
|
||||
|
||||
# Setup the virtual environment
|
||||
virtualenv env
|
||||
python3 -m venv env
|
||||
source env/bin/activate
|
||||
pip install django
|
||||
pip install -e .
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Run the tests
|
||||
|
@ -79,18 +92,6 @@ Run using a more concise output style.
|
|||
|
||||
./runtests.py -q
|
||||
|
||||
Run the tests using a more concise output style, no coverage, no flake8.
|
||||
|
||||
./runtests.py --fast
|
||||
|
||||
Don't run the flake8 code linting.
|
||||
|
||||
./runtests.py --nolint
|
||||
|
||||
Only run the flake8 code linting, don't run the tests.
|
||||
|
||||
./runtests.py --lintonly
|
||||
|
||||
Run the tests for a given test case.
|
||||
|
||||
./runtests.py MyTestCase
|
||||
|
@ -121,13 +122,13 @@ 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.
|
||||
Once you've made a pull request take a look at the build status in the GitHub interface and make sure the tests are running as you'd expect.
|
||||
|
||||
![Travis status][travis-status]
|
||||
![Build status][build-status]
|
||||
|
||||
*Above: Travis build notifications*
|
||||
*Above: build notifications*
|
||||
|
||||
## Managing compatibility issues
|
||||
|
||||
|
@ -210,7 +211,7 @@ If you want to draw attention to a note or warning, use a pair of enclosing line
|
|||
[so-filter]: https://stackexchange.com/filters/66475/rest-framework
|
||||
[issues]: https://github.com/encode/django-rest-framework/issues?state=open
|
||||
[pep-8]: https://www.python.org/dev/peps/pep-0008/
|
||||
[travis-status]: ../img/travis-status.png
|
||||
[build-status]: ../img/build-status.png
|
||||
[pull-requests]: https://help.github.com/articles/using-pull-requests
|
||||
[tox]: https://tox.readthedocs.io/en/latest/
|
||||
[markdown]: https://daringfireball.net/projects/markdown/basics
|
||||
|
|
|
@ -124,7 +124,7 @@ REST framework continues to be open-source and permissively licensed, but we fir
|
|||
## What funding has enabled so far
|
||||
|
||||
* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
|
||||
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
|
||||
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
|
||||
* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
|
||||
* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/).
|
||||
* Tom Christie, the creator of Django REST framework, working on the project full-time.
|
||||
|
@ -137,7 +137,7 @@ REST framework continues to be open-source and permissively licensed, but we fir
|
|||
## What future funding will enable
|
||||
|
||||
* Realtime API support, using WebSockets. This will consist of documentation and support for using REST framework together with Django Channels, plus integrating WebSocket support into the client libraries.
|
||||
* Better authentication defaults, possibly bringing JWT & CORs support into the core package.
|
||||
* Better authentication defaults, possibly bringing JWT & CORS support into the core package.
|
||||
* Securing the community & operations manager position long-term.
|
||||
* Opening up and securing a part-time position to focus on ticket triage and resolution.
|
||||
* Paying for development time on building API client libraries in a range of programming languages. These would be integrated directly into the upcoming API documentation.
|
||||
|
@ -154,13 +154,13 @@ Sign up for a paid plan today, and help ensure that REST framework becomes a sus
|
|||
|
||||
|
||||
|
||||
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
|
||||
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
|
||||
>
|
||||
> — Filipe Ximenes, Vinta Software
|
||||
|
||||
|
||||
|
||||
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
|
||||
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
|
||||
DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.
|
||||
>
|
||||
> — Andrew Conti, Django REST framework user
|
||||
|
|
|
@ -9,12 +9,14 @@ 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]
|
||||
* [https://findwork.dev/django-rest-framework-jobs][findwork-dev]
|
||||
* [https://www.indeed.com/q-Django-jobs.html][indeed-com]
|
||||
* [https://stackoverflow.com/jobs/developer-jobs-using-django][stackoverflow-com]
|
||||
* [https://stackoverflow.com/jobs/companies?tl=django][stackoverflow-com]
|
||||
* [https://www.upwork.com/o/jobs/browse/skill/django-framework/][upwork-com]
|
||||
* [https://www.technojobs.co.uk/django-jobs][technobjobs-co-uk]
|
||||
* [https://remoteok.io/remote-django-jobs][remoteok-io]
|
||||
* [https://remoteok.com/remote-django-jobs][remoteok-com]
|
||||
* [https://www.remotepython.com/jobs/][remotepython-com]
|
||||
* [https://www.pyjobs.com/][pyjobs-com]
|
||||
|
||||
|
||||
Know of any other great resources for Django REST Framework jobs that are missing in our list? Please [submit a pull request][submit-pr] or [email us][anna-email].
|
||||
|
@ -26,12 +28,14 @@ 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/
|
||||
[findwork-dev]: https://findwork.dev/django-rest-framework-jobs
|
||||
[indeed-com]: https://www.indeed.com/q-Django-jobs.html
|
||||
[stackoverflow-com]: https://stackoverflow.com/jobs/developer-jobs-using-django
|
||||
[stackoverflow-com]: https://stackoverflow.com/jobs/companies?tl=django
|
||||
[upwork-com]: https://www.upwork.com/o/jobs/browse/skill/django-framework/
|
||||
[technobjobs-co-uk]: https://www.technojobs.co.uk/django-jobs
|
||||
[remoteok-io]: https://remoteok.io/remote-django-jobs
|
||||
[remoteok-com]: https://remoteok.com/remote-django-jobs
|
||||
[remotepython-com]: https://www.remotepython.com/jobs/
|
||||
[pyjobs-com]: https://www.pyjobs.com/
|
||||
[drf-funding]: https://fund.django-rest-framework.org/topics/funding/
|
||||
[submit-pr]: https://github.com/encode/django-rest-framework
|
||||
[anna-email]: mailto:anna@django-rest-framework.org
|
||||
|
|
|
@ -195,7 +195,6 @@ 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.
|
||||
|
@ -206,6 +205,5 @@ The following issues still need to be addressed:
|
|||
[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/
|
||||
[transifex-client]: https://pypi.org/project/transifex-client/
|
||||
[translation-memory]: http://docs.transifex.com/guides/tm#let-tm-automatically-populate-translations
|
||||
[github-org]: https://github.com/encode/django-rest-framework/issues/2162
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
[mailing-list]: https://groups.google.com/forum/#!forum/django-rest-framework
|
||||
|
|
|
@ -1,9 +1,5 @@
|
|||
# Release Notes
|
||||
|
||||
> Release Early, Release Often
|
||||
>
|
||||
> — Eric S. Raymond, [The Cathedral and the Bazaar][cite].
|
||||
|
||||
## Versioning
|
||||
|
||||
Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.
|
||||
|
@ -38,11 +34,236 @@ You can determine your currently installed version using `pip show`:
|
|||
|
||||
---
|
||||
|
||||
## 3.14.x series
|
||||
|
||||
### 3.14.0
|
||||
|
||||
Date: 22nd September 2022
|
||||
|
||||
* Django 2.2 is no longer supported. [[#8662](https://github.com/encode/django-rest-framework/pull/8662)]
|
||||
* Django 4.1 compatibility. [[#8591](https://github.com/encode/django-rest-framework/pull/8591)]
|
||||
* Add `--api-version` CLI option to `generateschema` management command. [[#8663](https://github.com/encode/django-rest-framework/pull/8663)]
|
||||
* Enforce `is_valid(raise_exception=False)` as a keyword-only argument. [[#7952](https://github.com/encode/django-rest-framework/pull/7952)]
|
||||
* Stop calling `set_context` on Validators. [[#8589](https://github.com/encode/django-rest-framework/pull/8589)]
|
||||
* Return `NotImplemented` from `ErrorDetails.__ne__`. [[#8538](https://github.com/encode/django-rest-framework/pull/8538)]
|
||||
* Don't evaluate `DateTimeField.default_timezone` when a custom timezone is set. [[#8531](https://github.com/encode/django-rest-framework/pull/8531)]
|
||||
* Make relative URLs clickable in Browseable API. [[#8464](https://github.com/encode/django-rest-framework/pull/8464)]
|
||||
* Support `ManyRelatedField` falling back to the default value when the attribute specified by dot notation doesn't exist. Matches `ManyRelatedField.get_attribute` to `Field.get_attribute`. [[#7574](https://github.com/encode/django-rest-framework/pull/7574)]
|
||||
* Make `schemas.openapi.get_reference` public. [[#7515](https://github.com/encode/django-rest-framework/pull/7515)]
|
||||
* Make `ReturnDict` support `dict` union operators on Python 3.9 and later. [[#8302](https://github.com/encode/django-rest-framework/pull/8302)]
|
||||
* Update throttling to check if `request.user` is set before checking if the user is authenticated. [[#8370](https://github.com/encode/django-rest-framework/pull/8370)]
|
||||
|
||||
## 3.13.x series
|
||||
|
||||
### 3.13.1
|
||||
|
||||
Date: 15th December 2021
|
||||
|
||||
* Revert schema naming changes with function based `@api_view`. [#8297]
|
||||
|
||||
### 3.13.0
|
||||
|
||||
Date: 13th December 2021
|
||||
|
||||
* Django 4.0 compatability. [#8178]
|
||||
* Add `max_length` and `min_length` options to `ListSerializer`. [#8165]
|
||||
* Add `get_request_serializer` and `get_response_serializer` hooks to `AutoSchema`. [#7424]
|
||||
* Fix OpenAPI representation of null-able read only fields. [#8116]
|
||||
* Respect `UNICODE_JSON` setting in API schema outputs. [#7991]
|
||||
* Fix for `RemoteUserAuthentication`. [#7158]
|
||||
* Make Field constructors keyword-only. [#7632]
|
||||
|
||||
---
|
||||
|
||||
## 3.12.x series
|
||||
|
||||
### 3.12.4
|
||||
|
||||
Date: 26th March 2021
|
||||
|
||||
* Revert use of `deque` instead of `list` for tracking throttling `.history`. (Due to incompatibility with DjangoRedis cache backend. See #7870) [#7872]
|
||||
|
||||
### 3.12.3
|
||||
|
||||
Date: 25th March 2021
|
||||
|
||||
* Properly handle ATOMIC_REQUESTS when multiple database configurations are used. [#7739]
|
||||
* Bypass `COUNT` query when `LimitOffsetPagination` is configured but pagination params are not included on the request. [#6098]
|
||||
* Respect `allow_null=True` on `DecimalField`. [#7718]
|
||||
* Allow title cased `"Yes"`/`"No"` values with `BooleanField`. [#7739]
|
||||
* Add `PageNumberPagination.get_page_number()` method for overriding behavior. [#7652]
|
||||
* Fixed rendering of timedelta values in OpenAPI schemas, when present as default, min, or max fields. [#7641]
|
||||
* Render JSONFields with indentation in browsable API forms. [#6243]
|
||||
* Remove unnecessary database query in admin Token views. [#7852]
|
||||
* Raise validation errors when bools are passed to `PrimaryKeyRelatedField` fields, instead of casting to ints. [#7597]
|
||||
* Don't include model properties as automatically generated ordering fields with `OrderingFilter`. [#7609]
|
||||
* Use `deque` instead of `list` for tracking throttling `.history`. [#7849]
|
||||
|
||||
### 3.12.2
|
||||
|
||||
Date: 13th October 2020
|
||||
|
||||
* Fix issue if `rest_framework.authtoken.models` is imported, but `rest_framework.authtoken` is not in INSTALLED_APPS. [#7571]
|
||||
* Ignore subclasses of BrowsableAPIRenderer in OpenAPI schema. [#7497]
|
||||
* Narrower exception catching in serilizer fields, to ensure that any errors in broken `get_queryset()` methods are not masked. [#7480]
|
||||
|
||||
### 3.12.1
|
||||
|
||||
Date: 28th September 2020
|
||||
|
||||
* Add `TokenProxy` migration. [#7557]
|
||||
|
||||
### 3.12.0
|
||||
|
||||
Date: 28th September 2020
|
||||
|
||||
* Add `--file` option to `generateschema` command. [#7130]
|
||||
* Support `tags` for OpenAPI schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#grouping-operations-with-tags). [#7184]
|
||||
* Support customising the operation ID for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#operationid). [#7190]
|
||||
* Support OpenAPI components for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#components). [#7124]
|
||||
* The following methods on `AutoSchema` become public API: `get_path_parameters`, `get_pagination_parameters`, `get_filter_parameters`, `get_request_body`, `get_responses`, `get_serializer`, `get_paginator`, `map_serializer`, `map_field`, `map_choice_field`, `map_field_validators`, `allows_filters`. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#autoschema)
|
||||
* Add support for Django 3.1's database-agnositic `JSONField`. [#7467]
|
||||
* `SearchFilter` now supports nested search on `JSONField` and `HStoreField` model fields. [#7121]
|
||||
* `SearchFilter` now supports searching on `annotate()` fields. [#6240]
|
||||
* The authtoken model no longer exposes the `pk` in the admin URL. [#7341]
|
||||
* Add `__repr__` for Request instances. [#7239]
|
||||
* UTF-8 decoding with Latin-1 fallback for basic auth credentials. [#7193]
|
||||
* CharField treats surrogate characters as a validation failure. [#7026]
|
||||
* Don't include callables as default values in schemas. [#7105]
|
||||
* Improve `ListField` schema output to include all available child information. [#7137]
|
||||
* Allow `default=False` to be included for `BooleanField` schema outputs. [#7165]
|
||||
* Include `"type"` information in `ChoiceField` schema outputs. [#7161]
|
||||
* Include `"type": "object"` on schema objects. [#7169]
|
||||
* Don't include component in schema output for DELETE requests. [#7229]
|
||||
* Fix schema types for `DecimalField`. [#7254]
|
||||
* Fix schema generation for `ObtainAuthToken` view. [#7211]
|
||||
* Support passing `context=...` to view `.get_serializer()` methods. [#7298]
|
||||
* Pass custom code to `PermissionDenied` if permission class has one set. [#7306]
|
||||
* Include "example" in schema pagination output. [#7275]
|
||||
* Default status code of 201 on schema output for POST requests. [#7206]
|
||||
* Use camelCase for operation IDs in schema output. [#7208]
|
||||
* Warn if duplicate operation IDs exist in schema output. [#7207]
|
||||
* Improve handling of decimal type when mapping `ChoiceField` to a schema output. [#7264]
|
||||
* Disable YAML aliases for OpenAPI schema outputs. [#7131]
|
||||
* Fix action URL names for APIs included under a namespaced URL. [#7287]
|
||||
* Update jQuery version from 3.4 to 3.5. [#7313]
|
||||
* Fix `UniqueTogether` handling when serializer fields use `source=...`. [#7143]
|
||||
* HTTP `HEAD` requests now set `self.action` correctly on a ViewSet instance. [#7223]
|
||||
* Return a valid OpenAPI schema for the case where no API schema paths exist. [#7125]
|
||||
* Include tests in package distribution. [#7145]
|
||||
* Allow type checkers to support annotations like `ModelSerializer[Author]`. [#7385]
|
||||
* Don't include invalid `charset=None` portion in the request `Content-Type` header when using APIClient. [#7400]
|
||||
* Fix `\Z`/`\z` tokens in OpenAPI regexs. [#7389]
|
||||
* Fix `PrimaryKeyRelatedField` and `HyperlinkedRelatedField` when source field is actually a property. [#7142]
|
||||
* `Token.generate_key` is now a class method. [#7502]
|
||||
* `@action` warns if method is wrapped in a decorator that does not preserve information using `@functools.wraps`. [#7098]
|
||||
|
||||
---
|
||||
|
||||
## 3.11.x series
|
||||
|
||||
### 3.11.2
|
||||
|
||||
**Date**: 30th September 2020
|
||||
|
||||
* **Security**: Drop `urlize_quoted_links` template tag in favour of Django's built-in `urlize`. Removes a XSS vulnerability for some kinds of content in the browsable API.
|
||||
|
||||
### 3.11.1
|
||||
|
||||
**Date**: 5th August 2020
|
||||
|
||||
* Fix compat with Django 3.1
|
||||
|
||||
### 3.11.0
|
||||
|
||||
**Date**: 12th December 2019
|
||||
|
||||
* Drop `.set_context` API [in favour of a `requires_context` marker](3.11-announcement.md#validator-default-context).
|
||||
* Changed default widget for TextField with choices to select box. [#6892][gh6892]
|
||||
* Supported nested writes on non-relational fields, such as JSONField. [#6916][gh6916]
|
||||
* Include request/response media types in OpenAPI schemas, based on configured parsers/renderers. [#6865][gh6865]
|
||||
* Include operation descriptions in OpenAPI schemas, based on the docstring on the view. [#6898][gh6898]
|
||||
* Fix representation of serializers with all optional fields in OpenAPI schemas. [#6941][gh6941], [#6944][gh6944]
|
||||
* Fix representation of `serializers.HStoreField` in OpenAPI schemas. [#6914][gh6914]
|
||||
* Fix OpenAPI generation when title or version is not provided. [#6912][gh6912]
|
||||
* Use `int64` representation for large integers in OpenAPI schemas. [#7018][gh7018]
|
||||
* Improved error messages if no `.to_representation` implementation is provided on a field subclass. [#6996][gh6996]
|
||||
* Fix for serializer classes that use multiple inheritance. [#6980][gh6980]
|
||||
* Fix for reversing Hyperlinked URL fields with percent encoded components in the path. [#7059][gh7059]
|
||||
* Update bootstrap to 3.4.1. [#6923][gh6923]
|
||||
|
||||
## 3.10.x series
|
||||
|
||||
### 3.10.3
|
||||
|
||||
**Date**: 4th September 2019
|
||||
|
||||
* 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 calculations could error after a configuration change.
|
||||
|
||||
### 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.
|
||||
* Deprecate the `detail_route` decorator in favor of `action`, which accepts a `detail` bool. Use `@action(detail=True)` instead. [gh6687]
|
||||
* Deprecate the `list_route` decorator in favor of `action`, which accepts a `detail` bool. Use `@action(detail=False)` instead. [gh6687]
|
||||
|
||||
## 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.1-milestone]
|
||||
**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]
|
||||
|
@ -93,7 +314,7 @@ You can determine your currently installed version using `pip show`:
|
|||
* 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]
|
||||
* Change ISO 8601 date format to exclude year/month-only options [#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]
|
||||
|
@ -106,7 +327,7 @@ You can determine your currently installed version using `pip show`:
|
|||
* 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]
|
||||
* Improved 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]
|
||||
|
@ -157,11 +378,11 @@ You can determine your currently installed version using `pip show`:
|
|||
def perform_create(self, serializer):
|
||||
serializer.save(owner=self.request.user)
|
||||
|
||||
Alternatively you may override `save()` or `create()` or `update()` on the serialiser as appropriate.
|
||||
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 serialisation. Previously such
|
||||
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
|
||||
|
@ -294,7 +515,7 @@ You can determine your currently installed version using `pip show`:
|
|||
Note: `AutoSchema.__init__` now ensures `manual_fields` is a list.
|
||||
Previously may have been stored internally as `None`.
|
||||
|
||||
* Remove ulrparse compatability shim; use six instead [#5579][gh5579]
|
||||
* 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]
|
||||
|
@ -399,7 +620,7 @@ You can determine your currently installed version using `pip show`:
|
|||
* 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.
|
||||
|
||||
|
@ -1165,7 +1386,8 @@ For older release notes, [please see the version 2.x documentation][old-release-
|
|||
[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.1-milestone]: https://github.com/encode/django-rest-framework/milestone/71?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
|
||||
|
@ -2106,3 +2328,26 @@ For older release notes, [please see the version 2.x documentation][old-release-
|
|||
[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
|
||||
[gh6687]: https://github.com/encode/django-rest-framework/issues/6687
|
||||
|
||||
<!-- 3.11.0 -->
|
||||
[gh6892]: https://github.com/encode/django-rest-framework/issues/6892
|
||||
[gh6916]: https://github.com/encode/django-rest-framework/issues/6916
|
||||
[gh6865]: https://github.com/encode/django-rest-framework/issues/6865
|
||||
[gh6898]: https://github.com/encode/django-rest-framework/issues/6898
|
||||
[gh6941]: https://github.com/encode/django-rest-framework/issues/6941
|
||||
[gh6944]: https://github.com/encode/django-rest-framework/issues/6944
|
||||
[gh6914]: https://github.com/encode/django-rest-framework/issues/6914
|
||||
[gh6912]: https://github.com/encode/django-rest-framework/issues/6912
|
||||
[gh7018]: https://github.com/encode/django-rest-framework/issues/7018
|
||||
[gh6996]: https://github.com/encode/django-rest-framework/issues/6996
|
||||
[gh6980]: https://github.com/encode/django-rest-framework/issues/6980
|
||||
[gh7059]: https://github.com/encode/django-rest-framework/issues/7059
|
||||
[gh6923]: https://github.com/encode/django-rest-framework/issues/6923
|
||||
|
|
|
@ -14,142 +14,9 @@ We aim to make creating third party packages as easy as possible, whilst keeping
|
|||
|
||||
If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the [Mailing List][discussion-group].
|
||||
|
||||
## How to create a Third Party Package
|
||||
## Creating a Third Party Package
|
||||
|
||||
### Creating your package
|
||||
|
||||
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.
|
||||
|
||||
#### Running the initial cookiecutter command
|
||||
|
||||
To run the initial cookiecutter command, you'll first need to install the Python `cookiecutter` package.
|
||||
|
||||
$ pip install cookiecutter
|
||||
|
||||
Once `cookiecutter` is installed just run the following to create a new project.
|
||||
|
||||
$ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework
|
||||
|
||||
You'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values.
|
||||
|
||||
full_name (default is "Your full name here")? Johnny Appleseed
|
||||
email (default is "you@example.com")? jappleseed@example.com
|
||||
github_username (default is "yourname")? jappleseed
|
||||
pypi_project_name (default is "dj-package")? djangorestframework-custom-auth
|
||||
repo_name (default is "dj-package")? django-rest-framework-custom-auth
|
||||
app_name (default is "djpackage")? custom_auth
|
||||
project_short_description (default is "Your project description goes here")?
|
||||
year (default is "2014")?
|
||||
version (default is "0.1.0")?
|
||||
|
||||
#### Getting it onto GitHub
|
||||
|
||||
To put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository [here][new-repo]. If you need help, check out the [Create A Repo][create-a-repo] article on GitHub.
|
||||
|
||||
|
||||
#### Adding to Travis CI
|
||||
|
||||
We recommend using [Travis CI][travis-ci], a hosted continuous integration service which integrates well with GitHub and is free for public repositories.
|
||||
|
||||
To get started with Travis CI, [sign in][travis-ci] with your GitHub account. Once you're signed in, go to your [profile page][travis-profile] and enable the service hook for the repository you want.
|
||||
|
||||
If you use the cookiecutter template, your project will already contain a `.travis.yml` file which Travis CI will use to build your project and run tests. By default, builds are triggered everytime you push to your repository or create Pull Request.
|
||||
|
||||
#### Uploading to PyPI
|
||||
|
||||
Once you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via `pip`.
|
||||
|
||||
You must [register][pypi-register] an account before publishing to PyPI.
|
||||
|
||||
To register your package on PyPI run the following command.
|
||||
|
||||
$ python setup.py register
|
||||
|
||||
If this is the first time publishing to PyPI, you'll be prompted to login.
|
||||
|
||||
Note: Before publishing you'll need to make sure you have the latest pip that supports `wheel` as well as install the `wheel` package.
|
||||
|
||||
$ pip install --upgrade pip
|
||||
$ pip install wheel
|
||||
|
||||
After this, every time you want to release a new version on PyPI just run the following command.
|
||||
|
||||
$ python setup.py publish
|
||||
You probably want to also tag the version now:
|
||||
git tag -a {0} -m 'version 0.1.0'
|
||||
git push --tags
|
||||
|
||||
After releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release.
|
||||
|
||||
We recommend to follow [Semantic Versioning][semver] for your package's versions.
|
||||
|
||||
### Development
|
||||
|
||||
#### Version requirements
|
||||
|
||||
The cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, `tox.ini`, `.travis.yml`, and `setup.py` to match the set of versions you wish to support.
|
||||
|
||||
#### Tests
|
||||
|
||||
The cookiecutter template includes a `runtests.py` which uses the `pytest` package as a test runner.
|
||||
|
||||
Before running, you'll need to install a couple test requirements.
|
||||
|
||||
$ pip install -r requirements.txt
|
||||
|
||||
Once requirements installed, you can run `runtests.py`.
|
||||
|
||||
$ ./runtests.py
|
||||
|
||||
Run using a more concise output style.
|
||||
|
||||
$ ./runtests.py -q
|
||||
|
||||
Run the tests using a more concise output style, no coverage, no flake8.
|
||||
|
||||
$ ./runtests.py --fast
|
||||
|
||||
Don't run the flake8 code linting.
|
||||
|
||||
$ ./runtests.py --nolint
|
||||
|
||||
Only run the flake8 code linting, don't run the tests.
|
||||
|
||||
$ ./runtests.py --lintonly
|
||||
|
||||
Run the tests for a given test case.
|
||||
|
||||
$ ./runtests.py MyTestCase
|
||||
|
||||
Run the tests for a given test method.
|
||||
|
||||
$ ./runtests.py MyTestCase.test_this_method
|
||||
|
||||
Shorter form to run the tests for a given test method.
|
||||
|
||||
$ ./runtests.py test_this_method
|
||||
|
||||
To run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using `tox`. [Tox][tox-docs] is a generic virtualenv management and test command line tool.
|
||||
|
||||
First, install `tox` globally.
|
||||
|
||||
$ pip install tox
|
||||
|
||||
To run `tox`, just simply run:
|
||||
|
||||
$ tox
|
||||
|
||||
To run a particular `tox` environment:
|
||||
|
||||
$ tox -e envlist
|
||||
|
||||
`envlist` is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run:
|
||||
|
||||
$ tox -l
|
||||
|
||||
#### Version compatibility
|
||||
### Version compatibility
|
||||
|
||||
Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a `compat.py` module, and should provide a single common interface that the rest of the codebase can use.
|
||||
|
||||
|
@ -187,9 +54,10 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [hawkrest][hawkrest] - Provides Hawk HTTP Authorization.
|
||||
* [djangorestframework-httpsignature][djangorestframework-httpsignature] - Provides an easy to use HTTP Signature Authentication mechanism.
|
||||
* [djoser][djoser] - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.
|
||||
* [django-rest-auth][django-rest-auth] - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.
|
||||
* [dj-rest-auth][dj-rest-auth] - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.
|
||||
* [drf-oidc-auth][drf-oidc-auth] - Implements OpenID Connect token authentication for DRF.
|
||||
* [drfpasswordless][drfpasswordless] - Adds (Medium, Square Cash inspired) passwordless logins and signups via email and mobile numbers.
|
||||
* [django-rest-authemail][django-rest-authemail] - Provides a RESTful API for user signup and authentication using email addresses.
|
||||
|
||||
### Permissions
|
||||
|
||||
|
@ -197,6 +65,8 @@ 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.
|
||||
* [drf-psq][drf-psq] - An extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.
|
||||
|
||||
### Serializers
|
||||
|
||||
|
@ -208,17 +78,23 @@ 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).
|
||||
* [graphwrap][graphwrap] - Transform your REST API into a fully compliant GraphQL API with just two lines of code. Leverages [Graphene-Django](https://docs.graphene-python.org/projects/django/en/latest/) to dynamically build, at runtime, a GraphQL ObjectType for each view in your API.
|
||||
|
||||
### Serializer fields
|
||||
|
||||
* [drf-compound-fields][drf-compound-fields] - Provides "compound" serializer fields, such as lists of simple values.
|
||||
* [django-extra-fields][django-extra-fields] - Provides extra serializer fields.
|
||||
* [drf-extra-fields][drf-extra-fields] - Provides extra serializer fields.
|
||||
* [django-versatileimagefield][django-versatileimagefield] - Provides a drop-in replacement for Django's stock `ImageField` that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, [click here][django-versatileimagefield-drf-docs].
|
||||
|
||||
### Views
|
||||
|
||||
* [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.
|
||||
* [drf-typed-views][drf-typed-views] - Use Python type annotations to validate/deserialize request parameters. Inspired by API Star, Hug and FastAPI.
|
||||
* [rest-framework-actions][rest-framework-actions] - Provides control over each action in ViewSets. Serializers per action, method.
|
||||
|
||||
### Routers
|
||||
|
||||
|
@ -230,12 +106,13 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [djangorestframework-msgpack][djangorestframework-msgpack] - Provides MessagePack renderer and parser support.
|
||||
* [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
|
||||
* [djangorestframework-camel-case][djangorestframework-camel-case] - Provides camel case JSON renderers and parsers.
|
||||
* [nested-multipart-parser][nested-multipart-parser] - Provides nested parser for http multipart request
|
||||
|
||||
### Renderers
|
||||
|
||||
* [djangorestframework-csv][djangorestframework-csv] - Provides CSV renderer support.
|
||||
* [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
|
||||
* [drf_ujson][drf_ujson] - Implements JSON rendering using the UJSON package.
|
||||
* [drf_ujson2][drf_ujson2] - Implements JSON rendering using the UJSON package.
|
||||
* [rest-pandas][rest-pandas] - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.
|
||||
* [djangorestframework-rapidjson][djangorestframework-rapidjson] - Provides rapidjson support with parser and renderer.
|
||||
|
||||
|
@ -244,12 +121,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.
|
||||
* [django-rest-swagger][django-rest-swagger] - An API documentation generator for Swagger UI.
|
||||
* [djangorestrelationalhyperlink][djangorestrelationalhyperlink] - A hyperlinked serializer that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.
|
||||
* [django-rest-framework-proxy][django-rest-framework-proxy] - Proxy to redirect incoming request to another API server.
|
||||
* [gaiarestframework][gaiarestframework] - Utils for django-rest-framework
|
||||
* [drf-extensions][drf-extensions] - A collection of custom extensions
|
||||
|
@ -263,13 +140,21 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [django-rest-messaging][django-rest-messaging], [django-rest-messaging-centrifugo][django-rest-messaging-centrifugo] and [django-rest-messaging-js][django-rest-messaging-js] - A real-time pluggable messaging service using DRM.
|
||||
* [djangorest-alchemy][djangorest-alchemy] - SQLAlchemy support for REST framework.
|
||||
* [djangorestframework-datatables][djangorestframework-datatables] - Seamless integration between Django REST framework and [Datatables](https://datatables.net).
|
||||
* [django-rest-framework-condition][django-rest-framework-condition] - Decorators for managing HTTP cache headers for Django REST framework (ETag and Last-modified).
|
||||
* [django-rest-witchcraft][django-rest-witchcraft] - Provides DRF integration with SQLAlchemy with SQLAlchemy model serializers/viewsets and a bunch of other goodies
|
||||
* [djangorestframework-mvt][djangorestframework-mvt] - An extension for creating views that serve Postgres data as Map Box Vector Tiles.
|
||||
* [drf-viewset-profiler][drf-viewset-profiler] - Lib to profile all methods from a viewset line by line.
|
||||
* [djangorestframework-features][djangorestframework-features] - Advanced schema generation and more based on named features.
|
||||
* [django-elasticsearch-dsl-drf][django-elasticsearch-dsl-drf] - Integrate Elasticsearch DSL with Django REST framework. Package provides views, serializers, filter backends, pagination and other handy add-ons.
|
||||
* [django-api-client][django-api-client] - DRF client that groups the Endpoint response, for use in CBVs and FBV as if you were working with Django's Native Models..
|
||||
* [fast-drf] - A model based library for making API development faster and easier.
|
||||
* [django-requestlogs] - Providing middleware and other helpers for audit logging for REST framework.
|
||||
* [drf-standardized-errors][drf-standardized-errors] - DRF exception handler to standardize error responses for all API endpoints.
|
||||
|
||||
[cite]: http://www.software-ecosystems.com/Software_Ecosystems/Ecosystems.html
|
||||
[cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework
|
||||
[new-repo]: https://github.com/new
|
||||
[create-a-repo]: https://help.github.com/articles/create-a-repo/
|
||||
[travis-ci]: https://travis-ci.org
|
||||
[travis-profile]: https://travis-ci.org/profile
|
||||
[pypi-register]: https://pypi.org/account/register/
|
||||
[semver]: https://semver.org/
|
||||
[tox-docs]: https://tox.readthedocs.io/en/latest/
|
||||
|
@ -295,33 +180,32 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[djangorestframework-gis]: https://github.com/djangonauts/django-rest-framework-gis
|
||||
[djangorestframework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore
|
||||
[drf-compound-fields]: https://github.com/estebistec/drf-compound-fields
|
||||
[django-extra-fields]: https://github.com/Hipo/drf-extra-fields
|
||||
[djangorestframework-bulk]: https://github.com/miki725/django-rest-framework-bulk
|
||||
[drf-extra-fields]: https://github.com/Hipo/drf-extra-fields
|
||||
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
|
||||
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
|
||||
[wq.db.rest]: https://wq.io/docs/about-rest
|
||||
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
|
||||
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
|
||||
[nested-multipart-parser]: https://github.com/remigermain/nested-multipart-parser
|
||||
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
|
||||
[drf_ujson]: https://github.com/gizmag/drf-ujson-renderer
|
||||
[drf_ujson2]: https://github.com/Amertz08/drf_ujson2
|
||||
[rest-pandas]: https://github.com/wq/django-rest-pandas
|
||||
[djangorestframework-rapidjson]: https://github.com/allisson/django-rest-framework-rapidjson
|
||||
[djangorestframework-chain]: https://github.com/philipn/django-rest-framework-chain
|
||||
[djangorestrelationalhyperlink]: https://github.com/fredkingham/django_rest_model_hyperlink_serializers_project
|
||||
[django-rest-swagger]: https://github.com/marcgibbons/django-rest-swagger
|
||||
[django-rest-framework-proxy]: https://github.com/eofs/django-rest-framework-proxy
|
||||
[gaiarestframework]: https://github.com/AppsFuel/gaiarestframework
|
||||
[drf-extensions]: https://github.com/chibisov/drf-extensions
|
||||
[ember-django-adapter]: https://github.com/dustinfarris/ember-django-adapter
|
||||
[django-rest-auth]: https://github.com/Tivix/django-rest-auth/
|
||||
[dj-rest-auth]: https://github.com/iMerica/dj-rest-auth
|
||||
[django-versatileimagefield]: https://github.com/WGBH/django-versatileimagefield
|
||||
[django-versatileimagefield-drf-docs]:https://django-versatileimagefield.readthedocs.io/en/latest/drf_integration.html
|
||||
[drf-tracking]: https://github.com/aschn/drf-tracking
|
||||
[django-rest-framework-braces]: https://github.com/dealertrack/django-rest-framework-braces
|
||||
[dry-rest-permissions]: https://github.com/Helioscene/dry-rest-permissions
|
||||
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
|
||||
[django-url-filter]: https://github.com/miki725/django-url-filter
|
||||
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
|
||||
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
|
||||
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
|
||||
[drf-haystack]: https://drf-haystack.readthedocs.io/en/latest/
|
||||
[django-rest-framework-version-transforms]: https://github.com/mrhwick/django-rest-framework-version-transforms
|
||||
[djangorestframework-jsonapi]: https://github.com/django-json-api/django-rest-framework-json-api
|
||||
|
@ -336,3 +220,24 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[drfpasswordless]: https://github.com/aaronn/django-rest-framework-passwordless
|
||||
[djangorest-alchemy]: https://github.com/dealertrack/djangorest-alchemy
|
||||
[djangorestframework-datatables]: https://github.com/izimobil/django-rest-framework-datatables
|
||||
[django-rest-framework-condition]: https://github.com/jozo/django-rest-framework-condition
|
||||
[django-rest-witchcraft]: https://github.com/shosca/django-rest-witchcraft
|
||||
[drf-access-policy]: https://github.com/rsinger86/drf-access-policy
|
||||
[drf-flex-fields]: https://github.com/rsinger86/drf-flex-fields
|
||||
[drf-typed-views]: https://github.com/rsinger86/drf-typed-views
|
||||
[drf-action-serializer]: https://github.com/gregschmit/drf-action-serializer
|
||||
[djangorestframework-dataclasses]: https://github.com/oxan/djangorestframework-dataclasses
|
||||
[django-restql]: https://github.com/yezyilomo/django-restql
|
||||
[djangorestframework-mvt]: https://github.com/corteva/djangorestframework-mvt
|
||||
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
|
||||
[drf-viewset-profiler]: https://github.com/fvlima/drf-viewset-profiler
|
||||
[djangorestframework-features]: https://github.com/cloudcode-hungary/django-rest-framework-features/
|
||||
[django-elasticsearch-dsl-drf]: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf
|
||||
[django-api-client]: https://github.com/rhenter/django-api-client
|
||||
[drf-psq]: https://github.com/drf-psq/drf-psq
|
||||
[django-rest-authemail]: https://github.com/celiao/django-rest-authemail
|
||||
[graphwrap]: https://github.com/PaulGilmartin/graph_wrap
|
||||
[rest-framework-actions]: https://github.com/AlexisMunera98/rest-framework-actions
|
||||
[fast-drf]: https://github.com/iashraful/fast-drf
|
||||
[django-requestlogs]: https://github.com/Raekkeri/django-requestlogs
|
||||
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors
|
||||
|
|
|
@ -11,8 +11,8 @@ 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 class="book-cover" href="https://djangoforapis.com">
|
||||
<img src="../../img/books/dfa-cover.jpg"/>
|
||||
</a>
|
||||
<a class="book-cover" href="https://books.agiliq.com/projects/django-api-polls-tutorial/en/latest/">
|
||||
<img src="../../img/books/bda-cover.png"/>
|
||||
|
@ -76,6 +76,7 @@ There are a wide range of resources available for learning and using Django REST
|
|||
* [Chatbot Using Django REST Framework + api.ai + Slack — Part 1/3][chatbot-using-drf-part1]
|
||||
* [New Django Admin with DRF and EmberJS... What are the News?][new-django-admin-with-drf-and-emberjs]
|
||||
* [Blog posts about Django REST Framework][medium-django-rest-framework]
|
||||
* [Implementing Rest APIs With Embedded Privacy][doordash-implementing-rest-apis]
|
||||
|
||||
### Documentations
|
||||
* [Classy Django REST Framework][cdrf.co]
|
||||
|
@ -85,28 +86,28 @@ Want your Django REST Framework talk/tutorial/article to be added to our website
|
|||
|
||||
|
||||
[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/getting-started-with-django-rest-framework-and-angularjs.html
|
||||
[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://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/
|
||||
[start-your-api-django-rest-framework-part-1]: https://www.youtube.com/watch?v=hqo2kk91WpE
|
||||
[permissions-authentication-django-rest-framework-part-2]: https://www.youtube.com/watch?v=R3xvUDUZxGU
|
||||
[viewsets-and-routers-django-rest-framework-part-3]: https://www.youtube.com/watch?v=2d6w4DGQ4OU
|
||||
[django-rest-framework-user-endpoint]: https://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/
|
||||
[check-credentials-using-django-rest-framework]: https://richardtier.com/2014/03/06/110/
|
||||
[ember-and-django-part 1-video]: http://www.neckbeardrepublic.com/screencasts/ember-and-django-part-1
|
||||
[django-rest-framework-part-1-video]: http://www.neckbeardrepublic.com/screencasts/django-rest-framework-part-1
|
||||
[web-api-performance-profiling-django-rest-framework]: https://www.dabapps.com/blog/api-performance-profiling-django-rest-framework/
|
||||
[api-development-with-django-and-django-rest-framework]: https://bnotions.com/api-development-with-django-and-django-rest-framework/
|
||||
[api-development-with-django-and-django-rest-framework]: https://bnotions.com/news-and-insights/api-development-with-django-and-django-rest-framework/
|
||||
[cdrf.co]:http://www.cdrf.co
|
||||
[medium-django-rest-framework]: https://medium.com/django-rest-framework
|
||||
[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]: 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/
|
||||
[integrating-pandas-drf-and-bokeh]: https://web.archive.org/web/20180104205117/http://machinalis.com/blog/pandas-django-rest-framework-bokeh/
|
||||
[controlling-uncertainty-on-web-apps-and-apis]: https://web.archive.org/web/20180104205043/https://machinalis.com/blog/controlling-uncertainty-on-web-applications-and-apis/
|
||||
[full-text-search-in-drf]: https://web.archive.org/web/20180104205059/http://machinalis.com/blog/full-text-search-on-django-rest-framework/
|
||||
[oauth2-authentication-with-drf]: https://web.archive.org/web/20180104205054/http://machinalis.com/blog/oauth2-authentication/
|
||||
[nested-resources-with-drf]: https://web.archive.org/web/20180104205109/http://machinalis.com/blog/nested-resources-with-django/
|
||||
[image-fields-with-drf]: https://web.archive.org/web/20180104205048/http://machinalis.com/blog/image-fields-with-django-rest-framework/
|
||||
[chatbot-using-drf-part1]: https://chatbotslife.com/chatbot-using-django-rest-framework-api-ai-slack-part-1-3-69c7e38b7b1e#.g2aceuncf
|
||||
[new-django-admin-with-drf-and-emberjs]: https://blog.levit.be/new-django-admin-with-emberjs-what-are-the-news/
|
||||
[drf-schema]: https://drf-schema-adapter.readthedocs.io/en/latest/
|
||||
|
@ -128,3 +129,4 @@ Want your Django REST Framework talk/tutorial/article to be added to our website
|
|||
[anna-email]: mailto:anna@django-rest-framework.org
|
||||
[pycon-us-2017]: https://www.youtube.com/watch?v=Rk6MHZdust4
|
||||
[django-rest-react-valentinog]: https://www.valentinog.com/blog/tutorial-api-django-rest-react/
|
||||
[doordash-implementing-rest-apis]: https://doordash.engineering/2013/10/07/implementing-rest-apis-with-embedded-privacy/
|
||||
|
|
|
@ -1,5 +1,16 @@
|
|||
# Tutorial 7: Schemas & client libraries
|
||||
|
||||
----
|
||||
|
||||
**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details.
|
||||
|
||||
If you are looking for information regarding schemas, you might want to look at these updated resources:
|
||||
|
||||
1. [Schema](../api-guide/schemas.md)
|
||||
2. [Documenting your API](../topics/documenting-your-api.md)
|
||||
|
||||
----
|
||||
|
||||
A schema is a machine-readable document that describes the available API
|
||||
endpoints, their URLS, and what operations they support.
|
||||
|
182
docs/coreapi/from-documenting-your-api.md
Normal file
|
@ -0,0 +1,182 @@
|
|||
|
||||
## Built-in API documentation
|
||||
|
||||
----
|
||||
|
||||
**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details.
|
||||
|
||||
If you are looking for information regarding schemas, you might want to look at these updated resources:
|
||||
|
||||
1. [Schema](../api-guide/schemas.md)
|
||||
2. [Documenting your API](../topics/documenting-your-api.md)
|
||||
|
||||
----
|
||||
|
||||
The built-in API documentation includes:
|
||||
|
||||
* Documentation of API endpoints.
|
||||
* 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 = [
|
||||
...
|
||||
path('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 behavior, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
|
||||
|
||||
You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:
|
||||
|
||||
from rest_framework.documentation import include_docs_urls
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
# Generate schema with valid `request` instance:
|
||||
path('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 as of 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).
|
854
docs/coreapi/schemas.md
Normal file
|
@ -0,0 +1,854 @@
|
|||
source: schemas.py
|
||||
|
||||
# Schemas
|
||||
|
||||
----
|
||||
|
||||
**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details.
|
||||
|
||||
You are probably looking for [this page](../api-guide/schemas.md) if you want latest information regarding schemas.
|
||||
|
||||
----
|
||||
|
||||
> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.
|
||||
>
|
||||
> — Heroku, [JSON Schema for the Heroku Platform API][cite]
|
||||
|
||||
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
|
||||
from django.urls import path
|
||||
|
||||
schema_view = get_schema_view(title="Example API")
|
||||
|
||||
urlpatterns = [
|
||||
path('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 = [
|
||||
path('', 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 = [
|
||||
path('api/', include('myproject.api.urls')),
|
||||
]
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
patterns=schema_url_patterns,
|
||||
)
|
||||
|
||||
#### `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 behavior you want. For example, you can apply different
|
||||
permission, throttling, or authentication policies to the schema endpoint.
|
||||
|
||||
Here's an example of using `SchemaGenerator` together with a view to
|
||||
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 = [
|
||||
path('', 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.
|
||||
|
||||
|
||||
## drf-spectacular - Sane and flexible OpenAPI 3.0 schema generation for Django REST framework
|
||||
|
||||
[drf-spectacular][drf-spectacular] is a [OpenAPI 3][open-api] schema generation tool with explicit focus on extensibility,
|
||||
customizability and client generation. It's usage patterns are very similar to [drf-yasg][drf-yasg].
|
||||
|
||||
[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/
|
||||
[drf-spectacular]: https://github.com/tfranzel/drf-spectacular/
|
||||
[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
|
Before Width: | Height: | Size: 54 KiB |
BIN
docs/img/books/dfa-cover.jpg
Normal file
After Width: | Height: | Size: 49 KiB |
Before Width: | Height: | Size: 14 KiB |
BIN
docs/img/build-status.png
Normal file
After Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 75 KiB |
Before Width: | Height: | Size: 567 KiB |
BIN
docs/img/premium/bitio-readme.png
Normal file
After Width: | Height: | Size: 18 KiB |
Before Width: | Height: | Size: 6.8 KiB After Width: | Height: | Size: 6.8 KiB |
BIN
docs/img/premium/cryptapi-readme.png
Normal file
After Width: | Height: | Size: 17 KiB |
BIN
docs/img/premium/esg-readme.png
Normal file
After Width: | Height: | Size: 13 KiB |
BIN
docs/img/premium/fezto-readme.png
Normal file
After Width: | Height: | Size: 22 KiB |
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
Before Width: | Height: | Size: 22 KiB |
Before Width: | Height: | Size: 13 KiB |
Before Width: | Height: | Size: 23 KiB |
BIN
docs/img/premium/posthog-readme.png
Normal file
After Width: | Height: | Size: 4.8 KiB |
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
BIN
docs/img/premium/retool-readme.png
Normal file
After Width: | Height: | Size: 8.7 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 |
BIN
docs/img/premium/spacinov-readme.png
Normal file
After Width: | Height: | Size: 56 KiB |
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 19 KiB |
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 27 KiB |
Before Width: | Height: | Size: 9.8 KiB |
|
@ -20,8 +20,8 @@
|
|||
<p class="badges" height=20px>
|
||||
<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="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 href="https://github.com/encode/django-rest-framework/actions/workflows/main.yml">
|
||||
<img src="https://github.com/encode/django-rest-framework/actions/workflows/main.yml/badge.svg" class="status-badge">
|
||||
</a>
|
||||
|
||||
<a href="https://pypi.org/project/djangorestframework/">
|
||||
|
@ -52,7 +52,7 @@ Some reasons you might want to use REST framework:
|
|||
* [Authentication policies][authentication] including packages for [OAuth1a][oauth1-section] and [OAuth2][oauth2-section].
|
||||
* [Serialization][serializers] that supports both [ORM][modelserializer-section] and [non-ORM][serializer-section] data sources.
|
||||
* Customizable all the way down - just use [regular function-based views][functionview-section] if you don't need the [more][generic-views] [powerful][viewsets] [features][routers].
|
||||
* [Extensive documentation][index], and [great community support][group].
|
||||
* Extensive documentation, and [great community support][group].
|
||||
* Used and trusted by internationally recognised companies including [Mozilla][mozilla], [Red Hat][redhat], [Heroku][heroku], and [Eventbrite][eventbrite].
|
||||
|
||||
---
|
||||
|
@ -67,16 +67,17 @@ continued development by **[signing up for a paid plan][funding]**.
|
|||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||
<li><a href="https://getstream.io/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://releasehistory.io" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/release-history.png)">Release History</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://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
<li><a href="https://www.spacinov.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/spacinov.png)">Spacinov</a></li>
|
||||
<li><a href="https://retool.com/?utm_source=djangorest&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/retool-sidebar.png)">Retool</a></li>
|
||||
<li><a href="https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/bitio_logo_gold_background.png)">bit.io</a></li>
|
||||
<li><a href="https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/135996800-d49fe024-32d9-441a-98d9-4c7596287a67.png)">PostHog</a></li>
|
||||
<li><a href="https://cryptapi.io" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cryptapi.png)">CryptAPI</a></li>
|
||||
<li><a href="https://www.fezto.xyz/?utm_source=DjangoRESTFramework" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/fezto.png)">FEZTO</a></li>
|
||||
</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), [Release History](https://releasehistory.io), [Rollbar](https://rollbar.com), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), and [Lights On Software](https://lightsonsoftware.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=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage), [Spacinov](https://www.spacinov.com/), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [PostHog](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [CryptAPI](https://cryptapi.io), and [FEZTO](https://www.fezto.xyz/?utm_source=DjangoRESTFramework).*
|
||||
|
||||
---
|
||||
|
||||
|
@ -84,18 +85,18 @@ continued development by **[signing up for a paid plan][funding]**.
|
|||
|
||||
REST framework requires the following:
|
||||
|
||||
* Python (2.7, 3.4, 3.5, 3.6, 3.7)
|
||||
* Django (1.11, 2.0, 2.1, 2.2)
|
||||
* Python (3.6, 3.7, 3.8, 3.9, 3.10)
|
||||
* Django (2.2, 3.0, 3.1, 3.2, 4.0, 4.1)
|
||||
|
||||
We **highly recommend** and only officially support the latest patch release of
|
||||
each Python and Django series.
|
||||
|
||||
The following packages are optional:
|
||||
|
||||
* [coreapi][coreapi] (1.32.0+) - Schema generation support.
|
||||
* [Markdown][markdown] (2.1.0+) - Markdown support for the browsable API.
|
||||
* [PyYAML][pyyaml], [uritemplate][uriteemplate] (5.1+, 3.0.0+) - Schema generation support.
|
||||
* [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
|
||||
|
@ -112,16 +113,16 @@ Install using `pip`, including any optional packages you want...
|
|||
|
||||
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.
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
url(r'^api-auth/', include('rest_framework.urls'))
|
||||
path('api-auth/', include('rest_framework.urls'))
|
||||
]
|
||||
|
||||
Note that the URL path can be whatever you want.
|
||||
|
@ -147,7 +148,7 @@ Don't forget to make sure you've also added `rest_framework` to your `INSTALLED_
|
|||
We're ready to create our API now.
|
||||
Here's our project's root `urls.py` module:
|
||||
|
||||
from django.conf.urls import url, include
|
||||
from django.urls import path, include
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import routers, serializers, viewsets
|
||||
|
||||
|
@ -155,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):
|
||||
|
@ -169,8 +170,8 @@ Here's our project's root `urls.py` module:
|
|||
# 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'))
|
||||
path('', include(router.urls)),
|
||||
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
||||
]
|
||||
|
||||
You can now open the API in your browser at [http://127.0.0.1:8000/](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.
|
||||
|
@ -187,20 +188,17 @@ Framework.
|
|||
|
||||
## Support
|
||||
|
||||
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.freenode.net`, search [the IRC archives][botbot], or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
|
||||
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.libera.chat`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
|
||||
|
||||
For priority support please sign up for a [professional or premium sponsorship plan](https://fund.django-rest-framework.org/topics/funding/).
|
||||
|
||||
For updates on REST framework development, you may also want to follow [the author][twitter] on Twitter.
|
||||
|
||||
<a style="padding-top: 10px" href="https://twitter.com/_tomchristie" class="twitter-follow-button" data-show-count="false">Follow @_tomchristie</a>
|
||||
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
|
||||
|
||||
## Security
|
||||
|
||||
If you believe you’ve found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**.
|
||||
Security issues are handled under the supervision of the [Django security team](https://www.djangoproject.com/foundation/teams/#security-team).
|
||||
|
||||
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
**Please report security issues by emailing security@djangoproject.com**.
|
||||
|
||||
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
|
||||
## License
|
||||
|
||||
|
@ -236,10 +234,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||
[redhat]: https://www.redhat.com/
|
||||
[heroku]: https://www.heroku.com/
|
||||
[eventbrite]: https://www.eventbrite.co.uk/about/
|
||||
[coreapi]: https://pypi.org/project/coreapi/
|
||||
[pyyaml]: https://pypi.org/project/PyYAML/
|
||||
[uriteemplate]: https://pypi.org/project/uritemplate/
|
||||
[markdown]: https://pypi.org/project/Markdown/
|
||||
[pygments]: https://pypi.org/project/Pygments/
|
||||
[django-filter]: https://pypi.org/project/django-filter/
|
||||
[django-crispy-forms]: https://github.com/maraujop/django-crispy-forms
|
||||
[django-guardian]: https://github.com/django-guardian/django-guardian
|
||||
[index]: .
|
||||
[oauth1-section]: api-guide/authentication/#django-rest-framework-oauth
|
||||
|
@ -262,7 +261,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||
[funding]: community/funding.md
|
||||
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[botbot]: https://botbot.me/freenode/restframework/
|
||||
[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
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
|
||||
>
|
||||
> — [Jeff Atwood][cite]
|
||||
> — [Jeff Atwood][cite]
|
||||
|
||||
## Javascript clients
|
||||
|
||||
|
@ -31,11 +31,11 @@ In order to make AJAX requests, you need to include CSRF token in the HTTP heade
|
|||
|
||||
The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.
|
||||
|
||||
[Otto Yiu][ottoyiu] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
|
||||
[Adam Johnson][adamchainz] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
|
||||
|
||||
[cite]: https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/
|
||||
[csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
|
||||
[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax
|
||||
[cors]: https://www.w3.org/TR/cors/
|
||||
[ottoyiu]: https://github.com/ottoyiu/
|
||||
[django-cors-headers]: https://github.com/ottoyiu/django-cors-headers/
|
||||
[adamchainz]: https://github.com/adamchainz
|
||||
[django-cors-headers]: https://github.com/adamchainz/django-cors-headers
|
||||
|
|
|
@ -230,7 +230,7 @@ started.
|
|||
In order to start working with an API, we first need a `Client` instance. The
|
||||
client holds any configuration around which codecs and transports are supported
|
||||
when interacting with an API, which allows you to provide for more advanced
|
||||
kinds of behaviour.
|
||||
kinds of behavior.
|
||||
|
||||
import coreapi
|
||||
client = coreapi.Client()
|
||||
|
@ -384,7 +384,7 @@ First, install the API documentation views. These will include the schema resour
|
|||
|
||||
urlpatterns = [
|
||||
...
|
||||
url(r'^docs/', include_docs_urls(title='My API service'))
|
||||
path('docs/', include_docs_urls(title='My API service'), name='api-docs'),
|
||||
]
|
||||
|
||||
Once the API documentation URLs are installed, you'll be able to include both the required JavaScript resources. Note that the ordering of these two lines is important, as the schema loading requires CoreAPI to already be installed.
|
||||
|
@ -401,14 +401,14 @@ Once the API documentation URLs are installed, you'll be able to include both th
|
|||
|
||||
The `coreapi` library, and the `schema` object will now both be available on the `window` instance.
|
||||
|
||||
const coreapi = window.coreapi
|
||||
const schema = window.schema
|
||||
const coreapi = window.coreapi;
|
||||
const schema = window.schema;
|
||||
|
||||
## Instantiating a client
|
||||
|
||||
In order to interact with the API you'll need a client instance.
|
||||
|
||||
var client = new coreapi.Client()
|
||||
var client = new coreapi.Client();
|
||||
|
||||
Typically you'll also want to provide some authentication credentials when
|
||||
instantiating the client.
|
||||
|
@ -421,9 +421,9 @@ the user to login, and then instantiate a client using session authentication:
|
|||
|
||||
let auth = new coreapi.auth.SessionAuthentication({
|
||||
csrfCookieName: 'csrftoken',
|
||||
csrfHeaderName: 'X-CSRFToken'
|
||||
})
|
||||
let client = new coreapi.Client({auth: auth})
|
||||
csrfHeaderName: 'X-CSRFToken',
|
||||
});
|
||||
let client = new coreapi.Client({auth: auth});
|
||||
|
||||
The authentication scheme will handle including a CSRF header in any outgoing
|
||||
requests for unsafe HTTP methods.
|
||||
|
@ -434,10 +434,10 @@ The `TokenAuthentication` class can be used to support REST framework's built-in
|
|||
`TokenAuthentication`, as well as OAuth and JWT schemes.
|
||||
|
||||
let auth = new coreapi.auth.TokenAuthentication({
|
||||
scheme: 'JWT'
|
||||
token: '<token>'
|
||||
})
|
||||
let client = new coreapi.Client({auth: auth})
|
||||
scheme: 'JWT',
|
||||
token: '<token>',
|
||||
});
|
||||
let client = new coreapi.Client({auth: auth});
|
||||
|
||||
When using TokenAuthentication you'll probably need to implement a login flow
|
||||
using the CoreAPI client.
|
||||
|
@ -448,20 +448,20 @@ request to an "obtain token" endpoint
|
|||
For example, using the "Django REST framework JWT" package
|
||||
|
||||
// Setup some globally accessible state
|
||||
window.client = new coreapi.Client()
|
||||
window.loggedIn = false
|
||||
window.client = new coreapi.Client();
|
||||
window.loggedIn = false;
|
||||
|
||||
function loginUser(username, password) {
|
||||
let action = ["api-token-auth", "obtain-token"]
|
||||
let params = {username: "example", email: "example@example.com"}
|
||||
let action = ["api-token-auth", "obtain-token"];
|
||||
let params = {username: username, password: password};
|
||||
client.action(schema, action, params).then(function(result) {
|
||||
// On success, instantiate an authenticated client.
|
||||
let auth = window.coreapi.auth.TokenAuthentication({
|
||||
scheme: 'JWT',
|
||||
token: result['token']
|
||||
token: result['token'],
|
||||
})
|
||||
window.client = coreapi.Client({auth: auth})
|
||||
window.loggedIn = true
|
||||
window.client = coreapi.Client({auth: auth});
|
||||
window.loggedIn = true;
|
||||
}).catch(function (error) {
|
||||
// Handle error case where eg. user provides incorrect credentials.
|
||||
})
|
||||
|
@ -473,23 +473,23 @@ The `BasicAuthentication` class can be used to support HTTP Basic Authentication
|
|||
|
||||
let auth = new coreapi.auth.BasicAuthentication({
|
||||
username: '<username>',
|
||||
password: '<password>'
|
||||
password: '<password>',
|
||||
})
|
||||
let client = new coreapi.Client({auth: auth})
|
||||
let client = new coreapi.Client({auth: auth});
|
||||
|
||||
## Using the client
|
||||
|
||||
Making requests:
|
||||
|
||||
let action = ["users", "list"]
|
||||
let action = ["users", "list"];
|
||||
client.action(schema, action).then(function(result) {
|
||||
// Return value is in 'result'
|
||||
})
|
||||
|
||||
Including parameters:
|
||||
|
||||
let action = ["users", "create"]
|
||||
let params = {username: "example", email: "example@example.com"}
|
||||
let action = ["users", "create"];
|
||||
let params = {username: "example", email: "example@example.com"};
|
||||
client.action(schema, action, params).then(function(result) {
|
||||
// Return value is in 'result'
|
||||
})
|
||||
|
@ -512,12 +512,12 @@ The coreapi package is available on NPM.
|
|||
|
||||
You'll either want to include the API schema in your codebase directly, by copying it from the `schema.js` resource, or else load the schema asynchronously. For example:
|
||||
|
||||
let client = new coreapi.Client()
|
||||
let schema = null
|
||||
let client = new coreapi.Client();
|
||||
let schema = null;
|
||||
client.get("https://api.example.org/").then(function(data) {
|
||||
// Load a CoreJSON API schema.
|
||||
schema = data
|
||||
console.log('schema loaded')
|
||||
schema = data;
|
||||
console.log('schema loaded');
|
||||
})
|
||||
|
||||
[heroku-api]: https://devcenter.heroku.com/categories/platform-api
|
||||
|
|
|
@ -17,7 +17,7 @@ By default, the API will return the format specified by the headers, which in th
|
|||
|
||||
## Customizing
|
||||
|
||||
The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.3.5), making it easy to customize the look-and-feel.
|
||||
The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.4.1), making it easy to customize the look-and-feel.
|
||||
|
||||
To customize the default style, create a template called `rest_framework/api.html` that extends from `rest_framework/base.html`. For example:
|
||||
|
||||
|
@ -35,7 +35,7 @@ To replace the default theme, add a `bootstrap_theme` block to your `api.html` a
|
|||
<link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css">
|
||||
{% endblock %}
|
||||
|
||||
Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above.
|
||||
Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above. Make sure that the Bootstrap version of the new theme matches that of the default theme.
|
||||
|
||||
You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style.
|
||||
|
||||
|
@ -44,7 +44,7 @@ Full example:
|
|||
{% extends "rest_framework/base.html" %}
|
||||
|
||||
{% block bootstrap_theme %}
|
||||
<link rel="stylesheet" href="https://bootswatch.com/flatly/bootstrap.min.css" type="text/css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch@3.4.1/flatly/bootstrap.min.css" type="text/css">
|
||||
{% endblock %}
|
||||
|
||||
{% block bootstrap_navbar_variant %}{% endblock %}
|
||||
|
|
|
@ -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
|
||||
request.method = request.META[METHOD_OVERRIDE_HEADER]
|
||||
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
|
||||
|
||||
|
|