Merge branch 'master' into coreapi

This commit is contained in:
Asif Saif Uddin 2022-11-29 14:51:55 +06:00 committed by GitHub
commit 3f68619a1a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
261 changed files with 17264 additions and 8930 deletions

1
.github/FUNDING.yml vendored
View File

@ -1 +1,2 @@
github: encode
custom: https://fund.django-rest-framework.org/topics/funding/

10
.github/ISSUE_TEMPLATE/1-issue.md vendored Normal file
View 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
View 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
View 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

52
.github/workflows/main.yml vendored Normal file
View File

@ -0,0 +1,52 @@
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'
- '3.11'
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
View 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
View File

@ -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
View 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

View File

@ -1,53 +0,0 @@
language: python
cache: pip
dist: bionic
matrix:
fast_finish: true
include:
- { python: "3.5", env: DJANGO=2.2 }
- { python: "3.6", env: DJANGO=2.2 }
- { python: "3.6", env: DJANGO=3.0 }
- { python: "3.6", env: DJANGO=3.1 }
- { python: "3.6", env: DJANGO=master }
- { python: "3.7", env: DJANGO=2.2 }
- { python: "3.7", env: DJANGO=3.0 }
- { python: "3.7", env: DJANGO=3.1 }
- { python: "3.7", env: DJANGO=master }
- { python: "3.8", env: DJANGO=3.0 }
- { python: "3.8", env: DJANGO=3.1 }
- { python: "3.8", env: DJANGO=master }
- { python: "3.9-dev", env: DJANGO=3.1 }
- { python: "3.9-dev", env: DJANGO=master }
- { python: "3.8", env: TOXENV=base }
- { python: "3.8", env: TOXENV=lint }
- { python: "3.8", env: TOXENV=docs }
- python: "3.8"
env: TOXENV=dist
script:
- python setup.py bdist_wheel
- rm -r djangorestframework.egg-info # see #6139
- tox --installpkg ./dist/djangorestframework-*.whl
- tox # test sdist
allow_failures:
- env: DJANGO=master
install:
- pip install tox tox-travis
script:
- tox
after_success:
- pip install codecov
- codecov -e TOXENV,DJANGO
notifications:
email: false

9
.tx/config Normal file
View 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

View File

@ -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.
>
> &mdash; [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
python3 -m venv 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 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.
## 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.

View File

@ -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

View File

@ -1,7 +1,7 @@
include README.md
include LICENSE.md
recursive-include tests/* *
recursive-include rest_framework/static *.js *.css *.png *.ico *.eot *.svg *.ttf *.woff *.woff2
recursive-include 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__

View File

@ -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

View File

@ -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,12 +21,14 @@ The initial aim is to provide a single full-time position on REST framework.
[![][sentry-img]][sentry-url]
[![][stream-img]][stream-url]
[![][rollbar-img]][rollbar-url]
[![][esg-img]][esg-url]
[![][spacinov-img]][spacinov-url]
[![][retool-img]][retool-url]
[![][bitio-img]][bitio-url]
[![][posthog-img]][posthog-url]
[![][cryptapi-img]][cryptapi-url]
[![][fezto-img]][fezto-url]
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Rollbar][rollbar-url], [ESG][esg-url], [Retool][retool-url], and [bit.io][bitio-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].
---
@ -52,8 +54,8 @@ There is a live example API for testing purposes, [available here][sandbox].
# Requirements
* Python (3.5, 3.6, 3.7, 3.8, 3.9)
* Django (2.2, 3.0, 3.1)
* 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.
@ -65,11 +67,12 @@ Install using `pip`...
pip install djangorestframework
Add `'rest_framework'` to your `INSTALLED_APPS` setting.
```python
INSTALLED_APPS = [
...
'rest_framework',
]
```
# Example
@ -87,9 +90,10 @@ Startup up a new project like so...
Now edit the `example/urls.py` module in your project:
```python
from django.urls import path, include
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets, routers
from django.urls import include, path
from rest_framework import routers, serializers, viewsets
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
@ -108,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 = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
```
@ -131,7 +134,7 @@ 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',
]
}
```
@ -168,7 +171,7 @@ 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].
@ -176,13 +179,13 @@ You may also want to [follow the author on Twitter][twitter].
Please see the [security policy][security-policy].
[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/
@ -191,17 +194,21 @@ Please see the [security policy][security-policy].
[sentry-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/sentry-readme.png
[stream-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/stream-readme.png
[rollbar-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/rollbar-readme.png
[esg-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/esg-readme.png
[spacinov-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/spacinov-readme.png
[retool-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/retool-readme.png
[bitio-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/bitio-readme.png
[posthog-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/posthog-readme.png
[cryptapi-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cryptapi-readme.png
[fezto-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/fezto-readme.png
[sentry-url]: https://getsentry.com/welcome/
[stream-url]: https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf
[rollbar-url]: https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial
[esg-url]: https://software.esg-usa.com/
[stream-url]: https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage
[spacinov-url]: https://www.spacinov.com/
[retool-url]: https://retool.com/?utm_source=djangorest&utm_medium=sponsorship
[bitio-url]: https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship
[posthog-url]: https://posthog.com?utm_source=drf&utm_medium=sponsorship&utm_campaign=open-source-sponsorship
[cryptapi-url]: https://cryptapi.io
[fezto-url]: https://www.fezto.xyz/?utm_source=DjangoRESTFramework
[oauth1-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth
[oauth2-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit

View File

@ -2,8 +2,8 @@
## Reporting a Vulnerability
If you believe you've found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**.
Security issues are handled under the supervision of the [Django security team](https://www.djangoproject.com/foundation/teams/#security-team).
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
**Please report security issues by emailing security@djangoproject.com**.
[security-mail]: mailto:rest-framework-security@googlegroups.com
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.

View File

@ -11,9 +11,9 @@ source:
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted.
REST framework provides 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.
@ -23,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].
---
@ -60,8 +60,8 @@ using the `APIView` class-based views.
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)
@ -72,8 +72,8 @@ Or, if you're using the `@api_view` decorator with function based views.
@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)
@ -120,6 +120,14 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
## TokenAuthentication
---
**Note:** The token authentication provided by Django REST framework is a fairly simple implementation.
For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the [Django REST Knox][django-rest-knox] third party package.
---
This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
To use the `TokenAuthentication` scheme you'll need to [configure the authentication classes](#setting-the-authentication-scheme) to include `TokenAuthentication`, and additionally include `rest_framework.authtoken` in your `INSTALLED_APPS` setting:
@ -129,11 +137,9 @@ To use the `TokenAuthentication` scheme you'll need to [configure the authentica
'rest_framework.authtoken'
]
---
Make sure to run `manage.py migrate` after changing your settings.
**Note:** Make sure to run `manage.py migrate` after changing your settings. The `rest_framework.authtoken` app provides Django database migrations.
---
The `rest_framework.authtoken` app provides Django database migrations.
You'll also need to create tokens for your users.
@ -146,7 +152,7 @@ For clients to authenticate, the token key should be included in the `Authorizat
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
**Note:** If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable.
*If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable.*
If successfully authenticated, `TokenAuthentication` provides the following credentials.
@ -167,9 +173,9 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
---
#### Generating Tokens
### Generating Tokens
##### By using signals
#### By using signals
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
@ -193,7 +199,7 @@ 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:
@ -210,7 +216,7 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.
By default there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply 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.
@ -242,9 +248,9 @@ And in your `urls.py`:
]
##### 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`:
@ -279,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
@ -293,7 +299,7 @@ environment variable.
To use it, you must have `django.contrib.auth.backends.RemoteUserBackend` (or a subclass) in your
`AUTHENTICATION_BACKENDS` setting. By default, `RemoteUserBackend` creates `User` objects for usernames that don't
already exist. To change this and other behaviour, consult the
already exist. To change this and other behavior, consult the
[Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/).
If successfully authenticated, `RemoteUserAuthentication` provides the following credentials:
@ -301,7 +307,7 @@ If successfully authenticated, `RemoteUserAuthentication` provides the following
* `request.user` will be a Django `User` instance.
* `request.auth` will be `None`.
Consult your web server's documentation for information about configuring an authentication method, e.g.:
Consult your web server's documentation for information about configuring an authentication method, for example:
* [Apache Authentication How-To](https://httpd.apache.org/docs/2.4/howto/auth.html)
* [NGINX (Restricting Access)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)
@ -316,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.
@ -353,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 3.4+. The package is maintained by [Evonove][evonove] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
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`.
@ -384,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`.
@ -408,7 +418,7 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
## Djoser
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and 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 / dj-rest-auth
@ -420,17 +430,23 @@ There are currently two forks of this project.
* [Django-rest-auth][django-rest-auth] is the original project, [but is not currently receiving updates](https://github.com/Tivix/django-rest-auth/issues/568).
* [Dj-rest-auth][dj-rest-auth] is a newer fork of the project.
## django-rest-framework-social-oauth2
## drf-social-oauth2
[Django-rest-framework-social-oauth2][django-rest-framework-social-oauth2] library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to "in-house" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.
## django-rest-knox
[Django-rest-knox][django-rest-knox] library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).
[Drf-social-oauth2][drf-social-oauth2] is a framework that helps you authenticate with major social oauth2 vendors, such as Facebook, Google, Twitter, Orcid, etc. It generates tokens in a JWTed way with an easy setup.
## drfpasswordless
[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
@ -448,7 +464,7 @@ There are currently two forks of this project.
[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/
@ -463,6 +479,8 @@ There are currently two forks of this project.
[djoser]: https://github.com/sunscrapers/djoser
[django-rest-auth]: https://github.com/Tivix/django-rest-auth
[dj-rest-auth]: https://github.com/jazzband/dj-rest-auth
[django-rest-framework-social-oauth2]: https://github.com/PhilipGarnero/django-rest-framework-social-oauth2
[drf-social-oauth2]: https://github.com/wagnerdelima/drf-social-oauth2
[django-rest-knox]: https://github.com/James1345/django-rest-knox
[drfpasswordless]: https://github.com/aaronn/django-rest-framework-passwordless
[django-rest-authemail]: https://github.com/celiao/django-rest-authemail
[django-rest-durin]: https://github.com/eshaan7/django-rest-durin

View File

@ -13,13 +13,13 @@ 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
from django.views.decorators.vary import vary_on_cookie, vary_on_headers
from rest_framework.response import Response
from rest_framework.views import APIView
@ -27,8 +27,7 @@ from rest_framework import viewsets
class UserViewSet(viewsets.ViewSet):
# Cache requested url for each user for 2 hours
# 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):
@ -38,8 +37,18 @@ 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):
@ -55,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

View File

@ -38,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
@ -222,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:
@ -260,6 +260,15 @@ Set as `handler400`:
handler400 = 'rest_framework.exceptions.bad_request'
# Third party packages
The following third-party packages are also available.
## DRF Standardized Errors
The [drf-standardized-errors][drf-standardized-errors] package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.
[cite]: https://doughellmann.com/blog/2009/06/19/python-exception-handling-techniques/
[authentication]: authentication.md
[django-custom-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors

View File

@ -42,11 +42,11 @@ Set to false if this field is not required to be present during deserialization.
Setting this to `False` also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.
Defaults to `True`.
Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer) default value will be `False` if you have specified `blank=True` or `default` or `null=True` at your field in your `Model`.
### `default`
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
@ -78,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.
@ -144,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.
@ -152,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
@ -172,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.
@ -223,11 +222,11 @@ A field that ensures the input is a valid UUID string. The `to_internal_value` m
**Signature:** `UUIDField(format='hex_verbose')`
- `format`: Determines the representation format of the uuid value
- `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
- `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
- `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
- `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
* `format`: Determines the representation format of the uuid value
* `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
* `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
* `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
* `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value`
## FilePathField
@ -238,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
@ -252,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'.
---
@ -267,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
@ -278,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
@ -289,13 +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`.
* `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
@ -307,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
@ -325,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.
@ -385,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.
---
@ -400,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.
@ -413,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.
@ -437,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
@ -449,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.
@ -465,10 +461,10 @@ A field class that validates a list of objects.
**Signature**: `ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)`
- `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
- `allow_empty` - Designates if empty lists are allowed.
- `min_length` - Validates that the list contains no fewer than this number of elements.
- `max_length` - Validates that the list contains no more than this number of elements.
* `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
* `allow_empty` - Designates if empty lists are allowed.
* `min_length` - Validates that the list contains no fewer than this number of elements.
* `max_length` - Validates that the list contains no more than this number of elements.
For example, to validate a list of integers you might use something like the following:
@ -489,8 +485,8 @@ A field class that validates a dictionary of objects. The keys in `DictField` ar
**Signature**: `DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
- `allow_empty` - Designates if empty dictionaries are allowed.
* `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
* `allow_empty` - Designates if empty dictionaries are allowed.
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
@ -507,8 +503,8 @@ A preconfigured `DictField` that is compatible with Django's postgres `HStoreFie
**Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
- `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
- `allow_empty` - Designates if empty dictionaries are allowed.
* `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
* `allow_empty` - Designates if empty dictionaries are allowed.
Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings.
@ -518,8 +514,8 @@ A field class that validates that the incoming data structure consists of valid
**Signature**: `JSONField(binary, encoder)`
- `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
- `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
* `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
* `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
---
@ -570,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:
@ -583,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
@ -775,7 +772,7 @@ Here the mapping between the target and source attribute pairs (`x` and
`x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField`
declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`.
Our new `DataPointSerializer` exhibits the same behaviour as the custom field
Our new `DataPointSerializer` exhibits the same behavior as the custom field
approach.
Serializing:
@ -854,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

View File

@ -75,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
@ -224,7 +224,7 @@ The search behavior may be restricted by prepending various characters to the `s
* '^' Starts-with search.
* '=' Exact matches.
* '@' Full-text search. (Currently only supported Django's [PostgreSQL backend](https://docs.djangoproject.com/en/dev/ref/contrib/postgres/search/).)
* '@' Full-text search. (Currently only supported Django's [PostgreSQL backend][postgres-search].)
* '$' Regex search.
For example:
@ -241,7 +241,7 @@ To dynamically change search fields based on request content, it's possible to s
def get_search_fields(self, view, request):
if request.query_params.get('title_only'):
return ['title']
return super(CustomSearchFilter, self).get_search_fields(view, request)
return super().get_search_fields(view, request)
For more details, see the [Django documentation][search-django-admin].
@ -335,15 +335,6 @@ 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
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:
`get_schema_fields(self, view)`
The method should return a list of `coreapi.Field` instances.
# Third party packages
The following third party packages provide additional filter implementations.
@ -374,3 +365,4 @@ The [djangorestframework-word-filter][django-rest-framework-word-search-filter]
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
[HStoreField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#hstorefield
[JSONField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#jsonfield
[postgres-search]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/search/

View File

@ -65,7 +65,7 @@ The following attributes control the basic view behavior.
* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. If you are overriding a view method, it is important that you call `get_queryset()` instead of accessing this property directly, as `queryset` will get evaluated once, and those results will be cached for all subsequent requests.
* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method.
* `lookup_field` - The model field that should be used to for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
* `lookup_field` - The model field that should be used for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
* `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`.
**Pagination**:
@ -96,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.
@ -211,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
@ -329,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)
@ -389,3 +395,4 @@ The following third party packages provide additional generic view implementatio
[UpdateModelMixin]: #updatemodelmixin
[DestroyModelMixin]: #destroymodelmixin
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related

View File

@ -78,7 +78,7 @@ This pagination style accepts a single number page number in the request query p
HTTP 200 OK
{
"count": 1023
"count": 1023,
"next": "https://api.example.org/accounts/?page=5",
"previous": "https://api.example.org/accounts/?page=3",
"results": [
@ -126,7 +126,7 @@ This pagination style mirrors the syntax used when looking up multiple database
HTTP 200 OK
{
"count": 1023
"count": 1023,
"next": "https://api.example.org/accounts/?limit=100&offset=500",
"previous": "https://api.example.org/accounts/?limit=100&offset=300",
"results": [
@ -218,10 +218,10 @@ 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.
@ -264,15 +264,6 @@ API responses for list endpoints will now include a `Link` header, instead of in
*A custom pagination style, using the 'Link' header'*
## Pagination & schemas
You can also make the pagination controls available to the schema autogeneration
that REST framework provides, by implementing a `get_schema_fields()` method. This method should have the following signature:
`get_schema_fields(self, view)`
The method should return a list of `coreapi.Field` instances.
---
# HTML pagination controls
@ -312,7 +303,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
@ -322,3 +313,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

View File

@ -73,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`
@ -87,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.

View File

@ -24,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. *&mdash; 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. *&mdash; An HTTP 403 Forbidden response will be returned.*
@ -70,6 +70,8 @@ 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.
@ -116,7 +118,7 @@ Or, if you're using the `@api_view` decorator with function based views.
}
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:
@ -169,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.
@ -278,6 +274,30 @@ 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
@ -304,6 +324,10 @@ The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to
The [Django Rest Framework Roles][django-rest-framework-roles] package makes it easier to parameterize your API over multiple types of users.
## Rest Framework Roles
The [Rest Framework Roles][rest-framework-roles] makes it super easy to protect views based on roles. Most importantly allows you to decouple accessibility logic from models and views in a clean human-readable way.
## Django REST Framework API Key
The [Django REST Framework API Key][djangorestframework-api-key] package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. _machines_) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.
@ -329,6 +353,7 @@ The [Django Rest Framework PSQ][drf-psq] package is an extension that gives supp
[rest-condition]: https://github.com/caxap/rest_condition
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
[django-rest-framework-roles]: https://github.com/computer-lab/django-rest-framework-roles
[rest-framework-roles]: https://github.com/Pithikos/rest-framework-roles
[djangorestframework-api-key]: https://florimondmanca.github.io/djangorestframework-api-key/
[django-rest-framework-role-filters]: https://github.com/allisson/django-rest-framework-role-filters
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian

View File

@ -17,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.
@ -463,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`.
@ -603,6 +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/2.2/topics/db/models/#intermediary-manytomany
[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

View File

@ -103,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.
@ -247,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.
@ -257,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.
@ -281,7 +291,7 @@ The following is an example plaintext renderer that will return a response with
media_type = 'text/plain'
format = 'txt'
def render(self, data, media_type=None, renderer_context=None):
def render(self, data, accepted_media_type=None, renderer_context=None):
return smart_text(data, encoding=self.charset)
## Setting the character set
@ -293,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.
@ -308,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
---
@ -322,7 +332,7 @@ You can do some pretty flexible things using REST framework's renderers. Some e
* Specify multiple types of HTML representation for API clients to use.
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
## Varying behaviour by media type
## Varying behavior by media type
In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
@ -460,15 +470,15 @@ Modify your REST framework settings.
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
## XLSX (Binary Spreadsheet Endpoints)
## Microsoft Excel: XLSX (Binary Spreadsheet Endpoints)
XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-renderer-xlsx][drf-renderer-xlsx], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-excel][drf-excel], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
#### Installation & configuration
Install using pip.
$ pip install drf-renderer-xlsx
$ pip install drf-excel
Modify your REST framework settings.
@ -478,15 +488,15 @@ Modify your REST framework settings.
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
'drf_renderer_xlsx.renderers.XLSXRenderer',
'drf_excel.renderers.XLSXRenderer',
],
}
To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the `Content-Disposition` header. If no filename is provided, it will default to `export.xlsx`. For example:
from rest_framework.viewsets import ReadOnlyModelViewSet
from drf_renderer_xlsx.mixins import XLSXFileMixin
from drf_renderer_xlsx.renderers import XLSXRenderer
from drf_excel.mixins import XLSXFileMixin
from drf_excel.renderers import XLSXRenderer
from .models import MyExampleModel
from .serializers import MyExampleSerializer
@ -518,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
@ -539,7 +549,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
[mjumbewu]: https://github.com/mjumbewu
[flipperpa]: https://github.com/flipperpa
[wharton]: https://github.com/wharton
[drf-renderer-xlsx]: https://github.com/wharton/drf-renderer-xlsx
[drf-excel]: https://github.com/wharton/drf-excel
[vbabiy]: https://github.com/vbabiy
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/

View File

@ -23,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].
@ -49,7 +49,7 @@ If a client sends a request with a content-type that cannot be parsed then a `Un
# Content negotiation
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialization schemes for different media types.
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behavior such as selecting a different serialization schemes for different media types.
## .accepted_renderer
@ -136,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

View File

@ -338,5 +338,5 @@ The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions
[drf-extensions-nested-viewsets]: https://chibisov.github.io/drf-extensions/docs/#nested-routes
[drf-extensions-collection-level-controllers]: https://chibisov.github.io/drf-extensions/docs/#collection-level-controllers
[drf-extensions-customizable-endpoint-names]: https://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name
[url-namespace-docs]: https://docs.djangoproject.com/en/1.11/topics/http/urls/#url-namespaces
[include-api-reference]: https://docs.djangoproject.com/en/2.0/ref/urls/#include
[url-namespace-docs]: https://docs.djangoproject.com/en/4.0/topics/http/urls/#url-namespaces
[include-api-reference]: https://docs.djangoproject.com/en/4.0/ref/urls/#include

View File

@ -9,6 +9,23 @@ source:
>
> &mdash; Heroku, [JSON Schema for the Heroku Platform API][cite]
---
**Deprecation notice:**
REST framework's built-in support for generating OpenAPI schemas is
**deprecated** in favor of 3rd party packages that can provide this
functionality instead. The built-in support will be moved into a separate
package and then subsequently retired over the next releases.
As a full-fledged replacement, we recommend the [drf-spectacular] package.
It has extensive support for generating OpenAPI 3 schemas from
REST framework APIs, with both automatic and customisable options available.
For further information please refer to
[Documenting your API](../topics/documenting-your-api.md#drf-spectacular).
---
API schemas are a useful tool that allow for a range of use cases, including
generating reference documentation, or driving dynamic client libraries that
can interact with your API.
@ -122,6 +139,7 @@ The `get_schema_view()` helper takes the following keyword arguments:
url='https://www.example.org/api/',
patterns=schema_url_patterns,
)
* `public`: May be used to specify if schema should bypass views permissions. Default to False
* `generator_class`: May be used to specify a `SchemaGenerator` subclass to be
passed to the `SchemaView`.
@ -165,7 +183,7 @@ In order to customize the top-level schema, subclass
as an argument to the `generateschema` command or `get_schema_view()` helper
function.
### get_schema(self, request)
### get_schema(self, request=None, public=False)
Returns a dictionary that represents the OpenAPI schema:
@ -313,6 +331,11 @@ Computes the component's name from the serializer.
You may see warnings if your API has duplicate component names. If so you can override `get_component_name()` or pass the `component_name` `__init__()` kwarg (see below) to provide different names.
#### `get_reference()`
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
#### `map_serializer()`
Maps serializers to their OpenAPI representations.
@ -375,6 +398,20 @@ operationIds.
In order to work around this, you can override `get_operation_id_base()` to
provide a different base for name part of the ID.
#### `get_serializer()`
If the view has implemented `get_serializer()`, returns the result.
#### `get_request_serializer()`
By default returns `get_serializer()` but can be overridden to
differentiate between request and response objects.
#### `get_response_serializer()`
By default returns `get_serializer()` but can be overridden to
differentiate between request and response objects.
### `AutoSchema.__init__()` kwargs
`AutoSchema` provides a number of `__init__()` kwargs that can be used for
@ -407,6 +444,7 @@ If your views have related customizations that are needed frequently, you can
create a base `AutoSchema` subclass for your project that takes additional
`__init__()` kwargs to save subclassing `AutoSchema` for each view.
[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api
[openapi]: https://github.com/OAI/OpenAPI-Specification
[openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions
[openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject
@ -417,3 +455,4 @@ create a base `AutoSchema` subclass for your project that takes additional
[openapi-generator]: https://github.com/OpenAPITools/openapi-generator
[swagger-codegen]: https://github.com/swagger-api/swagger-codegen
[info-object]: https://swagger.io/specification/#infoObject
[drf-spectacular]: https://drf-spectacular.readthedocs.io/en/latest/readme.html

View File

@ -116,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()`
@ -282,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)
@ -524,6 +524,7 @@ You can add extra fields to a `ModelSerializer` or override the default fields b
class Meta:
model = Account
fields = ['url', 'groups']
Extra fields can correspond to any property or callable on the model.
@ -593,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 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`.
@ -621,13 +622,13 @@ Defaults to `serializers.ChoiceField`
The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`.
### `.build_standard_field(self, field_name, model_field)`
### `build_standard_field(self, field_name, model_field)`
Called to generate a serializer field that maps to a standard model field.
The default implementation returns a serializer class based on the `serializer_field_mapping` attribute.
### `.build_relational_field(self, field_name, relation_info)`
### `build_relational_field(self, field_name, relation_info)`
Called to generate a serializer field that maps to a relational model field.
@ -635,7 +636,7 @@ The default implementation returns a serializer class based on the `serializer_r
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
### `.build_nested_field(self, field_name, relation_info, nested_depth)`
### `build_nested_field(self, field_name, relation_info, nested_depth)`
Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set.
@ -645,17 +646,17 @@ The `nested_depth` will be the value of the `depth` option, minus one.
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
### `.build_property_field(self, field_name, model_class)`
### `build_property_field(self, field_name, model_class)`
Called to generate a serializer field that maps to a property or zero-argument method on the model class.
The default implementation returns a `ReadOnlyField` class.
### `.build_url_field(self, field_name, model_class)`
### `build_url_field(self, field_name, model_class)`
Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class.
### `.build_unknown_field(self, field_name, model_class)`
### `build_unknown_field(self, field_name, model_class)`
Called when the field name did not map to any model field or model property.
The default implementation raises an error, although subclasses may customize this behavior.
@ -755,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:
@ -877,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:
@ -911,7 +920,7 @@ Or use it to serialize multiple instances:
serializer = HighScoreSerializer(queryset, many=True)
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.
@ -960,7 +969,7 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.
The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
The following class is an example of a generic serializer that can handle coercing arbitrary complex objects into primitive representations.
class ObjectSerializer(serializers.BaseSerializer):
"""
@ -1012,7 +1021,7 @@ Some reasons this might be useful include...
The signatures for these methods are as follows:
#### `.to_representation(self, instance)`
#### `to_representation(self, instance)`
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
@ -1024,7 +1033,7 @@ May be overridden in order to modify the representation style. For example:
ret['username'] = ret['username'].lower()
return ret
#### ``.to_internal_value(self, data)``
#### ``to_internal_value(self, data)``
Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
@ -1087,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.

View File

@ -41,6 +41,8 @@ This class of status code indicates a provisional response. There are no 1xx st
HTTP_100_CONTINUE
HTTP_101_SWITCHING_PROTOCOLS
HTTP_102_PROCESSING
HTTP_103_EARLY_HINTS
## Successful - 2xx
@ -93,9 +95,11 @@ The 4xx class of status code is intended for cases in which the client seems to
HTTP_415_UNSUPPORTED_MEDIA_TYPE
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
HTTP_417_EXPECTATION_FAILED
HTTP_421_MISDIRECTED_REQUEST
HTTP_422_UNPROCESSABLE_ENTITY
HTTP_423_LOCKED
HTTP_424_FAILED_DEPENDENCY
HTTP_425_TOO_EARLY
HTTP_426_UPGRADE_REQUIRED
HTTP_428_PRECONDITION_REQUIRED
HTTP_429_TOO_MANY_REQUESTS

View File

@ -234,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...
@ -259,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.
@ -299,7 +299,7 @@ similar way as with `RequestsClient`.
# API Test cases
REST framework includes the following test case classes, that mirror the existing Django test case classes, but use `APIClient` instead of Django's default `Client`.
REST framework includes the following test case classes, that mirror the existing [Django's test case classes][provided_test_case_classes], but use `APIClient` instead of Django's default `Client`.
* `APISimpleTestCase`
* `APITransactionTestCase`
@ -413,5 +413,6 @@ For example, to add support for using `format='html'` in test requests, you migh
[client]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#the-test-client
[requestfactory]: https://docs.djangoproject.com/en/stable/topics/testing/advanced/#django.test.client.RequestFactory
[configuration]: #configuration
[refresh_from_db_docs]: https://docs.djangoproject.com/en/1.11/ref/models/instances/#django.db.models.Model.refresh_from_db
[refresh_from_db_docs]: https://docs.djangoproject.com/en/stable/ref/models/instances/#django.db.models.Model.refresh_from_db
[session_objects]: https://requests.readthedocs.io/en/master/user/advanced/#session-objects
[provided_test_case_classes]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#provided-test-case-classes

View File

@ -19,6 +19,10 @@ Multiple throttles can also be used if you want to impose both burst throttling
Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.
**The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins. In addition to this, the built-in throttling implementations are implemented using Django's cache framework, and use non-atomic operations to determine the request rate, which may sometimes result in some fuzziness.
The application-level throttling provided by REST framework is intended for implementing policies such as different business tiers and basic protections against service over-use.**
## How throttling is determined
As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
@ -59,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])
@ -69,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.
@ -92,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
@ -200,3 +220,5 @@ The following is an example of a rate throttle, that will randomly throttle 1 in
[identifying-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster
[cache-setting]: https://docs.djangoproject.com/en/stable/ref/settings/#caches
[cache-docs]: https://docs.djangoproject.com/en/stable/topics/cache/#setting-up-the-cache
[gh5181]: https://github.com/encode/django-rest-framework/issues/5181
[race]: https://en.wikipedia.org/wiki/Race_condition#Data_race

View File

@ -208,7 +208,7 @@ by specifying an empty list for the serializer `Meta.validators` attribute.
By default "unique together" validation enforces that all fields be
`required=True`. In some cases, you might want to explicit apply
`required=False` to one of the fields, in which case the desired behaviour
`required=False` to one of the fields, in which case the desired behavior
of the validation is ambiguous.
In this case you will typically need to exclude the validator from the
@ -238,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

View File

@ -145,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):
@ -152,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):

View File

@ -116,7 +116,7 @@ During dispatch, the following attributes are available on the `ViewSet`.
* `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`.
* `description` - the display description for the individual view of a viewset.
You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
You may inspect these attributes to adjust behavior based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
def get_permissions(self):
"""
@ -125,7 +125,7 @@ You may inspect these attributes to adjust behaviour based on the current action
if self.action == 'list':
permission_classes = [IsAuthenticated]
else:
permission_classes = [IsAdmin]
permission_classes = [IsAdminUser]
return [permission() for permission in permission_classes]
## Marking extra actions for routing
@ -152,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:
@ -171,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:
@ -183,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.

View File

@ -632,7 +632,7 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the 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."""

View File

@ -142,6 +142,6 @@ continued development by **[signing up for a paid plan][funding]**.
*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
[legacy-core-api-docs]:https://github.com/encode/django-rest-framework/blob/3.14.0/docs/coreapi/index.md
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[funding]: funding.md

View 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.

View 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.

View File

@ -187,7 +187,7 @@ The full set of itemized release notes [are available here][release-notes].
[api-blueprint]: https://apiblueprint.org/
[tut-7]: ../tutorial/7-schemas-and-client-libraries/
[schema-generation]: ../api-guide/schemas/
[api-clients]: ../topics/api-clients.md
[api-clients]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md
[milestone]: https://github.com/encode/django-rest-framework/milestone/35
[release-notes]: release-notes#34
[metadata]: ../api-guide/metadata/#custom-metadata-classes

View File

@ -195,5 +195,5 @@ on realtime support, for the 3.7 release.
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[funding]: funding.md
[api-docs]: ../topics/documenting-your-api.md
[js-docs]: ../topics/api-clients.md#javascript-client-library
[py-docs]: ../topics/api-clients.md#python-client-library
[js-docs]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md#javascript-client-library
[py-docs]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md#python-client-library

View File

@ -110,7 +110,7 @@ You can now compose permission classes using the and/or operators, `&` and `|`.
For example...
```python
permission_classes = [IsAuthenticated & (ReadOnly | IsAdmin)]
permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)]
```
If you're using custom permission classes then make sure that you are subclassing

View File

@ -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,11 +59,19 @@ 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
@ -67,7 +80,7 @@ To run the tests, clone the repository, and then:
# Setup the virtual environment
python3 -m venv env
source env/bin/activate
pip install django
pip install -e .
pip install -r requirements.txt
# Run the tests
@ -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
@ -123,11 +124,11 @@ GitHub's documentation for working on pull requests is [available here][pull-req
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

View File

@ -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.

View File

@ -11,11 +11,12 @@ Looking for a new Django REST Framework related role? On this site we provide a
* [https://djangojobs.net/jobs/][django-jobs-net]
* [https://findwork.dev/django-rest-framework-jobs][findwork-dev]
* [https://www.indeed.com/q-Django-jobs.html][indeed-com]
* [https://stackoverflow.com/jobs/developer-jobs-using-django][stackoverflow-com]
* [https://stackoverflow.com/jobs/companies?tl=django][stackoverflow-com]
* [https://www.upwork.com/o/jobs/browse/skill/django-framework/][upwork-com]
* [https://www.technojobs.co.uk/django-jobs][technobjobs-co-uk]
* [https://remoteok.io/remote-django-jobs][remoteok-io]
* [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].
@ -29,11 +30,12 @@ Wonder how else you can help? One of the best ways you can help Django REST Fram
[django-jobs-net]: https://djangojobs.net/jobs/
[findwork-dev]: https://findwork.dev/django-rest-framework-jobs
[indeed-com]: https://www.indeed.com/q-Django-jobs.html
[stackoverflow-com]: https://stackoverflow.com/jobs/developer-jobs-using-django
[stackoverflow-com]: https://stackoverflow.com/jobs/companies?tl=django
[upwork-com]: https://www.upwork.com/o/jobs/browse/skill/django-framework/
[technobjobs-co-uk]: https://www.technojobs.co.uk/django-jobs
[remoteok-io]: https://remoteok.io/remote-django-jobs
[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

View File

@ -34,8 +34,79 @@ 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
@ -169,6 +240,8 @@ Date: 28th September 2020
* 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
@ -2262,6 +2335,7 @@ For older release notes, [please see the version 2.x documentation][old-release-
<!-- 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

View File

@ -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 cookiecutter 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 every time 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
@ -214,17 +82,19 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [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
* [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
@ -236,6 +106,7 @@ 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
@ -276,13 +147,14 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [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/
@ -308,12 +180,13 @@ 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
[drf-extra-fields]: https://github.com/Hipo/drf-extra-fields
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
[wq.db.rest]: https://wq.io/docs/about-rest
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
[nested-multipart-parser]: https://github.com/remigermain/nested-multipart-parser
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
[drf_ujson2]: https://github.com/Amertz08/drf_ujson2
[rest-pandas]: https://github.com/wq/django-rest-pandas
@ -324,7 +197,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
[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
@ -362,3 +235,9 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
[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

View File

@ -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 + SlackPart 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]
@ -95,7 +96,7 @@ Want your Django REST Framework talk/tutorial/article to be added to our website
[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
@ -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/

View File

@ -1,231 +0,0 @@
# Tutorial 7: Schemas & client libraries
A schema is a machine-readable document that describes the available API
endpoints, their URLS, and what operations they support.
Schemas can be a useful tool for auto-generated documentation, and can also
be used to drive dynamic client libraries that can interact with the API.
## Core API
In order to provide schema support REST framework uses [Core API][coreapi].
Core API is a document specification for describing APIs. It is used to provide
an internal representation format of the available endpoints and possible
interactions that an API exposes. It can either be used server-side, or
client-side.
When used server-side, Core API allows an API to support rendering to a wide
range of schema or hypermedia formats.
When used client-side, Core API allows for dynamically driven client libraries
that can interact with any API that exposes a supported schema or hypermedia
format.
## Adding a schema
REST framework supports either explicitly defined schema views, or
automatically generated schemas. Since we're using viewsets and routers,
we can simply use the automatic schema generation.
You'll need to install the `coreapi` python package in order to include an
API schema, and `pyyaml` to render the schema into the commonly used
YAML-based OpenAPI format.
$ pip install coreapi pyyaml
We can now include a schema for our API, by including an autogenerated schema
view in our URL configuration.
```python
from rest_framework.schemas import get_schema_view
schema_view = get_schema_view(title='Pastebin API')
urlpatterns = [
   path('schema/', schema_view),
...
]
```
If you visit the `/schema/` endpoint in a browser you should now see `corejson`
representation become available as an option.
![Schema format](../img/corejson-format.png)
We can also request the schema from the command line, by specifying the desired
content type in the `Accept` header.
$ http http://127.0.0.1:8000/schema/ Accept:application/coreapi+json
HTTP/1.0 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/coreapi+json
{
"_meta": {
"title": "Pastebin API"
},
"_type": "document",
...
The default output style is to use the [Core JSON][corejson] encoding.
Other schema formats, such as [Open API][openapi] (formerly Swagger) are
also supported.
## Using a command line client
Now that our API is exposing a schema endpoint, we can use a dynamic client
library to interact with the API. To demonstrate this, let's use the
Core API command line client.
The command line client is available as the `coreapi-cli` package:
$ pip install coreapi-cli
Now check that it is available on the command line...
$ coreapi
Usage: coreapi [OPTIONS] COMMAND [ARGS]...
Command line client for interacting with CoreAPI services.
Visit https://www.coreapi.org/ for more information.
Options:
--version Display the package version number.
--help Show this message and exit.
Commands:
...
First we'll load the API schema using the command line client.
$ coreapi get http://127.0.0.1:8000/schema/
<Pastebin API "http://127.0.0.1:8000/schema/">
snippets: {
highlight(id)
list()
read(id)
}
users: {
list()
read(id)
}
We haven't authenticated yet, so right now we're only able to see the read only
endpoints, in line with how we've set up the permissions on the API.
Let's try listing the existing snippets, using the command line client:
$ coreapi action snippets list
[
{
"url": "http://127.0.0.1:8000/snippets/1/",
"id": 1,
"highlight": "http://127.0.0.1:8000/snippets/1/highlight/",
"owner": "lucy",
"title": "Example",
"code": "print('hello, world!')",
"linenos": true,
"language": "python",
"style": "friendly"
},
...
Some of the API endpoints require named parameters. For example, to get back
the highlight HTML for a particular snippet we need to provide an id.
$ coreapi action snippets highlight --param id=1
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Example</title>
...
## Authenticating our client
If we want to be able to create, edit and delete snippets, we'll need to
authenticate as a valid user. In this case we'll just use basic auth.
Make sure to replace the `<username>` and `<password>` below with your
actual username and password.
$ coreapi credentials add 127.0.0.1 <username>:<password> --auth basic
Added credentials
127.0.0.1 "Basic <...>"
Now if we fetch the schema again, we should be able to see the full
set of available interactions.
$ coreapi reload
Pastebin API "http://127.0.0.1:8000/schema/">
snippets: {
create(code, [title], [linenos], [language], [style])
delete(id)
highlight(id)
list()
partial_update(id, [title], [code], [linenos], [language], [style])
read(id)
update(id, code, [title], [linenos], [language], [style])
}
users: {
list()
read(id)
}
We're now able to interact with these endpoints. For example, to create a new
snippet:
$ coreapi action snippets create --param title="Example" --param code="print('hello, world')"
{
"url": "http://127.0.0.1:8000/snippets/7/",
"id": 7,
"highlight": "http://127.0.0.1:8000/snippets/7/highlight/",
"owner": "lucy",
"title": "Example",
"code": "print('hello, world')",
"linenos": false,
"language": "python",
"style": "friendly"
}
And to delete a snippet:
$ coreapi action snippets delete --param id=7
As well as the command line client, developers can also interact with your
API using client libraries. The Python client library is the first of these
to be available, and a Javascript client library is planned to be released
soon.
For more details on customizing schema generation and using Core API
client libraries you'll need to refer to the full documentation.
## Reviewing our work
With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browsable, includes a schema-driven client library, and comes complete with authentication, per-object permissions, and multiple renderer formats.
We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.
You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox].
## Onwards and upwards
We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here are a few places you can start:
* Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests.
* Join the [REST framework discussion group][group], and help build the community.
* Follow [the author][twitter] on Twitter and say hi.
**Now go build awesome things.**
[coreapi]: https://www.coreapi.org/
[corejson]: https://www.coreapi.org/specification/encoding/#core-json-encoding
[openapi]: https://openapis.org/
[repo]: https://github.com/encode/rest-framework-tutorial
[sandbox]: https://restframework.herokuapp.com/
[github]: https://github.com/encode/django-rest-framework
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[twitter]: https://twitter.com/_tomchristie

View File

@ -1,171 +0,0 @@
## Built-in API documentation
The built-in API documentation includes:
* Documentation of API endpoints.
* Automatically generated code samples for each of the available API client libraries.
* Support for API interaction.
### Installation
The `coreapi` library is required as a dependency for the API docs. Make sure
to install the latest version. The `Pygments` and `Markdown` libraries
are optional but recommended.
To install the API documentation, you'll need to include it in your project's URLconf:
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
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 behaviour, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
# Generate schema with valid `request` instance:
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

View File

@ -1,29 +0,0 @@
# Legacy CoreAPI Schemas Docs
Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation in Django REST Framework v3.10.
See the [Version 3.10 Release Announcement](/community/3.10-announcement.md) for more details.
----
You can continue to use CoreAPI schemas by setting the appropriate default schema class:
```python
# In settings.py
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
```
Under-the-hood, any subclass of `coreapi.AutoSchema` here will trigger use of the old CoreAPI schemas.
**Otherwise** you will automatically be opted-in to the new OpenAPI schemas.
All CoreAPI related code will be removed in Django REST Framework v3.12. Switch to OpenAPI schemas by then.
----
For reference this folder contains the old CoreAPI related documentation:
* [Tutorial 7: Schemas & client libraries](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//7-schemas-and-client-libraries.md).
* [Excerpts from _Documenting your API_ topic page](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//from-documenting-your-api.md).
* [`rest_framework.schemas` API Reference](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//schemas.md).

View File

@ -1,846 +0,0 @@
source: schemas.py
# Schemas
> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.
>
> &mdash; 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 behaviour you want. For example, you can apply different
permission, throttling, or authentication policies to the schema endpoint.
Here's an example of using `SchemaGenerator` together with a view to
return the schema.
**views.py:**
from rest_framework.decorators import api_view, renderer_classes
from rest_framework import renderers, response, schemas
generator = schemas.SchemaGenerator(title='Bookings API')
@api_view()
@renderer_classes([renderers.OpenAPIRenderer])
def schema_view(request):
schema = generator.get_schema(request)
return response.Response(schema)
**urls.py:**
urlpatterns = [
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

BIN
docs/img/build-status.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.8 KiB

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.8 KiB

View File

@ -20,8 +20,8 @@
<p class="badges" height=20px>
<iframe src="https://ghbtns.com/github-btn.html?user=encode&amp;repo=django-rest-framework&amp;type=watch&amp;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/">
@ -67,15 +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://software.esg-usa.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/esg-new-logo.png)">ESG</a></li>
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
<li><a href="https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
<li><a href="https://www.spacinov.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/spacinov.png)">Spacinov</a></li>
<li><a href="https://retool.com/?utm_source=djangorest&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/retool-sidebar.png)">Retool</a></li>
<li><a href="https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/bitio_logo_gold_background.png)">bit.io</a></li>
<li><a href="https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/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), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), and [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship).*
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage), [Spacinov](https://www.spacinov.com/), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [PostHog](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [CryptAPI](https://cryptapi.io), and [FEZTO](https://www.fezto.xyz/?utm_source=DjangoRESTFramework).*
---
@ -83,8 +85,8 @@ continued development by **[signing up for a paid plan][funding]**.
REST framework requires the following:
* Python (3.5, 3.6, 3.7, 3.8, 3.9)
* Django (2.2, 3.0, 3.1)
* Python (3.6, 3.7, 3.8, 3.9, 3.10, 3.11)
* 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.
@ -186,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 youve 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
@ -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

View File

@ -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

View File

@ -1,527 +0,0 @@
# API Clients
An API client handles the underlying details of how network requests are made
and how responses are decoded. They present the developer with an application
interface to work against, rather than working directly with the network interface.
The API clients documented here are not restricted to APIs built with Django REST framework.
They can be used with any API that exposes a supported schema format.
For example, [the Heroku platform API][heroku-api] exposes a schema in the JSON
Hyperschema format. As a result, the Core API command line client and Python
client library can be [used to interact with the Heroku API][heroku-example].
## Client-side Core API
[Core API][core-api] is a document specification that can be used to describe APIs. It can
be used either server-side, as is done with REST framework's [schema generation][schema-generation],
or used client-side, as described here.
When used client-side, Core API allows for *dynamically driven client libraries*
that can interact with any API that exposes a supported schema or hypermedia
format.
Using a dynamically driven client has a number of advantages over interacting
with an API by building HTTP requests directly.
#### More meaningful interaction
API interactions are presented in a more meaningful way. You're working at
the application interface layer, rather than the network interface layer.
#### Resilience & evolvability
The client determines what endpoints are available, what parameters exist
against each particular endpoint, and how HTTP requests are formed.
This also allows for a degree of API evolvability. URLs can be modified
without breaking existing clients, or more efficient encodings can be used
on-the-wire, with clients transparently upgrading.
#### Self-descriptive APIs
A dynamically driven client is able to present documentation on the API to the
end user. This documentation allows the user to discover the available endpoints
and parameters, and better understand the API they are working with.
Because this documentation is driven by the API schema it will always be fully
up to date with the most recently deployed version of the service.
---
# Command line client
The command line client allows you to inspect and interact with any API that
exposes a supported schema format.
## Getting started
To install the Core API command line client, use `pip`.
Note that the command-line client is a separate package to the
python client library. Make sure to install `coreapi-cli`.
$ pip install coreapi-cli
To start inspecting and interacting with an API the schema must first be loaded
from the network.
$ coreapi get http://api.example.org/
<Pastebin API "http://127.0.0.1:8000/">
snippets: {
create(code, [title], [linenos], [language], [style])
destroy(pk)
highlight(pk)
list([page])
partial_update(pk, [title], [code], [linenos], [language], [style])
retrieve(pk)
update(pk, code, [title], [linenos], [language], [style])
}
users: {
list([page])
retrieve(pk)
}
This will then load the schema, displaying the resulting `Document`. This
`Document` includes all the available interactions that may be made against the API.
To interact with the API, use the `action` command. This command requires a list
of keys that are used to index into the link.
$ coreapi action users list
[
{
"url": "http://127.0.0.1:8000/users/2/",
"id": 2,
"username": "aziz",
"snippets": []
},
...
]
To inspect the underlying HTTP request and response, use the `--debug` flag.
$ coreapi action users list --debug
> GET /users/ HTTP/1.1
> Accept: application/vnd.coreapi+json, */*
> Authorization: Basic bWF4Om1heA==
> Host: 127.0.0.1
> User-Agent: coreapi
< 200 OK
< Allow: GET, HEAD, OPTIONS
< Content-Type: application/json
< Date: Thu, 30 Jun 2016 10:51:46 GMT
< Server: WSGIServer/0.1 Python/2.7.10
< Vary: Accept, Cookie
<
< [{"url":"http://127.0.0.1/users/2/","id":2,"username":"aziz","snippets":[]},{"url":"http://127.0.0.1/users/3/","id":3,"username":"amy","snippets":["http://127.0.0.1/snippets/3/"]},{"url":"http://127.0.0.1/users/4/","id":4,"username":"max","snippets":["http://127.0.0.1/snippets/4/","http://127.0.0.1/snippets/5/","http://127.0.0.1/snippets/6/","http://127.0.0.1/snippets/7/"]},{"url":"http://127.0.0.1/users/5/","id":5,"username":"jose","snippets":[]},{"url":"http://127.0.0.1/users/6/","id":6,"username":"admin","snippets":["http://127.0.0.1/snippets/1/","http://127.0.0.1/snippets/2/"]}]
[
...
]
Some actions may include optional or required parameters.
$ coreapi action users create --param username=example
When using `--param`, the type of the input will be determined automatically.
If you want to be more explicit about the parameter type then use `--data` for
any null, numeric, boolean, list, or object inputs, and use `--string` for string inputs.
$ coreapi action users edit --string username=tomchristie --data is_admin=true
## Authentication & headers
The `credentials` command is used to manage the request `Authentication:` header.
Any credentials added are always linked to a particular domain, so as to ensure
that credentials are not leaked across differing APIs.
The format for adding a new credential is:
$ coreapi credentials add <domain> <credentials string>
For instance:
$ coreapi credentials add api.example.org "Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"
The optional `--auth` flag also allows you to add specific types of authentication,
handling the encoding for you. Currently only `"basic"` is supported as an option here.
For example:
$ coreapi credentials add api.example.org tomchristie:foobar --auth basic
You can also add specific request headers, using the `headers` command:
$ coreapi headers add api.example.org x-api-version 2
For more information and a listing of the available subcommands use `coreapi
credentials --help` or `coreapi headers --help`.
## Codecs
By default the command line client only includes support for reading Core JSON
schemas, however it includes a plugin system for installing additional codecs.
$ pip install openapi-codec jsonhyperschema-codec hal-codec
$ coreapi codecs show
Codecs
corejson application/vnd.coreapi+json encoding, decoding
hal application/hal+json encoding, decoding
openapi application/openapi+json encoding, decoding
jsonhyperschema application/schema+json decoding
json application/json data
text text/* data
## Utilities
The command line client includes functionality for bookmarking API URLs
under a memorable name. For example, you can add a bookmark for the
existing API, like so...
$ coreapi bookmarks add accountmanagement
There is also functionality for navigating forward or backward through the
history of which API URLs have been accessed.
$ coreapi history show
$ coreapi history back
For more information and a listing of the available subcommands use
`coreapi bookmarks --help` or `coreapi history --help`.
## Other commands
To display the current `Document`:
$ coreapi show
To reload the current `Document` from the network:
$ coreapi reload
To load a schema file from disk:
$ coreapi load my-api-schema.json --format corejson
To dump the current document to console in a given format:
$ coreapi dump --format openapi
To remove the current document, along with all currently saved history,
credentials, headers and bookmarks:
$ coreapi clear
---
# Python client library
The `coreapi` Python package allows you to programmatically interact with any
API that exposes a supported schema format.
## Getting started
You'll need to install the `coreapi` package using `pip` before you can get
started.
$ pip install coreapi
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.
import coreapi
client = coreapi.Client()
Once we have a `Client` instance, we can fetch an API schema from the network.
schema = client.get('https://api.example.org/')
The object returned from this call will be a `Document` instance, which is
a representation of the API schema.
## Authentication
Typically you'll also want to provide some authentication credentials when
instantiating the client.
#### Token authentication
The `TokenAuthentication` class can be used to support REST framework's built-in
`TokenAuthentication`, as well as OAuth and JWT schemes.
auth = coreapi.auth.TokenAuthentication(
scheme='JWT',
token='<token>'
)
client = coreapi.Client(auth=auth)
When using TokenAuthentication you'll probably need to implement a login flow
using the CoreAPI client.
A suggested pattern for this would be to initially make an unauthenticated client
request to an "obtain token" endpoint
For example, using the "Django REST framework JWT" package
client = coreapi.Client()
schema = client.get('https://api.example.org/')
action = ['api-token-auth', 'create']
params = {"username": "example", "password": "secret"}
result = client.action(schema, action, params)
auth = coreapi.auth.TokenAuthentication(
scheme='JWT',
token=result['token']
)
client = coreapi.Client(auth=auth)
#### Basic authentication
The `BasicAuthentication` class can be used to support HTTP Basic Authentication.
auth = coreapi.auth.BasicAuthentication(
username='<username>',
password='<password>'
)
client = coreapi.Client(auth=auth)
## Interacting with the API
Now that we have a client and have fetched our schema `Document`, we can now
start to interact with the API:
users = client.action(schema, ['users', 'list'])
Some endpoints may include named parameters, which might be either optional or required:
new_user = client.action(schema, ['users', 'create'], params={"username": "max"})
## Codecs
Codecs are responsible for encoding or decoding Documents.
The decoding process is used by a client to take a bytestring of an API schema
definition, and returning the Core API `Document` that represents that interface.
A codec should be associated with a particular media type, such as `'application/coreapi+json'`.
This media type is used by the server in the response `Content-Type` header,
in order to indicate what kind of data is being returned in the response.
#### Configuring codecs
The codecs that are available can be configured when instantiating a client.
The keyword argument used here is `decoders`, because in the context of a
client the codecs are only for *decoding* responses.
In the following example we'll configure a client to only accept `Core JSON`
and `JSON` responses. This will allow us to receive and decode a Core JSON schema,
and subsequently to receive JSON responses made against the API.
from coreapi import codecs, Client
decoders = [codecs.CoreJSONCodec(), codecs.JSONCodec()]
client = Client(decoders=decoders)
#### Loading and saving schemas
You can use a codec directly, in order to load an existing schema definition,
and return the resulting `Document`.
input_file = open('my-api-schema.json', 'rb')
schema_definition = input_file.read()
codec = codecs.CoreJSONCodec()
schema = codec.load(schema_definition)
You can also use a codec directly to generate a schema definition given a `Document` instance:
schema_definition = codec.dump(schema)
output_file = open('my-api-schema.json', 'rb')
output_file.write(schema_definition)
## Transports
Transports are responsible for making network requests. The set of transports
that a client has installed determines which network protocols it is able to
support.
Currently the `coreapi` library only includes an HTTP/HTTPS transport, but
other protocols can also be supported.
#### Configuring transports
The behavior of the network layer can be customized by configuring the
transports that the client is instantiated with.
import requests
from coreapi import transports, Client
credentials = {'api.example.org': 'Token 3bd44a009d16ff'}
transports = transports.HTTPTransport(credentials=credentials)
client = Client(transports=transports)
More complex customizations can also be achieved, for example modifying the
underlying `requests.Session` instance to [attach transport adaptors][transport-adaptors]
that modify the outgoing requests.
---
# JavaScript Client Library
The JavaScript client library allows you to interact with your API either from a browser, or using node.
## Installing the JavaScript client
There are two separate JavaScript resources that you need to include in your HTML pages in order to use the JavaScript client library. These are a static `coreapi.js` file, which contains the code for the dynamic client library, and a templated `schema.js` resource, which exposes your API schema.
First, install the API documentation views. These will include the schema resource that'll allow you to load the schema directly from an HTML page, without having to make an asynchronous AJAX call.
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
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.
<!--
Load the CoreAPI library and the API schema.
/static/rest_framework/js/coreapi-0.1.1.js
/docs/schema.js
-->
{% load static %}
<script src="{% static 'rest_framework/js/coreapi-0.1.1.js' %}"></script>
<script src="{% url 'api-docs:schema-js' %}"></script>
The `coreapi` library, and the `schema` object will now both be available on the `window` instance.
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();
Typically you'll also want to provide some authentication credentials when
instantiating the client.
#### Session authentication
The `SessionAuthentication` class allows session cookies to provide the user
authentication. You'll want to provide a standard HTML login flow, to allow
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});
The authentication scheme will handle including a CSRF header in any outgoing
requests for unsafe HTTP methods.
#### Token authentication
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});
When using TokenAuthentication you'll probably need to implement a login flow
using the CoreAPI client.
A suggested pattern for this would be to initially make an unauthenticated client
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;
function loginUser(username, password) {
let action = ["api-token-auth", "obtain-token"];
let params = {username: "example", email: "example@example.com"};
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'],
})
window.client = coreapi.Client({auth: auth});
window.loggedIn = true;
}).catch(function (error) {
// Handle error case where eg. user provides incorrect credentials.
})
}
#### Basic authentication
The `BasicAuthentication` class can be used to support HTTP Basic Authentication.
let auth = new coreapi.auth.BasicAuthentication({
username: '<username>',
password: '<password>',
})
let client = new coreapi.Client({auth: auth});
## Using the client
Making requests:
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"};
client.action(schema, action, params).then(function(result) {
// Return value is in 'result'
})
Handling errors:
client.action(schema, action, params).then(function(result) {
// Return value is in 'result'
}).catch(function (error) {
// Error value is in 'error'
})
## Installation with node
The coreapi package is available on NPM.
$ npm install coreapi
$ node
const coreapi = require('coreapi')
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;
client.get("https://api.example.org/").then(function(data) {
// Load a CoreJSON API schema.
schema = data;
console.log('schema loaded');
})
[heroku-api]: https://devcenter.heroku.com/categories/platform-api
[heroku-example]: https://www.coreapi.org/tools-and-resources/example-services/#heroku-json-hyper-schema
[core-api]: https://www.coreapi.org/
[schema-generation]: ../api-guide/schemas.md
[transport-adaptors]: http://docs.python-requests.org/en/master/user/advanced/#transport-adapters

View File

@ -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 %}

View File

@ -4,12 +4,42 @@
>
> &mdash; Roy Fielding, [REST APIs must be hypertext driven][cite]
REST framework provides built-in support for generating OpenAPI schemas, which
can be used with tools that allow you to build API documentation.
REST framework provides a range of different choices for documenting your API. The following
is a non-exhaustive list of the most popular ones.
There are also a number of great third-party documentation packages available.
## Third party packages for OpenAPI support
## Generating documentation from OpenAPI schemas
### drf-spectacular
[drf-spectacular][drf-spectacular] is an [OpenAPI 3][open-api] schema generation library with explicit
focus on extensibility, customizability and client generation. It is the recommended way for
generating and presenting OpenAPI schemas.
The library aims to extract as much schema information as possible, while providing decorators and extensions for easy
customization. There is explicit support for [swagger-codegen][swagger], [SwaggerUI][swagger-ui] and [Redoc][redoc],
i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters,
documentation and more. Several popular plugins for DRF are supported out-of-the-box as well.
### drf-yasg
[drf-yasg][drf-yasg] is a [Swagger / OpenAPI 2][swagger] generation tool implemented without using the schema generation provided
by Django Rest Framework.
It aims to implement as much of the [OpenAPI 2][open-api] specification as possible - nested schemas, named models,
response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code
generation tools like `swagger-codegen`.
This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`:
![Screenshot - drf-yasg][image-drf-yasg]
---
## Built-in OpenAPI schema generation (deprecated)
**Deprecation notice: REST framework's built-in support for generating OpenAPI schemas is
deprecated in favor of 3rd party packages that can provide this functionality instead.
As replacement, we recommend using the [drf-spectacular](#drf-spectacular) package.**
There are a number of packages available that allow you to generate HTML
documentation pages from OpenAPI schemas.
@ -124,35 +154,6 @@ urlpatterns = [
See the [ReDoc documentation][redoc] for advanced usage.
## Third party packages
There are a number of mature third-party packages for providing API documentation.
#### drf-yasg - Yet Another Swagger Generator
[drf-yasg][drf-yasg] is a [Swagger][swagger] generation tool implemented without using the schema generation provided
by Django Rest Framework.
It aims to implement as much of the [OpenAPI][open-api] specification as possible - nested schemas, named models,
response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code
generation tools like `swagger-codegen`.
This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`:
![Screenshot - drf-yasg][image-drf-yasg]
#### 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. Usage patterns are very similar to [drf-yasg][drf-yasg].
It aims to extract as much schema information as possible, while providing decorators and extensions for easy
customization. There is explicit support for [swagger-codegen][swagger], [SwaggerUI][swagger-ui] and [Redoc][redoc],
i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters,
documentation and more. Several popular plugins for DRF are supported out-of-the-box as well.
---
## Self describing APIs
@ -202,7 +203,7 @@ You can modify the response behavior to `OPTIONS` requests by overriding the `op
meta = self.metadata_class()
data = meta.determine_metadata(request, self)
data.pop('description')
return data
return Response(data=data, status=status.HTTP_200_OK)
See [the Metadata docs][metadata-docs] for more details.

View File

@ -208,7 +208,7 @@ Field templates can also use additional style properties, depending on their typ
The complete list of `base_template` options and their associated style options is listed below.
base_template | Valid field types | Additional style options
----|----|----
-----------------------|-------------------------------------------------------------|-----------------------------------------------
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
textarea.html | `CharField` | rows, placeholder, hide_label
select.html | `ChoiceField` or relational field types | hide_label

View File

@ -17,9 +17,9 @@ You can change the default language by using the standard Django `LANGUAGE_CODE`
LANGUAGE_CODE = "es-es"
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE_CLASSES` setting:
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE` setting:
MIDDLEWARE_CLASSES = [
MIDDLEWARE = [
...
'django.middleware.locale.LocaleMiddleware'
]
@ -90,7 +90,7 @@ If you're only translating custom error messages that exist inside your project
## How the language is determined
If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE_CLASSES` setting.
If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE` setting.
You can find more information on how the language preference is determined in the [Django documentation][django-language-preference]. For reference, the method is:
@ -103,10 +103,10 @@ You can find more information on how the language preference is determined in th
For API clients the most appropriate of these will typically be to use the `Accept-Language` header; Sessions and cookies will not be available unless using session authentication, and generally better practice to prefer an `Accept-Language` header for API clients rather than using language URL prefixes.
[cite]: https://youtu.be/Wa0VfS2q94Y
[django-translation]: https://docs.djangoproject.com/en/1.7/topics/i18n/translation
[django-translation]: https://docs.djangoproject.com/en/stable/topics/i18n/translation
[custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling
[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/
[django-po-source]: https://raw.githubusercontent.com/encode/django-rest-framework/master/rest_framework/locale/en_US/LC_MESSAGES/django.po
[django-language-preference]: https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#how-django-discovers-language-preference
[django-locale-paths]: https://docs.djangoproject.com/en/1.7/ref/settings/#std:setting-LOCALE_PATHS
[django-locale-name]: https://docs.djangoproject.com/en/1.7/topics/i18n/#term-locale-name
[django-language-preference]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#how-django-discovers-language-preference
[django-locale-paths]: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-LOCALE_PATHS
[django-locale-name]: https://docs.djangoproject.com/en/stable/topics/i18n/#term-locale-name

View File

@ -4,7 +4,7 @@
>
> &mdash; Mike Amundsen, [REST fest 2012 keynote][cite].
First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to ensure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
If you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices.

View File

@ -45,7 +45,7 @@ We'll need to add our new `snippets` app and the `rest_framework` app to `INSTAL
INSTALLED_APPS = [
...
'rest_framework',
'snippets.apps.SnippetsConfig',
'snippets',
]
Okay, we're ready to roll.
@ -77,7 +77,7 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni
We'll also need to create an initial migration for our snippet model, and sync the database for the first time.
python manage.py makemigrations snippets
python manage.py migrate
python manage.py migrate snippets
## Creating a Serializer class
@ -307,8 +307,8 @@ Quit out of the shell...
Validating models...
0 errors found
Django version 1.11, using settings 'tutorial.settings'
Development server is running at http://127.0.0.1:8000/
Django version 4.0, using settings 'tutorial.settings'
Starting Development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
In another terminal window, we can test the server.
@ -374,5 +374,5 @@ We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].
[sandbox]: https://restframework.herokuapp.com/
[venv]: https://docs.python.org/3/library/venv.html
[tut-2]: 2-requests-and-responses.md
[httpie]: https://github.com/jakubroztocil/httpie#installation
[httpie]: https://github.com/httpie/httpie#installation
[curl]: https://curl.haxx.se/

View File

@ -29,7 +29,7 @@ REST framework provides two wrappers you can use to write API views.
These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
The wrappers also provide behavior such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
## Pulling it all together
@ -112,7 +112,7 @@ Now update the `snippets/urls.py` file slightly, to append a set of `format_suff
urlpatterns = [
path('snippets/', views.snippet_list),
path('snippets/<int:pk>', views.snippet_detail),
path('snippets/<int:pk>/', views.snippet_detail),
]
urlpatterns = format_suffix_patterns(urlpatterns)

View File

@ -79,9 +79,9 @@ Okay, we're done. If you run the development server everything should be workin
## Using mixins
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behaviour.
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behavior.
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behavior are implemented in REST framework's mixin classes.
Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again.

View File

@ -38,7 +38,7 @@ And now we can add a `.save()` method to our model class:
formatter = HtmlFormatter(style=self.style, linenos=linenos,
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super(Snippet, self).save(*args, **kwargs)
super().save(*args, **kwargs)
When that's all done we'll need to update our database tables.
Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.

View File

@ -31,7 +31,6 @@ The other thing we need to consider when creating the code highlight view is tha
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets/views.py` add:
from rest_framework import renderers
from rest_framework.response import Response
class SnippetHighlight(generics.GenericAPIView):
queryset = Snippet.objects.all()
@ -143,7 +142,7 @@ We can change the default list style to use pagination, by modifying our `tutori
Note that settings in REST framework are all namespaced into a single dictionary setting, named `REST_FRAMEWORK`, which helps keep them well separated from your other project settings.
We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.
We could also customize the pagination style if we needed to, but in this case we'll just stick with the default.
## Browsing the API

View File

@ -10,10 +10,11 @@ A `ViewSet` class is only bound to a set of method handlers at the last moment,
Let's take our current set of views, and refactor them into view sets.
First of all let's refactor our `UserList` and `UserDetail` views into a single `UserViewSet`. We can remove the two views, and replace them with a single class:
First of all let's refactor our `UserList` and `UserDetail` classes into a single `UserViewSet` class. We can remove the two view classes, and replace them with a single ViewSet class:
from rest_framework import viewsets
class UserViewSet(viewsets.ReadOnlyModelViewSet):
"""
This viewset automatically provides `list` and `retrieve` actions.
@ -25,13 +26,14 @@ Here we've used the `ReadOnlyModelViewSet` class to automatically provide the de
Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class.
from rest_framework import permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import permissions
class SnippetViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
This ViewSet automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action.
@ -64,9 +66,10 @@ To see what's going on under the hood let's first explicitly create a set of vie
In the `snippets/urls.py` file we bind our `ViewSet` classes into a set of concrete views.
from snippets.views import SnippetViewSet, UserViewSet, api_root
from rest_framework import renderers
from snippets.views import api_root, SnippetViewSet, UserViewSet
snippet_list = SnippetViewSet.as_view({
'get': 'list',
'post': 'create'
@ -87,7 +90,7 @@ In the `snippets/urls.py` file we bind our `ViewSet` classes into a set of concr
'get': 'retrieve'
})
Notice how we're creating multiple views from each `ViewSet` class, by binding the http methods to the required action for each view.
Notice how we're creating multiple views from each `ViewSet` class, by binding the HTTP methods to the required action for each view.
Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.
@ -108,24 +111,25 @@ Here's our re-wired `snippets/urls.py` file.
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from snippets import views
# Create a router and register our viewsets with it.
# Create a router and register our ViewSets with it.
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet)
router.register(r'users', views.UserViewSet)
router.register(r'snippets', views.SnippetViewSet, basename='snippet')
router.register(r'users', views.UserViewSet, basename='user')
# The API URLs are now determined automatically by the router.
urlpatterns = [
path('', include(router.urls)),
]
Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.
Registering the ViewSets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the view set itself.
The `DefaultRouter` class we're using also automatically creates the API root view for us, so we can now delete the `api_root` method from our `views` module.
The `DefaultRouter` class we're using also automatically creates the API root view for us, so we can now delete the `api_root` function from our `views` module.
## Trade-offs between views vs viewsets
## Trade-offs between views vs ViewSets
Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.
Using ViewSets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.
That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually.
That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function-based views. Using ViewSets is less explicit than building your API views individually.

View File

@ -30,21 +30,24 @@ The project layout should look like:
<some path>/tutorial
$ find .
.
./manage.py
./tutorial
./tutorial/asgi.py
./tutorial/__init__.py
./tutorial/quickstart
./tutorial/quickstart/__init__.py
./tutorial/quickstart/admin.py
./tutorial/quickstart/apps.py
./tutorial/quickstart/migrations
./tutorial/quickstart/migrations/__init__.py
./tutorial/quickstart/models.py
./tutorial/quickstart/__init__.py
./tutorial/quickstart/apps.py
./tutorial/quickstart/admin.py
./tutorial/quickstart/tests.py
./tutorial/quickstart/views.py
./tutorial/settings.py
./tutorial/urls.py
./tutorial/wsgi.py
./env
./env/...
./manage.py
It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart).
@ -52,9 +55,9 @@ Now sync your database for the first time:
python manage.py migrate
We'll also create an initial user named `admin` with a password of `password123`. We'll authenticate as that user later in our example.
We'll also create an initial user named `admin` with a password. We'll authenticate as that user later in our example.
python manage.py createsuperuser --email admin@example.com --username admin
python manage.py createsuperuser --username admin --email admin@example.com
Once you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding...
@ -62,7 +65,7 @@ Once you've set up a database and the initial user is created and ready to go, o
First up we're going to define some serializers. Let's create a new module named `tutorial/quickstart/serializers.py` that we'll use for our data representations.
from django.contrib.auth.models import User, Group
from django.contrib.auth.models import Group, User
from rest_framework import serializers
@ -83,10 +86,10 @@ Notice that we're using hyperlinked relations in this case with `HyperlinkedMode
Right, we'd better write some views then. Open `tutorial/quickstart/views.py` and get typing.
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
from django.contrib.auth.models import Group, User
from rest_framework import permissions, viewsets
from tutorial.quickstart.serializers import GroupSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
@ -116,6 +119,7 @@ Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
from django.urls import include, path
from rest_framework import routers
from tutorial.quickstart import views
router = routers.DefaultRouter()
@ -129,6 +133,8 @@ Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
urlpatterns += router.urls
Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
Again, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly.
@ -164,9 +170,30 @@ We're now ready to test the API we've built. Let's fire up the server from the
We can now access our API, both from the command-line, using tools like `curl`...
bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/
Enter host password for user 'admin':
{
"count": 2,
"count": 1,
"next": null,
"previous": null,
"results": [
{
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin",
"email": "admin@example.com",
"groups": []
}
]
}
Or using the [httpie][httpie], command line tool...
bash: http -a admin http://127.0.0.1:8000/users/
http: password for admin@127.0.0.1:8000::
$HTTP/1.1 200 OK
...
{
"count": 1,
"next": null,
"previous": null,
"results": [
@ -175,38 +202,6 @@ We can now access our API, both from the command-line, using tools like `curl`..
"groups": [],
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin"
},
{
"email": "tom@example.com",
"groups": [],
"url": "http://127.0.0.1:8000/users/2/",
"username": "tom"
}
]
}
Or using the [httpie][httpie], command line tool...
bash: http -a admin:password123 http://127.0.0.1:8000/users/
HTTP/1.1 200 OK
...
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"email": "admin@example.com",
"groups": [],
"url": "http://localhost:8000/users/1/",
"username": "paul"
},
{
"email": "tom@example.com",
"groups": [],
"url": "http://127.0.0.1:8000/users/2/",
"username": "tom"
}
]
}
@ -225,4 +220,4 @@ If you want to get a more in depth understanding of how REST framework fits toge
[image]: ../img/quickstart.png
[tutorial]: 1-serialization.md
[guide]: ../api-guide/requests.md
[httpie]: https://github.com/jakubroztocil/httpie#installation
[httpie]: https://httpie.io/docs#installation

View File

@ -37,7 +37,7 @@ body.index-page #main-content iframe.github-star-button {
margin-right: -15px;
}
/* Travis CI and PyPI badge */
/* CI and PyPI badge */
body.index-page #main-content img.status-badge {
float: right;
margin-right: 8px;

View File

@ -53,7 +53,6 @@ nav:
- 'Settings': 'api-guide/settings.md'
- Topics:
- 'Documenting your API': 'topics/documenting-your-api.md'
- 'API Clients': 'topics/api-clients.md'
- 'Internationalization': 'topics/internationalization.md'
- 'AJAX, CSRF & CORS': 'topics/ajax-csrf-cors.md'
- 'HTML & Forms': 'topics/html-and-forms.md'
@ -66,6 +65,8 @@ nav:
- 'Contributing to REST framework': 'community/contributing.md'
- 'Project management': 'community/project-management.md'
- 'Release Notes': 'community/release-notes.md'
- '3.14 Announcement': 'community/3.14-announcement.md'
- '3.13 Announcement': 'community/3.13-announcement.md'
- '3.12 Announcement': 'community/3.12-announcement.md'
- '3.11 Announcement': 'community/3.11-announcement.md'
- '3.10 Announcement': 'community/3.10-announcement.md'

View File

@ -1,6 +1,7 @@
# The base set of requirements for REST framework is actually
# just Django, but for the purposes of development and testing
# there are a number of packages that are useful to install.
# just Django and pytz, but for the purposes of development
# and testing there are a number of packages that are useful
# to install.
# Laying these out as separate requirements files, allows us to
# only included the relevant sets when running tox, and ensures
@ -9,5 +10,4 @@
-r requirements/requirements-optionals.txt
-r requirements/requirements-testing.txt
-r requirements/requirements-documentation.txt
-r requirements/requirements-codestyle.txt
-r requirements/requirements-packaging.txt

View File

@ -1,7 +0,0 @@
# PEP8 code linting, which we run on all commits.
flake8==3.8.3
flake8-tidy-imports==4.1.0
pycodestyle==2.6.0
# Sort and lint imports
isort==5.4.2

View File

@ -1,2 +1,3 @@
# MkDocs to build our documentation.
mkdocs==1.1
mkdocs>=1.1.2,<1.2
jinja2>=2.10,<3.1.0 # contextfilter has been renamed

View File

@ -1,9 +1,10 @@
# Optional packages which may be used with REST framework.
psycopg2-binary>=2.8.5, <2.9
markdown==3.1.1
pygments==2.4.2
django-guardian==2.2.0
django-filter>=2.2.0, <2.3
coreapi==2.3.1
coreschema==0.0.4
pyyaml>=5.1
django-filter>=2.4.0,<3.0
django-guardian>=2.4.0,<2.5
inflection==0.5.1
markdown==3.3
psycopg2-binary>=2.9.5,<2.10
pygments==2.12
pyyaml>=5.3.1,<5.4

View File

@ -1,8 +1,8 @@
# Wheel for PyPI installs.
wheel==0.34.2
wheel>=0.35.1,<0.36
# Twine for secured PyPI uploads.
twine==3.1.1
twine>=3.2.0,<3.3
# Transifex client for managing translation resources.
transifex-client==0.13.9
transifex-client>=0.13.12,<0.14

View File

@ -1,4 +1,5 @@
# Pytest for running the tests.
pytest>=5.4.1,<5.5
pytest-django>=3.9.0,<3.10
pytest-cov>=2.7.1
pytest>=6.2.0,<8.0
pytest-cov>=4.0.0,<5.0
pytest-django>=4.5.2,<5.0
importlib-metadata<5.0

View File

@ -10,7 +10,7 @@ ______ _____ _____ _____ __
import django
__title__ = 'Django REST framework'
__version__ = '3.12.1'
__version__ = '3.14.0'
__author__ = 'Tom Christie'
__license__ = 'BSD 3-Clause'
__copyright__ = 'Copyright 2011-2019 Encode OSS Ltd'
@ -29,11 +29,7 @@ if django.VERSION < (3, 2):
default_app_config = 'rest_framework.apps.RestFrameworkConfig'
class RemovedInDRF313Warning(DeprecationWarning):
pass
class RemovedInDRF314Warning(PendingDeprecationWarning):
class RemovedInDRF315Warning(DeprecationWarning):
pass

View File

@ -227,6 +227,6 @@ class RemoteUserAuthentication(BaseAuthentication):
header = "REMOTE_USER"
def authenticate(self, request):
user = authenticate(remote_user=request.META.get(self.header))
user = authenticate(request=request, remote_user=request.META.get(self.header))
if user and user.is_active:
return (user, None)

View File

@ -0,0 +1,17 @@
# Generated by Django 4.1.3 on 2022-11-24 21:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('authtoken', '0003_tokenproxy'),
]
operations = [
migrations.AlterModelOptions(
name='tokenproxy',
options={'verbose_name': 'Token', 'verbose_name_plural': 'Tokens'},
),
]

View File

@ -46,9 +46,10 @@ class TokenProxy(Token):
"""
@property
def pk(self):
return self.user.pk
return self.user_id
class Meta:
proxy = 'rest_framework.authtoken' in settings.INSTALLED_APPS
abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS
verbose_name = "token"
verbose_name = _("Token")
verbose_name_plural = _("Tokens")

View File

@ -2,6 +2,7 @@
The `compat` module provides support for backwards compatibility with older
versions of Django/Python, and compatibility wrappers around optional packages.
"""
import django
from django.conf import settings
from django.views.generic import View
@ -152,6 +153,30 @@ else:
return False
if django.VERSION >= (4, 2):
# Django 4.2+: use the stock parse_header_parameters function
# Note: Django 4.1 also has an implementation of parse_header_parameters
# which is slightly different from the one in 4.2, it needs
# the compatibility shim as well.
from django.utils.http import parse_header_parameters
else:
# Django <= 4.1: create a compatibility shim for parse_header_parameters
from django.http.multipartparser import parse_header
def parse_header_parameters(line):
# parse_header works with bytes, but parse_header_parameters
# works with strings. Call encode to convert the line to bytes.
main_value_pair, params = parse_header(line.encode())
return main_value_pair, {
# parse_header will convert *some* values to string.
# parse_header_parameters converts *all* values to string.
# Make sure all values are converted by calling decode on
# any remaining non-string values.
k: v if isinstance(v, str) else v.decode()
for k, v in params.items()
}
# `separators` argument to `json.dumps()` differs between 2.x and 3.x
# See: https://bugs.python.org/issue22767
SHORT_SEPARATORS = (',', ':')

View File

@ -142,7 +142,7 @@ def action(methods=None, detail=None, url_path=None, url_name=None, **kwargs):
how the `@renderer_classes` etc. decorators work for function-
based API views.
"""
methods = ['get'] if (methods is None) else methods
methods = ['get'] if methods is None else methods
methods = [method.lower() for method in methods]
assert detail is not None, (

View File

@ -1,7 +1,7 @@
"""
Handled exceptions raised by REST framework.
In addition Django's built in 403 and 404 exceptions are handled.
In addition, Django's built in 403 and 404 exceptions are handled.
(`django.http.Http404` and `django.core.exceptions.PermissionDenied`)
"""
import math
@ -20,7 +20,7 @@ def _get_error_details(data, default_code=None):
Descend into a nested data structure, forcing any
lazy translation strings or strings into `ErrorDetail`.
"""
if isinstance(data, list):
if isinstance(data, (list, tuple)):
ret = [
_get_error_details(item, default_code) for item in data
]
@ -72,16 +72,19 @@ class ErrorDetail(str):
return self
def __eq__(self, other):
r = super().__eq__(other)
if r is NotImplemented:
result = super().__eq__(other)
if result is NotImplemented:
return NotImplemented
try:
return r and self.code == other.code
return result and self.code == other.code
except AttributeError:
return r
return result
def __ne__(self, other):
return not self.__eq__(other)
result = self.__eq__(other)
if result is NotImplemented:
return NotImplemented
return not result
def __repr__(self):
return 'ErrorDetail(string=%r, code=%r)' % (
@ -150,7 +153,9 @@ class ValidationError(APIException):
# For validation failures, we may collect many errors together,
# so the details should always be coerced to a list if not already.
if not isinstance(detail, dict) and not isinstance(detail, list):
if isinstance(detail, tuple):
detail = list(detail)
elif not isinstance(detail, dict) and not isinstance(detail, list):
detail = [detail]
self.detail = _get_error_details(detail, code)

View File

@ -1,3 +1,4 @@
import contextlib
import copy
import datetime
import decimal
@ -5,7 +6,6 @@ import functools
import inspect
import re
import uuid
import warnings
from collections import OrderedDict
from collections.abc import Mapping
@ -27,13 +27,10 @@ from django.utils.duration import duration_string
from django.utils.encoding import is_protected_type, smart_str
from django.utils.formats import localize_input, sanitize_separators
from django.utils.ipv6 import clean_ipv6_address
from django.utils.timezone import utc
from django.utils.translation import gettext_lazy as _
from pytz.exceptions import InvalidTimeError
from rest_framework import (
ISO_8601, RemovedInDRF313Warning, RemovedInDRF314Warning
)
from rest_framework import ISO_8601
from rest_framework.exceptions import ErrorDetail, ValidationError
from rest_framework.settings import api_settings
from rest_framework.utils import html, humanize_datetime, json, representation
@ -63,6 +60,9 @@ def is_simple_callable(obj):
"""
True if the object is a callable that takes no arguments.
"""
if not callable(obj):
return False
# Bail early since we cannot inspect built-in function signatures.
if inspect.isbuiltin(obj):
raise BuiltinSignatureError(
@ -263,16 +263,6 @@ class CreateOnlyDefault:
if is_update:
raise SkipField()
if callable(self.default):
if hasattr(self.default, 'set_context'):
warnings.warn(
"Method `set_context` on defaults is deprecated and will "
"no longer be called starting with 3.13. Instead set "
"`requires_context = True` on the class, and accept the "
"context as an additional argument.",
RemovedInDRF313Warning, stacklevel=2
)
self.default.set_context(self)
if getattr(self.default, 'requires_context', False):
return self.default(serializer_field)
else:
@ -320,7 +310,7 @@ class Field:
default_empty_html = empty
initial = None
def __init__(self, read_only=False, write_only=False,
def __init__(self, *, read_only=False, write_only=False,
required=None, default=empty, initial=empty, source=None,
label=None, help_text=None, style=None,
error_messages=None, validators=None, allow_null=False):
@ -502,16 +492,6 @@ class Field:
# No default, or this is a partial update.
raise SkipField()
if callable(self.default):
if hasattr(self.default, 'set_context'):
warnings.warn(
"Method `set_context` on defaults is deprecated and will "
"no longer be called starting with 3.13. Instead set "
"`requires_context = True` on the class, and accept the "
"context as an additional argument.",
RemovedInDRF313Warning, stacklevel=2
)
self.default.set_context(self)
if getattr(self.default, 'requires_context', False):
return self.default(self)
else:
@ -576,16 +556,6 @@ class Field:
"""
errors = []
for validator in self.validators:
if hasattr(validator, 'set_context'):
warnings.warn(
"Method `set_context` on validators is deprecated and will "
"no longer be called starting with 3.13. Instead set "
"`requires_context = True` on the class, and accept the "
"context as an additional argument.",
RemovedInDRF313Warning, stacklevel=2
)
validator.set_context(self)
try:
if getattr(validator, 'requires_context', False):
validator(value, self)
@ -704,7 +674,7 @@ class BooleanField(Field):
initial = False
TRUE_VALUES = {
't', 'T',
'y', 'Y', 'yes', 'YES',
'y', 'Y', 'yes', 'Yes', 'YES',
'true', 'True', 'TRUE',
'on', 'On', 'ON',
'1', 1,
@ -712,7 +682,7 @@ class BooleanField(Field):
}
FALSE_VALUES = {
'f', 'F',
'n', 'N', 'no', 'NO',
'n', 'N', 'no', 'No', 'NO',
'false', 'False', 'FALSE',
'off', 'Off', 'OFF',
'0', 0, 0.0,
@ -721,15 +691,13 @@ class BooleanField(Field):
NULL_VALUES = {'null', 'Null', 'NULL', '', None}
def to_internal_value(self, data):
try:
with contextlib.suppress(TypeError):
if data in self.TRUE_VALUES:
return True
elif data in self.FALSE_VALUES:
return False
elif data in self.NULL_VALUES and self.allow_null:
return None
except TypeError: # Input is an unhashable type
pass
self.fail('invalid', input=data)
def to_representation(self, value):
@ -742,23 +710,6 @@ class BooleanField(Field):
return bool(value)
class NullBooleanField(BooleanField):
initial = None
def __init__(self, **kwargs):
warnings.warn(
"The `NullBooleanField` is deprecated and will be removed starting "
"with 3.14. Instead use the `BooleanField` field and set "
"`allow_null=True` which does the same thing.",
RemovedInDRF314Warning, stacklevel=2
)
assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.'
kwargs['allow_null'] = True
super().__init__(**kwargs)
# String types...
class CharField(Field):
@ -968,7 +919,8 @@ class FloatField(Field):
'invalid': _('A valid number is required.'),
'max_value': _('Ensure this value is less than or equal to {max_value}.'),
'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
'max_string_length': _('String value too large.')
'max_string_length': _('String value too large.'),
'overflow': _('Integer value too large to convert to float')
}
MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
@ -994,6 +946,8 @@ class FloatField(Field):
return float(data)
except (TypeError, ValueError):
self.fail('invalid')
except OverflowError:
self.fail('overflow')
def to_representation(self, value):
return float(value)
@ -1012,10 +966,11 @@ class DecimalField(Field):
MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None,
localize=False, rounding=None, **kwargs):
localize=False, rounding=None, normalize_output=False, **kwargs):
self.max_digits = max_digits
self.decimal_places = decimal_places
self.localize = localize
self.normalize_output = normalize_output
if coerce_to_string is not None:
self.coerce_to_string = coerce_to_string
if self.localize:
@ -1046,6 +1001,11 @@ class DecimalField(Field):
'Invalid rounding option %s. Valid values for rounding are: %s' % (rounding, valid_roundings))
self.rounding = rounding
def validate_empty_values(self, data):
if smart_str(data).strip() == '' and self.allow_null:
return (True, None)
return super().validate_empty_values(data)
def to_internal_value(self, data):
"""
Validate that the input is a decimal number and return a Decimal
@ -1112,11 +1072,20 @@ class DecimalField(Field):
def to_representation(self, value):
coerce_to_string = getattr(self, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING)
if value is None:
if coerce_to_string:
return ''
else:
return None
if not isinstance(value, decimal.Decimal):
value = decimal.Decimal(str(value).strip())
quantized = self.quantize(value)
if self.normalize_output:
quantized = quantized.normalize()
if not coerce_to_string:
return quantized
if self.localize:
@ -1152,21 +1121,21 @@ class DateTimeField(Field):
}
datetime_parser = datetime.datetime.strptime
def __init__(self, format=empty, input_formats=None, default_timezone=None, *args, **kwargs):
def __init__(self, format=empty, input_formats=None, default_timezone=None, **kwargs):
if format is not empty:
self.format = format
if input_formats is not None:
self.input_formats = input_formats
if default_timezone is not None:
self.timezone = default_timezone
super().__init__(*args, **kwargs)
super().__init__(**kwargs)
def enforce_timezone(self, value):
"""
When `self.default_timezone` is `None`, always return naive datetimes.
When `self.default_timezone` is not `None`, always return aware datetimes.
"""
field_timezone = getattr(self, 'timezone', self.default_timezone())
field_timezone = self.timezone if hasattr(self, 'timezone') else self.default_timezone()
if field_timezone is not None:
if timezone.is_aware(value):
@ -1179,7 +1148,7 @@ class DateTimeField(Field):
except InvalidTimeError:
self.fail('make_aware', timezone=field_timezone)
elif (field_timezone is None) and timezone.is_aware(value):
return timezone.make_naive(value, utc)
return timezone.make_naive(value, datetime.timezone.utc)
return value
def default_timezone(self):
@ -1195,19 +1164,14 @@ class DateTimeField(Field):
return self.enforce_timezone(value)
for input_format in input_formats:
with contextlib.suppress(ValueError, TypeError):
if input_format.lower() == ISO_8601:
try:
parsed = parse_datetime(value)
if parsed is not None:
return self.enforce_timezone(parsed)
except (ValueError, TypeError):
pass
else:
try:
parsed = self.datetime_parser(value, input_format)
return self.enforce_timezone(parsed)
except (ValueError, TypeError):
pass
humanized_format = humanize_datetime.datetime_formats(input_formats)
self.fail('invalid', format=humanized_format)
@ -1238,12 +1202,12 @@ class DateField(Field):
}
datetime_parser = datetime.datetime.strptime
def __init__(self, format=empty, input_formats=None, *args, **kwargs):
def __init__(self, format=empty, input_formats=None, **kwargs):
if format is not empty:
self.format = format
if input_formats is not None:
self.input_formats = input_formats
super().__init__(*args, **kwargs)
super().__init__(**kwargs)
def to_internal_value(self, value):
input_formats = getattr(self, 'input_formats', api_settings.DATE_INPUT_FORMATS)
@ -1304,12 +1268,12 @@ class TimeField(Field):
}
datetime_parser = datetime.datetime.strptime
def __init__(self, format=empty, input_formats=None, *args, **kwargs):
def __init__(self, format=empty, input_formats=None, **kwargs):
if format is not empty:
self.format = format
if input_formats is not None:
self.input_formats = input_formats
super().__init__(*args, **kwargs)
super().__init__(**kwargs)
def to_internal_value(self, value):
input_formats = getattr(self, 'input_formats', api_settings.TIME_INPUT_FORMATS)
@ -1365,6 +1329,7 @@ class DurationField(Field):
'invalid': _('Duration has wrong format. Use one of these formats instead: {format}.'),
'max_value': _('Ensure this value is less than or equal to {max_value}.'),
'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
'overflow': _('The number of days must be between {min_days} and {max_days}.'),
}
def __init__(self, **kwargs):
@ -1383,7 +1348,10 @@ class DurationField(Field):
def to_internal_value(self, value):
if isinstance(value, datetime.timedelta):
return value
try:
parsed = parse_duration(str(value))
except OverflowError:
self.fail('overflow', min_days=datetime.timedelta.min.days, max_days=datetime.timedelta.max.days)
if parsed is not None:
return parsed
self.fail('invalid', format='[DD] [HH:[MM:]]ss[.uuuuuu]')
@ -1459,9 +1427,9 @@ class MultipleChoiceField(ChoiceField):
}
default_empty_html = []
def __init__(self, *args, **kwargs):
def __init__(self, **kwargs):
self.allow_empty = kwargs.pop('allow_empty', True)
super().__init__(*args, **kwargs)
super().__init__(**kwargs)
def get_value(self, dictionary):
if self.field_name not in dictionary:
@ -1480,6 +1448,8 @@ class MultipleChoiceField(ChoiceField):
self.fail('empty')
return {
# Arguments for super() are needed because of scoping inside
# comprehensions.
super(MultipleChoiceField, self).to_internal_value(item)
for item in data
}
@ -1518,12 +1488,12 @@ class FileField(Field):
'max_length': _('Ensure this filename has at most {max_length} characters (it has {length}).'),
}
def __init__(self, *args, **kwargs):
def __init__(self, **kwargs):
self.max_length = kwargs.pop('max_length', None)
self.allow_empty_file = kwargs.pop('allow_empty_file', False)
if 'use_url' in kwargs:
self.use_url = kwargs.pop('use_url')
super().__init__(*args, **kwargs)
super().__init__(**kwargs)
def to_internal_value(self, data):
try:
@ -1567,9 +1537,9 @@ class ImageField(FileField):
),
}
def __init__(self, *args, **kwargs):
def __init__(self, **kwargs):
self._DjangoImageField = kwargs.pop('_DjangoImageField', DjangoImageField)
super().__init__(*args, **kwargs)
super().__init__(**kwargs)
def to_internal_value(self, data):
# Image validation is a bit grungy, so we'll just outright
@ -1584,8 +1554,8 @@ class ImageField(FileField):
# Composite field types...
class _UnvalidatedField(Field):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.allow_blank = True
self.allow_null = True
@ -1606,7 +1576,7 @@ class ListField(Field):
'max_length': _('Ensure this field has no more than {max_length} elements.')
}
def __init__(self, *args, **kwargs):
def __init__(self, **kwargs):
self.child = kwargs.pop('child', copy.deepcopy(self.child))
self.allow_empty = kwargs.pop('allow_empty', True)
self.max_length = kwargs.pop('max_length', None)
@ -1618,7 +1588,7 @@ class ListField(Field):
"Remove `source=` from the field declaration."
)
super().__init__(*args, **kwargs)
super().__init__(**kwargs)
self.child.bind(field_name='', parent=self)
if self.max_length is not None:
message = lazy_format(self.error_messages['max_length'], max_length=self.max_length)
@ -1683,7 +1653,7 @@ class DictField(Field):
'empty': _('This dictionary may not be empty.'),
}
def __init__(self, *args, **kwargs):
def __init__(self, **kwargs):
self.child = kwargs.pop('child', copy.deepcopy(self.child))
self.allow_empty = kwargs.pop('allow_empty', True)
@ -1693,7 +1663,7 @@ class DictField(Field):
"Remove `source=` from the field declaration."
)
super().__init__(*args, **kwargs)
super().__init__(**kwargs)
self.child.bind(field_name='', parent=self)
def get_value(self, dictionary):
@ -1742,8 +1712,8 @@ class DictField(Field):
class HStoreField(DictField):
child = CharField(allow_blank=True, allow_null=True)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __init__(self, **kwargs):
super().__init__(**kwargs)
assert isinstance(self.child, CharField), (
"The `child` argument must be an instance of `CharField`, "
"as the hstore extension stores values as strings."
@ -1755,11 +1725,14 @@ class JSONField(Field):
'invalid': _('Value must be valid JSON.')
}
def __init__(self, *args, **kwargs):
# Workaround for isinstance calls when importing the field isn't possible
_is_jsonfield = True
def __init__(self, **kwargs):
self.binary = kwargs.pop('binary', False)
self.encoder = kwargs.pop('encoder', None)
self.decoder = kwargs.pop('decoder', None)
super().__init__(*args, **kwargs)
super().__init__(**kwargs)
def get_value(self, dictionary):
if html.is_html_input(dictionary) and self.field_name in dictionary:
@ -1846,7 +1819,7 @@ class SerializerMethodField(Field):
For example:
class ExampleSerializer(self):
class ExampleSerializer(Serializer):
extra_info = SerializerMethodField()
def get_extra_info(self, obj):

View File

@ -232,10 +232,20 @@ class OrderingFilter(BaseFilterBackend):
)
raise ImproperlyConfigured(msg % self.__class__.__name__)
model_class = queryset.model
model_property_names = [
# 'pk' is a property added in Django's Model class, however it is valid for ordering.
attr for attr in dir(model_class) if isinstance(getattr(model_class, attr), property) and attr != 'pk'
]
return [
(field.source.replace('.', '__') or field_name, field.label)
for field_name, field in serializer_class(context=context).fields.items()
if not getattr(field, 'write_only', False) and not field.source == '*'
if (
not getattr(field, 'write_only', False) and
not field.source == '*' and
field.source not in model_property_names
)
]
def get_valid_fields(self, queryset, view, context={}):

View File

@ -7,13 +7,14 @@
# aymen chaieb <chaieb.aymen1992@gmail.com>, 2017
# Bashar Al-Abdulhadi, 2016-2017
# Eyad Toma <d.eyad.t@gmail.com>, 2015,2017
# zak zak <zakaria.bendifallah@gmail.com>, 2020
msgid ""
msgstr ""
"Project-Id-Version: Django REST framework\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2016-07-12 16:13+0100\n"
"PO-Revision-Date: 2017-10-18 09:51+0000\n"
"Last-Translator: Andrew Ayoub <andrew.ayoub@connectads.com>\n"
"POT-Creation-Date: 2020-10-13 21:45+0200\n"
"PO-Revision-Date: 2020-10-13 19:45+0000\n"
"Last-Translator: Xavier Ordoquy <xordoquy@linovia.com>\n"
"Language-Team: Arabic (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/ar/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
@ -21,40 +22,40 @@ msgstr ""
"Language: ar\n"
"Plural-Forms: nplurals=6; plural=n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5;\n"
#: authentication.py:73
#: authentication.py:70
msgid "Invalid basic header. No credentials provided."
msgstr ""
msgstr "رأس أساسي غير صالح, لم تقدم اي بيانات."
#: authentication.py:76
#: authentication.py:73
msgid "Invalid basic header. Credentials string should not contain spaces."
msgstr ""
msgstr "رأس أساسي غير صالح, سلسلة البيانات لا يجب أن تحتوي على أي أحرف مسافات"
#: authentication.py:82
#: authentication.py:83
msgid "Invalid basic header. Credentials not correctly base64 encoded."
msgstr ""
msgstr "رأس أساسي غير صالح, البيانات ليست مرمّزة بصحة على أساس64."
#: authentication.py:99
#: authentication.py:101
msgid "Invalid username/password."
msgstr "اسم المستخدم/كلمة السر غير صحيحين."
#: authentication.py:102 authentication.py:198
#: authentication.py:104 authentication.py:206
msgid "User inactive or deleted."
msgstr "المستخدم غير مفعل او تم حذفه."
#: authentication.py:176
#: authentication.py:184
msgid "Invalid token header. No credentials provided."
msgstr ""
msgstr "رمز الراْس المميّز غير صالح, لم تقدم أي بيانات."
#: authentication.py:179
#: authentication.py:187
msgid "Invalid token header. Token string should not contain spaces."
msgstr ""
msgstr "رمز الراْس المميّز غير صالح, سلسلة الرمز المميّز لا يجب أن تحتوي على أي أحرف مسافات."
#: authentication.py:185
#: authentication.py:193
msgid ""
"Invalid token header. Token string should not contain invalid characters."
msgstr ""
msgstr "رمز الراْس المميّز غير صالح, سلسلة الرمز المميّز لا يجب أن تحتوي على أي أحرف غير صالحة."
#: authentication.py:195
#: authentication.py:203
msgid "Invalid token."
msgstr "رمز غير صحيح."
@ -62,382 +63,515 @@ msgstr "رمز غير صحيح."
msgid "Auth Token"
msgstr "رمز التفويض"
#: authtoken/models.py:15
#: authtoken/models.py:13
msgid "Key"
msgstr "المفتاح"
#: authtoken/models.py:18
#: authtoken/models.py:16
msgid "User"
msgstr "المستخدم"
#: authtoken/models.py:20
#: authtoken/models.py:18
msgid "Created"
msgstr "أنشئ"
#: authtoken/models.py:29
#: authtoken/models.py:27 authtoken/serializers.py:19
msgid "Token"
msgstr "الرمز"
#: authtoken/models.py:30
#: authtoken/models.py:28
msgid "Tokens"
msgstr "الرموز"
#: authtoken/serializers.py:8
#: authtoken/serializers.py:9
msgid "Username"
msgstr "اسم المستخدم"
#: authtoken/serializers.py:9
#: authtoken/serializers.py:13
msgid "Password"
msgstr "كلمة المرور"
#: authtoken/serializers.py:20
msgid "User account is disabled."
msgstr "حساب المستخدم غير مفعل."
#: authtoken/serializers.py:23
#: authtoken/serializers.py:35
msgid "Unable to log in with provided credentials."
msgstr "تعذر تسجيل الدخول بالبيانات التي ادخلتها."
#: authtoken/serializers.py:26
#: authtoken/serializers.py:38
msgid "Must include \"username\" and \"password\"."
msgstr "يجب أن تتضمن \"اسم المستخدم\" و \"كلمة المرور\"."
#: exceptions.py:49
#: exceptions.py:102
msgid "A server error occurred."
msgstr "حدث خطأ في المخدم."
#: exceptions.py:84
msgid "Malformed request."
#: exceptions.py:142
msgid "Invalid input."
msgstr ""
#: exceptions.py:89
#: exceptions.py:161
msgid "Malformed request."
msgstr "الطلب صيغ بشكل سيء."
#: exceptions.py:167
msgid "Incorrect authentication credentials."
msgstr "بيانات الدخول غير صحيحة."
#: exceptions.py:94
#: exceptions.py:173
msgid "Authentication credentials were not provided."
msgstr "لم يتم تزويد بيانات الدخول."
#: exceptions.py:99
#: exceptions.py:179
msgid "You do not have permission to perform this action."
msgstr "ليس لديك صلاحية للقيام بهذا الإجراء."
#: exceptions.py:104 views.py:81
#: exceptions.py:185
msgid "Not found."
msgstr "غير موجود."
#: exceptions.py:109
#: exceptions.py:191
#, python-brace-format
msgid "Method \"{method}\" not allowed."
msgstr "طلب غير مسموح به"
msgstr "الطريقة \"{method}\" غير مسموح بها."
#: exceptions.py:120
#: exceptions.py:202
msgid "Could not satisfy the request Accept header."
msgstr ""
msgstr "لم نتمكن من تلبية الرٱس Accept في الطلب."
#: exceptions.py:132
#: exceptions.py:212
#, python-brace-format
msgid "Unsupported media type \"{media_type}\" in request."
msgstr ""
msgstr "الوسيط \"{media_type}\" الموجود في الطلب غير معتمد."
#: exceptions.py:145
#: exceptions.py:223
msgid "Request was throttled."
msgstr "تم تقييد الطلب."
#: exceptions.py:224
#, python-brace-format
msgid "Expected available in {wait} second."
msgstr ""
#: fields.py:269 relations.py:206 relations.py:239 validators.py:98
#: validators.py:181
#: exceptions.py:225
#, python-brace-format
msgid "Expected available in {wait} seconds."
msgstr ""
#: fields.py:316 relations.py:245 relations.py:279 validators.py:90
#: validators.py:183
msgid "This field is required."
msgstr "هذا الحقل مطلوب."
#: fields.py:270
#: fields.py:317
msgid "This field may not be null."
msgstr "لا يمكن لهذا الحقل ان يكون فارغاً null."
#: fields.py:608 fields.py:639
msgid "\"{input}\" is not a valid boolean."
msgstr "\"{input}\" ليس قيمة منطقية."
#: fields.py:701
msgid "Must be a valid boolean."
msgstr ""
#: fields.py:674
#: fields.py:766
msgid "Not a valid string."
msgstr ""
#: fields.py:767
msgid "This field may not be blank."
msgstr "لا يمكن لهذا الحقل ان يكون فارغاً."
#: fields.py:675 fields.py:1675
#: fields.py:768 fields.py:1881
#, python-brace-format
msgid "Ensure this field has no more than {max_length} characters."
msgstr "تأكد ان الحقل لا يزيد عن {max_length} محرف."
#: fields.py:676
#: fields.py:769
#, python-brace-format
msgid "Ensure this field has at least {min_length} characters."
msgstr "تأكد ان الحقل {min_length} محرف على الاقل."
#: fields.py:713
#: fields.py:816
msgid "Enter a valid email address."
msgstr "عليك ان تدخل بريد إلكتروني صالح."
#: fields.py:724
#: fields.py:827
msgid "This value does not match the required pattern."
msgstr "هذه القيمة لا تطابق النمط المطلوب."
#: fields.py:735
#: fields.py:838
msgid ""
"Enter a valid \"slug\" consisting of letters, numbers, underscores or "
"hyphens."
msgstr "أدخل \"slug\" صالح يحتوي على حروف، أرقام، شُرط سفلية أو واصلات."
#: fields.py:839
msgid ""
"Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, "
"or hyphens."
msgstr ""
#: fields.py:747
#: fields.py:854
msgid "Enter a valid URL."
msgstr "الرجاء إدخال رابط إلكتروني صالح."
#: fields.py:760
msgid "\"{value}\" is not a valid UUID."
#: fields.py:867
msgid "Must be a valid UUID."
msgstr ""
#: fields.py:796
#: fields.py:903
msgid "Enter a valid IPv4 or IPv6 address."
msgstr "برجاء إدخال عنوان IPV4 أو IPV6 صحيح"
msgstr "أدخِل عنوان IPV4 أو IPV6 صحيح."
#: fields.py:821
#: fields.py:931
msgid "A valid integer is required."
msgstr "الرجاء إدخال رقم صحيح صالح."
#: fields.py:822 fields.py:857 fields.py:891
#: fields.py:932 fields.py:969 fields.py:1005 fields.py:1366
#, python-brace-format
msgid "Ensure this value is less than or equal to {max_value}."
msgstr "تأكد ان القيمة أقل أو تساوي {max_value}."
#: fields.py:823 fields.py:858 fields.py:892
#: fields.py:933 fields.py:970 fields.py:1006 fields.py:1367
#, python-brace-format
msgid "Ensure this value is greater than or equal to {min_value}."
msgstr "تأكد ان القيمة أكبر أو تساوي {min_value}."
#: fields.py:824 fields.py:859 fields.py:896
#: fields.py:934 fields.py:971 fields.py:1010
msgid "String value too large."
msgstr "القيمه اكبر من المسموح"
msgstr "السلسلة اطول من القيمة المسموح بها."
#: fields.py:856 fields.py:890
#: fields.py:968 fields.py:1004
msgid "A valid number is required."
msgstr "الرجاء إدخال رقم صالح."
#: fields.py:893
#: fields.py:1007
#, python-brace-format
msgid "Ensure that there are no more than {max_digits} digits in total."
msgstr "تأكد ان القيمة لا تحوي أكثر من {max_digits} رقم."
#: fields.py:894
#: fields.py:1008
#, python-brace-format
msgid ""
"Ensure that there are no more than {max_decimal_places} decimal places."
msgstr ""
msgstr "تأكد انه لا يوجد اكثر من {max_decimal_places} منازل عشرية."
#: fields.py:895
#: fields.py:1009
#, python-brace-format
msgid ""
"Ensure that there are no more than {max_whole_digits} digits before the "
"decimal point."
msgstr ""
msgstr "تأكد انه لا يوجد اكثر من {max_whole_digits} أرقام قبل النقطة العشرية."
#: fields.py:1025
#: fields.py:1148
#, python-brace-format
msgid "Datetime has wrong format. Use one of these formats instead: {format}."
msgstr "صيغة التاريخ و الوقت غير صحيحة. عليك أن تستخدم واحدة من هذه الصيغ التالية: {format}."
#: fields.py:1026
#: fields.py:1149
msgid "Expected a datetime but got a date."
msgstr "متوقع تاريخ و وقت و وجد تاريخ فقط"
#: fields.py:1103
#: fields.py:1150
#, python-brace-format
msgid "Invalid datetime for the timezone \"{timezone}\"."
msgstr ""
#: fields.py:1151
msgid "Datetime value out of range."
msgstr ""
#: fields.py:1236
#, python-brace-format
msgid "Date has wrong format. Use one of these formats instead: {format}."
msgstr "صيغة التاريخ غير صحيحة. عليك أن تستخدم واحدة من هذه الصيغ التالية: {format}."
#: fields.py:1104
#: fields.py:1237
msgid "Expected a date but got a datetime."
msgstr "متوقع تاريخ فقط و وجد تاريخ ووقت"
#: fields.py:1170
#: fields.py:1303
#, python-brace-format
msgid "Time has wrong format. Use one of these formats instead: {format}."
msgstr "صيغة الوقت غير صحيحة. عليك أن تستخدم واحدة من هذه الصيغ التالية: {format}."
#: fields.py:1232
#: fields.py:1365
#, python-brace-format
msgid "Duration has wrong format. Use one of these formats instead: {format}."
msgstr "صيغة المده غير صحيحه, برجاء إستخدام أحد هذه الصيغ {format}"
msgstr "صيغة المدة غير صحيحه, يرجى إستخدام إحدى هذه الصيغ: {format}."
#: fields.py:1251 fields.py:1300
#: fields.py:1399 fields.py:1456
#, python-brace-format
msgid "\"{input}\" is not a valid choice."
msgstr "\"{input}\" ليست واحدة من الخيارات الصالحة."
#: fields.py:1254 relations.py:71 relations.py:441
#: fields.py:1402
#, python-brace-format
msgid "More than {count} items..."
msgstr "أكثر من {count} عنصر..."
#: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524
#: fields.py:1457 fields.py:1603 relations.py:485 serializers.py:570
#, python-brace-format
msgid "Expected a list of items but got type \"{input_type}\"."
msgstr ""
msgstr "المتوقع وجود قائمة عناصر لكن وجد النوع \"{input_type}\"."
#: fields.py:1302
#: fields.py:1458
msgid "This selection may not be empty."
msgstr ""
msgstr "هذا التحديد لا يجب أن يكون فارغا."
#: fields.py:1339
#: fields.py:1495
#, python-brace-format
msgid "\"{input}\" is not a valid path choice."
msgstr ""
msgstr "{input} كإختيار مسار غير صالح."
#: fields.py:1358
#: fields.py:1514
msgid "No file was submitted."
msgstr "لم يتم إرسال أي ملف."
#: fields.py:1359
#: fields.py:1515
msgid ""
"The submitted data was not a file. Check the encoding type on the form."
msgstr ""
msgstr "المعطيات المرسولة ليست ملف. إفحص نوع الترميز في النموذج."
#: fields.py:1360
#: fields.py:1516
msgid "No filename could be determined."
msgstr ""
msgstr "ما من إسم ملف أمكن تحديده."
#: fields.py:1361
#: fields.py:1517
msgid "The submitted file is empty."
msgstr "الملف الذي تم إرساله فارغ."
#: fields.py:1362
#: fields.py:1518
#, python-brace-format
msgid ""
"Ensure this filename has at most {max_length} characters (it has {length})."
msgstr "تأكد ان اسم الملف لا يحوي أكثر من {max_length} محرف (الإسم المرسل يحوي {length} محرف)."
#: fields.py:1410
#: fields.py:1566
msgid ""
"Upload a valid image. The file you uploaded was either not an image or a "
"corrupted image."
msgstr ""
msgstr "الرجاء تحميل صورة صالحة. الملف الذي تم تحميله إما لم يكن صورة او انه كان صورة تالفة."
#: fields.py:1449 relations.py:438 serializers.py:525
#: fields.py:1604 relations.py:486 serializers.py:571
msgid "This list may not be empty."
msgstr "القائمة يجب أن لا تكون فارغة."
#: fields.py:1605
#, python-brace-format
msgid "Ensure this field has at least {min_length} elements."
msgstr ""
#: fields.py:1502
#: fields.py:1606
#, python-brace-format
msgid "Ensure this field has no more than {max_length} elements."
msgstr ""
#: fields.py:1682
#, python-brace-format
msgid "Expected a dictionary of items but got type \"{input_type}\"."
msgstr "المتوقع كان قاموس عناصر و لكن النوع المتحصل عليه هو \"{input_type}\"."
#: fields.py:1683
msgid "This dictionary may not be empty."
msgstr ""
#: fields.py:1549
#: fields.py:1755
msgid "Value must be valid JSON."
msgstr ""
msgstr "القيمة يجب أن تكون JSON صالح."
#: filters.py:36 templates/rest_framework/filters/django_filter.html:5
msgid "Submit"
msgstr "أرسل"
#: filters.py:336
msgid "ascending"
msgstr "تصاعدي"
#: filters.py:337
msgid "descending"
msgstr "تنازلي"
#: pagination.py:193
msgid "Invalid page."
msgstr "صفحة غير صحيحة."
#: pagination.py:427
msgid "Invalid cursor"
msgstr ""
#: relations.py:207
msgid "Invalid pk \"{pk_value}\" - object does not exist."
msgstr "معرف العنصر \"{pk_value}\" غير صالح - العنصر غير موجود."
#: relations.py:208
msgid "Incorrect type. Expected pk value, received {data_type}."
msgstr ""
#: relations.py:240
msgid "Invalid hyperlink - No URL match."
msgstr ""
#: relations.py:241
msgid "Invalid hyperlink - Incorrect URL match."
msgstr ""
#: relations.py:242
msgid "Invalid hyperlink - Object does not exist."
msgstr ""
#: relations.py:243
msgid "Incorrect type. Expected URL string, received {data_type}."
msgstr ""
#: relations.py:401
msgid "Object with {slug_name}={value} does not exist."
msgstr ""
#: relations.py:402
msgid "Invalid value."
msgstr "قيمة غير صالحة."
#: serializers.py:326
msgid "Invalid data. Expected a dictionary, but got {datatype}."
msgstr ""
#: templates/rest_framework/admin.html:116
#: templates/rest_framework/base.html:128
msgid "Filters"
msgstr "مرشحات"
#: templates/rest_framework/filters/django_filter.html:2
#: templates/rest_framework/filters/django_filter_crispyforms.html:4
msgid "Field filters"
msgstr "مرشحات الحقول"
#: templates/rest_framework/filters/ordering.html:3
msgid "Ordering"
msgstr "الترتيب"
#: templates/rest_framework/filters/search.html:2
#: filters.py:49 templates/rest_framework/filters/search.html:2
msgid "Search"
msgstr "بحث"
#: templates/rest_framework/horizontal/radio.html:2
#: templates/rest_framework/inline/radio.html:2
#: templates/rest_framework/vertical/radio.html:2
#: filters.py:50
msgid "A search term."
msgstr ""
#: filters.py:180 templates/rest_framework/filters/ordering.html:3
msgid "Ordering"
msgstr "الترتيب"
#: filters.py:181
msgid "Which field to use when ordering the results."
msgstr ""
#: filters.py:287
msgid "ascending"
msgstr "تصاعدي"
#: filters.py:288
msgid "descending"
msgstr "تنازلي"
#: pagination.py:174
msgid "A page number within the paginated result set."
msgstr ""
#: pagination.py:179 pagination.py:372 pagination.py:590
msgid "Number of results to return per page."
msgstr ""
#: pagination.py:189
msgid "Invalid page."
msgstr "صفحة غير صحيحة."
#: pagination.py:374
msgid "The initial index from which to return the results."
msgstr ""
#: pagination.py:581
msgid "The pagination cursor value."
msgstr ""
#: pagination.py:583
msgid "Invalid cursor"
msgstr "مؤشر غير صالح"
#: relations.py:246
#, python-brace-format
msgid "Invalid pk \"{pk_value}\" - object does not exist."
msgstr "معرف العنصر \"{pk_value}\" غير صالح - العنصر غير موجود."
#: relations.py:247
#, python-brace-format
msgid "Incorrect type. Expected pk value, received {data_type}."
msgstr "نوع خاطئ. المتوقع قيمة من pk، لكن المتحصل عليه {data_type}."
#: relations.py:280
msgid "Invalid hyperlink - No URL match."
msgstr "إرتباط تشعبي غير صالح - لا مطابقة لURL."
#: relations.py:281
msgid "Invalid hyperlink - Incorrect URL match."
msgstr "إرتباط تشعبي غير صالح - مطابقة خاطئة لURL."
#: relations.py:282
msgid "Invalid hyperlink - Object does not exist."
msgstr "إرتباط تشعبي غير صالح - عنصر غير موجود."
#: relations.py:283
#, python-brace-format
msgid "Incorrect type. Expected URL string, received {data_type}."
msgstr "نوع خاطئ. المتوقع سلسلة URL، لكن المتحصل عليه {data_type}."
#: relations.py:448
#, python-brace-format
msgid "Object with {slug_name}={value} does not exist."
msgstr "عنصر ب {slug_name}={value} غير موجود."
#: relations.py:449
msgid "Invalid value."
msgstr "قيمة غير صالحة."
#: schemas/utils.py:32
msgid "unique integer value"
msgstr ""
#: schemas/utils.py:34
msgid "UUID string"
msgstr ""
#: schemas/utils.py:36
msgid "unique value"
msgstr ""
#: schemas/utils.py:38
#, python-brace-format
msgid "A {value_type} identifying this {name}."
msgstr ""
#: serializers.py:337
#, python-brace-format
msgid "Invalid data. Expected a dictionary, but got {datatype}."
msgstr "معطيات غير صالحة. المتوقع هو قاموس، لكن المتحصل عليه {datatype}."
#: templates/rest_framework/admin.html:116
#: templates/rest_framework/base.html:136
msgid "Extra Actions"
msgstr ""
#: templates/rest_framework/admin.html:130
#: templates/rest_framework/base.html:150
msgid "Filters"
msgstr "مرشحات"
#: templates/rest_framework/base.html:37
msgid "navbar"
msgstr ""
#: templates/rest_framework/base.html:75
msgid "content"
msgstr ""
#: templates/rest_framework/base.html:78
msgid "request form"
msgstr ""
#: templates/rest_framework/base.html:157
msgid "main content"
msgstr ""
#: templates/rest_framework/base.html:173
msgid "request info"
msgstr ""
#: templates/rest_framework/base.html:177
msgid "response info"
msgstr ""
#: templates/rest_framework/horizontal/radio.html:4
#: templates/rest_framework/inline/radio.html:3
#: templates/rest_framework/vertical/radio.html:3
msgid "None"
msgstr "لا شيء"
#: templates/rest_framework/horizontal/select_multiple.html:2
#: templates/rest_framework/inline/select_multiple.html:2
#: templates/rest_framework/vertical/select_multiple.html:2
#: templates/rest_framework/horizontal/select_multiple.html:4
#: templates/rest_framework/inline/select_multiple.html:3
#: templates/rest_framework/vertical/select_multiple.html:3
msgid "No items to select."
msgstr ""
msgstr "ما من عناصر للتحديد."
#: validators.py:43
#: validators.py:39
msgid "This field must be unique."
msgstr "هذا الحقل يجب أن يكون فريد"
#: validators.py:97
#: validators.py:89
#, python-brace-format
msgid "The fields {field_names} must make a unique set."
msgstr "الحقول {field_names} يجب أن تشكل مجموعة فريدة."
#: validators.py:171
#, python-brace-format
msgid "Surrogate characters are not allowed: U+{code_point:X}."
msgstr ""
#: validators.py:245
#: validators.py:243
#, python-brace-format
msgid "This field must be unique for the \"{date_field}\" date."
msgstr ""
msgstr "الحقل يجب ان يكون فريد للتاريخ {date_field}."
#: validators.py:260
#: validators.py:258
#, python-brace-format
msgid "This field must be unique for the \"{date_field}\" month."
msgstr ""
msgstr "الحقل يجب ان يكون فريد للشهر {date_field}."
#: validators.py:273
#: validators.py:271
#, python-brace-format
msgid "This field must be unique for the \"{date_field}\" year."
msgstr ""
msgstr "الحقل يجب ان يكون فريد للعام {date_field}."
#: versioning.py:42
#: versioning.py:40
msgid "Invalid version in \"Accept\" header."
msgstr ""
msgstr "إصدار غير صالح في الرٱس \"Accept\"."
#: versioning.py:73
#: versioning.py:71
msgid "Invalid version in URL path."
msgstr ""
msgstr "إصدار غير صالح في المسار URL."
#: versioning.py:115
#: versioning.py:116
msgid "Invalid version in URL path. Does not match any version namespace."
msgstr ""
msgstr " إصدار غير صالح في المسار URL. لا يطابق أي إصدار من مساحة الإسم."
#: versioning.py:147
#: versioning.py:148
msgid "Invalid version in hostname."
msgstr ""
msgstr "إصدار غير صالح في اسم المضيف."
#: versioning.py:169
#: versioning.py:170
msgid "Invalid version in query parameter."
msgstr ""
#: views.py:88
msgid "Permission denied."
msgstr "ليس لديك صلاحية."
msgstr "إصدار غير صالح في معلمة الإستعلام."

Binary file not shown.

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