Merge branch 'master' into openapi-serializer-field-name

This commit is contained in:
Tom Christie 2022-10-17 10:39:38 +01:00 committed by GitHub
commit d2128ce65c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
279 changed files with 17572 additions and 7381 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

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

@ -0,0 +1,51 @@
name: CI
on:
push:
branches:
- master
pull_request:
jobs:
tests:
name: Python ${{ matrix.python-version }}
runs-on: ubuntu-20.04
strategy:
matrix:
python-version:
- '3.6'
- '3.7'
- '3.8'
- '3.9'
- '3.10'
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
cache-dependency-path: 'requirements/*.txt'
- name: Upgrade packaging tools
run: python -m pip install --upgrade pip setuptools virtualenv wheel
- name: Install dependencies
run: python -m pip install --upgrade codecov tox tox-py
- name: Run tox targets for ${{ matrix.python-version }}
run: tox --py current
- name: Run extra tox targets
if: ${{ matrix.python-version == '3.9' }}
run: |
python setup.py bdist_wheel
rm -r djangorestframework.egg-info # see #6139
tox -e base,dist,docs
tox -e dist --installpkg ./dist/djangorestframework-*.whl
- name: Upload coverage
run: |
codecov -e TOXENV,DJANGO

24
.github/workflows/pre-commit.yml vendored Normal file
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,50 +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.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-venv 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)
* Django (2.2, 3.0)
* 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.
INSTALLED_APPS = [
...
'rest_framework',
]
```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,13 +199,13 @@ If you've already created some users, you can generate tokens for all existing u
for user in User.objects.all():
Token.objects.get_or_create(user=user)
##### By exposing an api endpoint
#### By exposing an api endpoint
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behaviour. To use it, add the `obtain_auth_token` view to your URLconf:
from rest_framework.authtoken import views
urlpatterns += [
url(r'^api-token-auth/', views.obtain_auth_token)
path('api-token-auth/', views.obtain_auth_token)
]
Note that the URL part of the pattern can be whatever you want to use.
@ -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 to throttle 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.
@ -238,13 +244,13 @@ For example, you may return additional user information beyond the `token` value
And in your `urls.py`:
urlpatterns += [
url(r'^api-token-auth/', CustomAuthToken.as_view())
path('api-token-auth/', CustomAuthToken.as_view())
]
##### With Django admin
#### With Django admin
It is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class 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 behaviour is not suitable for login views, which should always have CSRF validation applied.
## RemoteUserAuthentication
@ -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.
@ -332,7 +338,7 @@ If the `.authenticate_header()` method is not overridden, the authentication sch
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'.
from django.contrib.auth.models import User
from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import exceptions
@ -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 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

@ -82,7 +82,7 @@ The default content negotiation class may be set globally, using the `DEFAULT_CO
You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class-based views.
from myapp.negotiation import IgnoreClientContentNegotiation
from myapp.negotiation import IgnoreClientContentNegotiation
from rest_framework.response import Response
from rest_framework.views import APIView

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,7 +42,7 @@ 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`
@ -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")
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.
@ -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,13 @@ Corresponds to `django.db.models.fields.DecimalField`.
**Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)`
- `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
- `decimal_places` The number of decimal places to store with the number.
- `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
- `max_value` Validate that the number provided is no greater than this value.
- `min_value` Validate that the number provided is no less than this value.
- `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
- `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
* `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
* `decimal_places` The number of decimal places to store with the number.
* `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
* `max_value` Validate that the number provided is no greater than this value.
* `min_value` Validate that the number provided is no less than this value.
* `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
* `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
#### Example usage
@ -307,10 +306,6 @@ And to validate numbers up to anything less than one billion with a resolution o
serializers.DecimalField(max_digits=19, decimal_places=10)
This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer.
If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise.
---
# Date and time fields
@ -325,7 +320,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.
@ -371,7 +366,7 @@ Corresponds to `django.db.models.fields.TimeField`
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `TIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `time` objects should be returned by `to_representation`. In this case the time encoding will be determined by the renderer.
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
#### `TimeField` format strings
#### `TimeField` format strings
Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`)
@ -385,8 +380,8 @@ The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu
**Signature:** `DurationField(max_value=None, min_value=None)`
- `max_value` Validate that the duration provided is no greater than this value.
- `min_value` Validate that the duration provided is no less than this value.
* `max_value` Validate that the duration provided is no greater than this value.
* `min_value` Validate that the duration provided is no less than this value.
---
@ -400,10 +395,10 @@ Used by `ModelSerializer` to automatically generate fields if the corresponding
**Signature:** `ChoiceField(choices)`
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
@ -413,10 +408,10 @@ A field that can accept a set of zero, one or many values, chosen from a limited
**Signature:** `MultipleChoiceField(choices)`
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
@ -437,9 +432,9 @@ Corresponds to `django.forms.fields.FileField`.
**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
- `max_length` - Designates the maximum length for the file name.
- `allow_empty_file` - Designates if empty files are allowed.
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
* `max_length` - Designates the maximum length for the file name.
* `allow_empty_file` - Designates if empty files are allowed.
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
## ImageField
@ -449,9 +444,9 @@ Corresponds to `django.forms.fields.ImageField`.
**Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
- `max_length` - Designates the maximum length for the file name.
- `allow_empty_file` - Designates if empty files are allowed.
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
* `max_length` - Designates the maximum length for the file name.
* `allow_empty_file` - Designates if empty files are allowed.
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained.
@ -465,10 +460,10 @@ A field class that validates a list of objects.
**Signature**: `ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)`
- `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
- `allow_empty` - Designates if empty lists are allowed.
- `min_length` - Validates that the list contains no fewer than this number of elements.
- `max_length` - Validates that the list contains no more than this number of elements.
* `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
* `allow_empty` - Designates if empty lists are allowed.
* `min_length` - Validates that the list contains no fewer than this number of elements.
* `max_length` - Validates that the list contains no more than this number of elements.
For example, to validate a list of integers you might use something like the following:
@ -489,8 +484,8 @@ A field class that validates a dictionary of objects. The keys in `DictField` ar
**Signature**: `DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
- `allow_empty` - Designates if empty dictionaries are allowed.
* `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
* `allow_empty` - Designates if empty dictionaries are allowed.
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
@ -507,8 +502,8 @@ A preconfigured `DictField` that is compatible with Django's postgres `HStoreFie
**Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
- `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
- `allow_empty` - Designates if empty dictionaries are allowed.
* `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
* `allow_empty` - Designates if empty dictionaries are allowed.
Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings.
@ -518,8 +513,8 @@ A field class that validates that the incoming data structure consists of valid
**Signature**: `JSONField(binary, encoder)`
- `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
- `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
* `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
* `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
---
@ -570,7 +565,7 @@ This is a read-only field. It gets its value by calling a method on the serializ
**Signature**: `SerializerMethodField(method_name=None)`
- `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
* `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
The serializer method referred to by the `method_name` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
@ -583,6 +578,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
@ -854,3 +850,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

@ -45,7 +45,7 @@ Another style of filtering might involve restricting the queryset based on some
For example if your URL config contained an entry like this:
url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
re_path('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
@ -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
@ -145,10 +145,18 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering
The [`django-filter`][django-filter-docs] library includes a `DjangoFilterBackend` class which
supports highly customizable field filtering for REST framework.
To use `DjangoFilterBackend`, first install `django-filter`. Then add `django_filters` to Django's `INSTALLED_APPS`
To use `DjangoFilterBackend`, first install `django-filter`.
pip install django-filter
Then add `'django_filters'` to Django's `INSTALLED_APPS`:
INSTALLED_APPS = [
...
'django_filters',
...
]
You should now either add the filter backend to your settings:
REST_FRAMEWORK = {
@ -216,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:
@ -233,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].
@ -327,7 +335,7 @@ Generic filters may also present an interface in the browsable API. To do so you
The method should return a rendered HTML string.
## Pagination & schemas
## Filtering & schemas
You can also make the filter controls available to the schema autogeneration
that REST framework provides, by implementing a `get_schema_fields()` method. This method should have the following signature:
@ -365,4 +373,5 @@ The [djangorestframework-word-filter][django-rest-framework-word-search-filter]
[django-url-filter]: https://github.com/miki725/django-url-filter
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
[HStoreField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#hstorefield
[JSONField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#jsonfield
[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

@ -32,9 +32,9 @@ Example:
from blog import views
urlpatterns = [
url(r'^/$', views.apt_root),
url(r'^comments/$', views.comment_list),
url(r'^comments/(?P<pk>[0-9]+)/$', views.comment_detail)
path('', views.apt_root),
path('comments/', views.comment_list),
path('comments/<int:pk>/', views.comment_detail)
]
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
@ -62,7 +62,7 @@ Also note that `format_suffix_patterns` does not support descending into `includ
If using the `i18n_patterns` function provided by Django, as well as `format_suffix_patterns` you should make sure that the `i18n_patterns` function is applied as the final, or outermost function. For example:
url patterns = [
urlpatterns = [
]

View File

@ -45,7 +45,7 @@ For more complex cases you might also want to override various methods on the vi
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something like the following entry:
url(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
path('users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
---
@ -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.
@ -312,7 +312,7 @@ The [`drf-proxy-pagination` package][drf-proxy-pagination] includes a `ProxyPagi
## link-header-pagination
The [`django-rest-framework-link-header-pagination` package][drf-link-header-pagination] includes a `LinkHeaderPagination` class which provides pagination via an HTTP `Link` header as described in [Github's developer documentation](github-link-pagination).
The [`django-rest-framework-link-header-pagination` package][drf-link-header-pagination] includes a `LinkHeaderPagination` class which provides pagination via an HTTP `Link` header as described in [GitHub REST API documentation][github-traversing-with-pagination].
[cite]: https://docs.djangoproject.com/en/stable/topics/pagination/
[link-header]: ../img/link-header-pagination.png
@ -322,3 +322,4 @@ The [`django-rest-framework-link-header-pagination` package][drf-link-header-pag
[drf-link-header-pagination]: https://github.com/tbeadle/django-rest-framework-link-header-pagination
[disqus-cursor-api]: https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api
[float_cursor_pagination_example]: https://gist.github.com/keturn/8bc88525a183fd41c73ffb729b8865be#file-fpcursorpagination-py
[github-traversing-with-pagination]: https://docs.github.com/en/rest/guides/traversing-with-pagination

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`
@ -125,7 +125,7 @@ If it is called without a `filename` URL keyword argument, then the client must
# urls.py
urlpatterns = [
# ...
url(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
re_path(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
]
---

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,7 +171,7 @@ 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.
@ -179,12 +181,6 @@ The default behaviour can also be overridden to support custom model permissions
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
@ -312,6 +332,11 @@ The [Django REST Framework API Key][djangorestframework-api-key] package provide
The [Django Rest Framework Role Filters][django-rest-framework-role-filters] package provides simple filtering over multiple types of roles.
## Django Rest Framework PSQ
The [Django Rest Framework PSQ][drf-psq] package is an extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
[authentication]: authentication.md
[throttling]: throttling.md
@ -328,3 +353,4 @@ The [Django Rest Framework Role Filters][django-rest-framework-role-filters] pac
[django-rest-framework-role-filters]: https://github.com/allisson/django-rest-framework-role-filters
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
[drf-access-policy]: https://github.com/rsinger86/drf-access-policy
[drf-psq]: https://github.com/drf-psq/drf-psq

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.
@ -247,7 +278,7 @@ This field is always read-only.
As opposed to previously discussed _references_ to another entity, the referred entity can instead also be embedded or _nested_
in the representation of the object that refers to it.
Such nested relationships can be expressed by using serializers as fields.
Such nested relationships can be expressed by using serializers as fields.
If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field.
@ -337,7 +368,7 @@ output representation should be generated from the model instance.
To implement a custom relational field, you should override `RelatedField`, and implement the `.to_representation(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. The `value` argument will typically be a model instance.
If you want to implement a read-write relational field, you must also implement the `.to_internal_value(self, data)` method.
If you want to implement a read-write relational field, you must also implement the [`.to_internal_value(self, data)` method][to_internal_value].
To provide a dynamic queryset based on the `context`, you can also override `.get_queryset(self)` instead of specifying `.queryset` on the class or when initializing the field.
@ -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,5 +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
---
@ -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
@ -503,7 +513,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
## UltraJSON
[UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Jacob Haslehurst][hzy] maintains the [drf-ujson-renderer][drf-ujson-renderer] package which implements JSON rendering using the UJSON package.
[UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Adam Mertz][Amertz08] maintains [drf_ujson2][drf_ujson2], a fork of the now unmaintained [drf-ujson-renderer][drf-ujson-renderer], which implements JSON rendering using the UJSON package.
## CamelCase JSON
@ -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/
@ -547,8 +557,9 @@ Comma-separated values are a plain-text tabular data format, that can be easily
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
[ultrajson]: https://github.com/esnme/ultrajson
[hzy]: https://github.com/hzy
[Amertz08]: https://github.com/Amertz08
[drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer
[drf_ujson2]: https://github.com/Amertz08/drf_ujson2
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
[Django REST Pandas]: https://github.com/wq/django-rest-pandas
[Pandas]: https://pandas.pydata.org/

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

@ -32,16 +32,16 @@ You should **include the request as a keyword argument** to the function, for ex
from rest_framework.reverse import reverse
from rest_framework.views import APIView
from django.utils.timezone import now
from django.utils.timezone import now
class APIRootView(APIView):
def get(self, request):
year = now().year
data = {
...
'year-summary-url': reverse('year-summary', args=[year], request=request)
class APIRootView(APIView):
def get(self, request):
year = now().year
data = {
...
'year-summary-url': reverse('year-summary', args=[year], request=request)
}
return Response(data)
return Response(data)
## reverse_lazy

View File

@ -63,7 +63,7 @@ For example, you can append `router.urls` to a list of existing views...
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
path('forgot-password/', ForgotPasswordFormView.as_view()),
]
urlpatterns += router.urls
@ -71,22 +71,22 @@ For example, you can append `router.urls` to a list of existing views...
Alternatively you can use Django's `include` function, like so...
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^', include(router.urls)),
path('forgot-password', ForgotPasswordFormView.as_view()),
path('', include(router.urls)),
]
You may use `include` with an application namespace:
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^api/', include((router.urls, 'app_name'))),
path('forgot-password/', ForgotPasswordFormView.as_view()),
path('api/', include((router.urls, 'app_name'))),
]
Or both an application and instance namespace:
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^api/', include((router.urls, 'app_name'), namespace='instance_name')),
path('forgot-password/', ForgotPasswordFormView.as_view()),
path('api/', include((router.urls, 'app_name'), namespace='instance_name')),
]
See Django's [URL namespaces docs][url-namespace-docs] and the [`include` API reference][include-api-reference] for more details.
@ -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

@ -114,7 +114,7 @@ The `get_schema_view()` helper takes the following keyword arguments:
only want the `myproject.api` urls to be exposed in the schema:
schema_url_patterns = [
url(r'^api/', include('myproject.api.urls')),
path('api/', include('myproject.api.urls')),
]
schema_view = get_schema_view(
@ -122,6 +122,7 @@ The `get_schema_view()` helper takes the following keyword arguments:
url='https://www.example.org/api/',
patterns=schema_url_patterns,
)
* `public`: May be used to specify if schema should bypass views permissions. Default to False
* `generator_class`: May be used to specify a `SchemaGenerator` subclass to be
passed to the `SchemaView`.
@ -165,7 +166,7 @@ In order to customize the top-level schema, subclass
as an argument to the `generateschema` command or `get_schema_view()` helper
function.
### get_schema(self, request)
### get_schema(self, request=None, public=False)
Returns a dictionary that represents the OpenAPI schema:
@ -181,8 +182,8 @@ dictionary For example you might wish to add terms of service to the [top-level
```
class TOSSchemaGenerator(SchemaGenerator):
def get_schema(self):
schema = super().get_schema()
def get_schema(self, *args, **kwargs):
schema = super().get_schema(*args, **kwargs)
schema["info"]["termsOfService"] = "https://example.com/tos.html"
return schema
```
@ -313,6 +314,11 @@ Computes the component's name from the serializer.
You may see warnings if your API has duplicate component names. If so you can override `get_component_name()` or pass the `component_name` `__init__()` kwarg (see below) to provide different names.
#### `get_reference()`
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
#### `map_serializer()`
Maps serializers to their OpenAPI representations.
@ -375,6 +381,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 +427,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

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()`
@ -161,7 +161,7 @@ Each key in the dictionary will be the field name, and the values will be lists
When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.
#### Raising an exception on invalid data
#### Raising an exception on invalid data
The `.is_valid()` method takes an optional `raise_exception` flag that will cause it to raise a `serializers.ValidationError` exception if there are validation errors.
@ -251,7 +251,7 @@ For more information see the [validators documentation](validators.md).
When passing an initial object or queryset to a serializer instance, the object will be made available as `.instance`. If no initial object is passed then the `.instance` attribute will be `None`.
When passing data to a serializer instance, the unmodified data will be made available as `.initial_data`. If the data keyword argument is not passed then the `.initial_data` attribute will not exist.
When passing data to a serializer instance, the unmodified data will be made available as `.initial_data`. If the `data` keyword argument is not passed then the `.initial_data` attribute will not exist.
## Partial updates
@ -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.
@ -601,17 +602,17 @@ A mapping of Django model fields to REST framework serializer fields. You can ov
This property should be the serializer field class, that is used for relational fields by default.
For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`.
For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`.
For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`.
### `serializer_url_field`
### `.serializer_url_field`
The serializer field class that should be used for any `url` field on the serializer.
Defaults to `serializers.HyperlinkedIdentityField`
### `serializer_choice_field`
### `.serializer_choice_field`
The serializer field class that should be used for any choice fields on the serializer.
@ -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:
@ -901,7 +910,7 @@ We can now use this class to serialize single `HighScore` instances:
def high_score(request, pk):
instance = HighScore.objects.get(pk=pk)
serializer = HighScoreSerializer(instance)
return Response(serializer.data)
return Response(serializer.data)
Or use it to serialize multiple instances:
@ -909,9 +918,9 @@ Or use it to serialize multiple instances:
def all_high_scores(request):
queryset = HighScore.objects.order_by('-score')
serializer = HighScoreSerializer(queryset, many=True)
return Response(serializer.data)
return Response(serializer.data)
##### Read-write `BaseSerializer` classes
#### Read-write `BaseSerializer` classes
To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `serializers.ValidationError` if the supplied data is in an incorrect format.
@ -940,8 +949,8 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
'player_name': 'May not be more than 10 characters.'
})
# Return the validated values. This will be available as
# the `.validated_data` property.
# Return the validated values. This will be available as
# the `.validated_data` property.
return {
'score': int(score),
'player_name': player_name
@ -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):
"""
@ -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.
@ -1180,7 +1189,7 @@ The [drf-writable-nested][drf-writable-nested] package provides writable nested
## DRF Encrypt Content
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion

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.
@ -46,9 +50,9 @@ The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `mi
You can also set the throttling policy on a per-view or per-viewset basis,
using the `APIView` class-based views.
from rest_framework.response import Response
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView
from rest_framework.views import APIView
class ExampleView(APIView):
throttle_classes = [UserRateThrottle]
@ -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

@ -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):
@ -169,7 +170,7 @@ To override the default settings, REST framework provides a set of additional de
from rest_framework.throttling import UserRateThrottle
class OncePerDayUserThrottle(UserRateThrottle):
rate = '1/day'
rate = '1/day'
@api_view(['GET'])
@throttle_classes([OncePerDayUserThrottle])

View File

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

@ -0,0 +1,169 @@
<style>
.promo li a {
float: left;
width: 130px;
height: 20px;
text-align: center;
margin: 10px 30px;
padding: 150px 0 0 0;
background-position: 0 50%;
background-size: 130px auto;
background-repeat: no-repeat;
font-size: 120%;
color: black;
}
.promo li {
list-style: none;
}
</style>
# Django REST framework 3.12
REST framework 3.12 brings a handful of refinements to the OpenAPI schema
generation, plus support for Django's new database-agnostic `JSONField`,
and some improvements to the `SearchFilter` class.
## Grouping operations with tags.
Open API schemas will now automatically include tags, based on the first element
in the URL path.
For example...
Method | Path | Tags
--------------------------------|-----------------|-------------
`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']`
`GET`, `POST` | `/users/` | `['users']`
`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']`
`GET`, `POST` | `/orders/` | `['orders']`
The tags used for a particular view may also be overridden...
```python
class MyOrders(APIView):
schema = AutoSchema(tags=['users', 'orders'])
...
```
See [the schema documentation](https://www.django-rest-framework.org/api-guide/schemas/#grouping-operations-with-tags) for more information.
## Customizing the operation ID.
REST framework automatically determines operation IDs to use in OpenAPI
schemas. The latest version provides more control for overriding the behaviour
used to generate the operation IDs.
See [the schema documentation](https://www.django-rest-framework.org/api-guide/schemas/#operationid) for more information.
## Support for OpenAPI components.
In order to output more graceful OpenAPI schemes, REST framework 3.12 now
defines components in the schema, and then references them inside request
and response objects. This is in contrast with the previous approach, which
fully expanded the request and response bodies for each operation.
The names used for a component default to using the serializer class name, [but
may be overridden if needed](https://www.django-rest-framework.org/api-guide/schemas/#components
)...
```python
class MyOrders(APIView):
schema = AutoSchema(component_name="OrderDetails")
```
## More Public API
Many methods on the `AutoSchema` class have now been promoted to public API,
allowing you to more fully customize the schema generation. The following methods
are now available for overriding...
* `get_path_parameters`
* `get_pagination_parameters`
* `get_filter_parameters`
* `get_request_body`
* `get_responses`
* `get_serializer`
* `get_paginator`
* `map_serializer`
* `map_field`
* `map_choice_field`
* `map_field_validators`
* `allows_filters`.
See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#per-view-customization)
for details on using custom `AutoSchema` subclasses.
## Support for JSONField.
Django 3.1 deprecated the existing `django.contrib.postgres.fields.JSONField`
in favour of a new database-agnositic `JSONField`.
REST framework 3.12 now supports this new model field, and `ModelSerializer`
classes will correctly map the model field.
## SearchFilter improvements
There are a couple of significant improvements to the `SearchFilter` class.
### Nested searches against JSONField and HStoreField
The class now supports nested search within `JSONField` and `HStoreField`, using
the double underscore notation for traversing which element of the field the
search should apply to.
```python
class SitesSearchView(generics.ListAPIView):
"""
An API view to return a list of archaeological sites, optionally filtered
by a search against the site name or location. (Location searches are
matched against the region and country names.)
"""
queryset = Sites.objects.all()
serializer_class = SitesSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['site_name', 'location__region', 'location__country']
```
### Searches against annotate fields
Django allows querysets to create additional virtual fields, using the `.annotate`
method. We now support searching against annotate fields.
```python
class PublisherSearchView(generics.ListAPIView):
"""
Search for publishers, optionally filtering the search against the average
rating of all their books.
"""
queryset = Publisher.objects.annotate(avg_rating=Avg('book__rating'))
serializer_class = PublisherSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['avg_rating']
```
---
## Funding
REST framework is a *collaboratively funded project*. If you use
REST framework commercially we strongly encourage you to invest in its
continued development by **[signing up for a paid plan][funding]**.
*Every single sign-up helps us make REST framework long-term financially sustainable.*
<ul class="premium-promo promo">
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
<li><a href="https://software.esg-usa.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/esg-new-logo.png)">ESG</a></li>
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
<li><a href="https://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
<li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless-plus-text.png)">Kloudless</a></li>
<li><a href="https://lightsonsoftware.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/lightson-dark.png)">Lights On Software</a></li>
<li><a href="https://retool.com/?utm_source=djangorest&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/retool-sidebar.png)">Retool</a></li>
</ul>
<div style="clear: both; padding-bottom: 20px;"></div>
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), and [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship).*
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[funding]: funding.md

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

@ -69,7 +69,7 @@ schema_view = get_schema_view(
)
urlpatterns = [
url(r'^swagger/$', schema_view),
path('swagger/', schema_view),
...
]
```
@ -198,8 +198,8 @@ Make sure to include the view before your router urls. For example:
schema_view = get_schema_view(title='Example API')
urlpatterns = [
url('^$', schema_view),
url(r'^', include(router.urls)),
path('', schema_view),
path('', include(router.urls)),
]
### Schema path representations

View File

@ -73,7 +73,7 @@ To install the API documentation, you'll need to include it in your projects URL
urlpatterns = [
...
url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))
path('docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))
]
Once installed you should see something a little like this:

View File

@ -62,6 +62,7 @@ Here's an example of adding an OpenAPI schema to the URL conf:
```python
from rest_framework.schemas import get_schema_view
from rest_framework.renderers import JSONOpenAPIRenderer
from django.urls import path
schema_view = get_schema_view(
title='Server Monitoring API',
@ -70,7 +71,7 @@ schema_view = get_schema_view(
)
urlpatterns = [
url('^schema.json$', schema_view),
path('schema.json', schema_view),
...
]
```
@ -109,7 +110,7 @@ You can now compose permission classes using the and/or operators, `&` and `|`.
For example...
```python
permission_classes = [IsAuthenticated & (ReadOnly | IsAdmin)]
permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)]
```
If you're using custom permission classes then make sure that you are subclassing

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

View File

@ -34,13 +34,151 @@ You can determine your currently installed version using `pip show`:
---
## 3.14.x series
### 3.14.0
Date: 22nd September 2022
* Django 2.2 is no longer supported. [[#8662](https://github.com/encode/django-rest-framework/pull/8662)]
* Django 4.1 compatibility. [[#8591](https://github.com/encode/django-rest-framework/pull/8591)]
* Add `--api-version` CLI option to `generateschema` management command. [[#8663](https://github.com/encode/django-rest-framework/pull/8663)]
* Enforce `is_valid(raise_exception=False)` as a keyword-only argument. [[#7952](https://github.com/encode/django-rest-framework/pull/7952)]
* Stop calling `set_context` on Validators. [[#8589](https://github.com/encode/django-rest-framework/pull/8589)]
* Return `NotImplemented` from `ErrorDetails.__ne__`. [[#8538](https://github.com/encode/django-rest-framework/pull/8538)]
* Don't evaluate `DateTimeField.default_timezone` when a custom timezone is set. [[#8531](https://github.com/encode/django-rest-framework/pull/8531)]
* Make relative URLs clickable in Browseable API. [[#8464](https://github.com/encode/django-rest-framework/pull/8464)]
* Support `ManyRelatedField` falling back to the default value when the attribute specified by dot notation doesn't exist. Matches `ManyRelatedField.get_attribute` to `Field.get_attribute`. [[#7574](https://github.com/encode/django-rest-framework/pull/7574)]
* Make `schemas.openapi.get_reference` public. [[#7515](https://github.com/encode/django-rest-framework/pull/7515)]
* Make `ReturnDict` support `dict` union operators on Python 3.9 and later. [[#8302](https://github.com/encode/django-rest-framework/pull/8302)]
* Update throttling to check if `request.user` is set before checking if the user is authenticated. [[#8370](https://github.com/encode/django-rest-framework/pull/8370)]
## 3.13.x series
### 3.13.1
Date: 15th December 2021
* Revert schema naming changes with function based `@api_view`. [#8297]
### 3.13.0
Date: 13th December 2021
* Django 4.0 compatability. [#8178]
* Add `max_length` and `min_length` options to `ListSerializer`. [#8165]
* Add `get_request_serializer` and `get_response_serializer` hooks to `AutoSchema`. [#7424]
* Fix OpenAPI representation of null-able read only fields. [#8116]
* Respect `UNICODE_JSON` setting in API schema outputs. [#7991]
* Fix for `RemoteUserAuthentication`. [#7158]
* Make Field constructors keyword-only. [#7632]
---
## 3.12.x series
### 3.12.4
Date: 26th March 2021
* Revert use of `deque` instead of `list` for tracking throttling `.history`. (Due to incompatibility with DjangoRedis cache backend. See #7870) [#7872]
### 3.12.3
Date: 25th March 2021
* Properly handle ATOMIC_REQUESTS when multiple database configurations are used. [#7739]
* Bypass `COUNT` query when `LimitOffsetPagination` is configured but pagination params are not included on the request. [#6098]
* Respect `allow_null=True` on `DecimalField`. [#7718]
* Allow title cased `"Yes"`/`"No"` values with `BooleanField`. [#7739]
* Add `PageNumberPagination.get_page_number()` method for overriding behavior. [#7652]
* Fixed rendering of timedelta values in OpenAPI schemas, when present as default, min, or max fields. [#7641]
* Render JSONFields with indentation in browsable API forms. [#6243]
* Remove unnecessary database query in admin Token views. [#7852]
* Raise validation errors when bools are passed to `PrimaryKeyRelatedField` fields, instead of casting to ints. [#7597]
* Don't include model properties as automatically generated ordering fields with `OrderingFilter`. [#7609]
* Use `deque` instead of `list` for tracking throttling `.history`. [#7849]
### 3.12.2
Date: 13th October 2020
* Fix issue if `rest_framework.authtoken.models` is imported, but `rest_framework.authtoken` is not in INSTALLED_APPS. [#7571]
* Ignore subclasses of BrowsableAPIRenderer in OpenAPI schema. [#7497]
* Narrower exception catching in serilizer fields, to ensure that any errors in broken `get_queryset()` methods are not masked. [#7480]
### 3.12.1
Date: 28th September 2020
* Add `TokenProxy` migration. [#7557]
### 3.12.0
Date: 28th September 2020
* Add `--file` option to `generateschema` command. [#7130]
* Support `tags` for OpenAPI schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#grouping-operations-with-tags). [#7184]
* Support customising the operation ID for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#operationid). [#7190]
* Support OpenAPI components for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#components). [#7124]
* The following methods on `AutoSchema` become public API: `get_path_parameters`, `get_pagination_parameters`, `get_filter_parameters`, `get_request_body`, `get_responses`, `get_serializer`, `get_paginator`, `map_serializer`, `map_field`, `map_choice_field`, `map_field_validators`, `allows_filters`. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#autoschema)
* Add support for Django 3.1's database-agnositic `JSONField`. [#7467]
* `SearchFilter` now supports nested search on `JSONField` and `HStoreField` model fields. [#7121]
* `SearchFilter` now supports searching on `annotate()` fields. [#6240]
* The authtoken model no longer exposes the `pk` in the admin URL. [#7341]
* Add `__repr__` for Request instances. [#7239]
* UTF-8 decoding with Latin-1 fallback for basic auth credentials. [#7193]
* CharField treats surrogate characters as a validation failure. [#7026]
* Don't include callables as default values in schemas. [#7105]
* Improve `ListField` schema output to include all available child information. [#7137]
* Allow `default=False` to be included for `BooleanField` schema outputs. [#7165]
* Include `"type"` information in `ChoiceField` schema outputs. [#7161]
* Include `"type": "object"` on schema objects. [#7169]
* Don't include component in schema output for DELETE requests. [#7229]
* Fix schema types for `DecimalField`. [#7254]
* Fix schema generation for `ObtainAuthToken` view. [#7211]
* Support passing `context=...` to view `.get_serializer()` methods. [#7298]
* Pass custom code to `PermissionDenied` if permission class has one set. [#7306]
* Include "example" in schema pagination output. [#7275]
* Default status code of 201 on schema output for POST requests. [#7206]
* Use camelCase for operation IDs in schema output. [#7208]
* Warn if duplicate operation IDs exist in schema output. [#7207]
* Improve handling of decimal type when mapping `ChoiceField` to a schema output. [#7264]
* Disable YAML aliases for OpenAPI schema outputs. [#7131]
* Fix action URL names for APIs included under a namespaced URL. [#7287]
* Update jQuery version from 3.4 to 3.5. [#7313]
* Fix `UniqueTogether` handling when serializer fields use `source=...`. [#7143]
* HTTP `HEAD` requests now set `self.action` correctly on a ViewSet instance. [#7223]
* Return a valid OpenAPI schema for the case where no API schema paths exist. [#7125]
* Include tests in package distribution. [#7145]
* Allow type checkers to support annotations like `ModelSerializer[Author]`. [#7385]
* Don't include invalid `charset=None` portion in the request `Content-Type` header when using APIClient. [#7400]
* Fix `\Z`/`\z` tokens in OpenAPI regexs. [#7389]
* Fix `PrimaryKeyRelatedField` and `HyperlinkedRelatedField` when source field is actually a property. [#7142]
* `Token.generate_key` is now a class method. [#7502]
* `@action` warns if method is wrapped in a decorator that does not preserve information using `@functools.wraps`. [#7098]
---
## 3.11.x series
### 3.11.2
**Date**: 30th September 2020
* **Security**: Drop `urlize_quoted_links` template tag in favour of Django's built-in `urlize`. Removes a XSS vulnerability for some kinds of content in the browsable API.
### 3.11.1
**Date**: 5th August 2020
* Fix compat with Django 3.1
### 3.11.0
**Date**: 12th December 2019
* Drop `.set_context` API [in favour of a `requires_context` marker](../3.11-announcement#validator-default-context).
* Drop `.set_context` API [in favour of a `requires_context` marker](3.11-announcement.md#validator-default-context).
* Changed default widget for TextField with choices to select box. [#6892][gh6892]
* Supported nested writes on non-relational fields, such as JSONField. [#6916][gh6916]
* Include request/response media types in OpenAPI schemas, based on configured parsers/renderers. [#6865][gh6865]
@ -102,6 +240,8 @@ You can determine your currently installed version using `pip show`:
* 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
@ -2195,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
@ -198,6 +66,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [rest_condition][rest-condition] - Another extension for building complex permissions in a simple and convenient way.
* [dry-rest-permissions][dry-rest-permissions] - Provides a simple way to define permissions for individual api actions.
* [drf-access-policy][drf-access-policy] - Declarative and flexible permissions inspired by AWS' IAM policies.
* [drf-psq][drf-psq] - An extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.
### Serializers
@ -213,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
@ -235,12 +106,13 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [djangorestframework-msgpack][djangorestframework-msgpack] - Provides MessagePack renderer and parser support.
* [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
* [djangorestframework-camel-case][djangorestframework-camel-case] - Provides camel case JSON renderers and parsers.
* [nested-multipart-parser][nested-multipart-parser] - Provides nested parser for http multipart request
### Renderers
* [djangorestframework-csv][djangorestframework-csv] - Provides CSV renderer support.
* [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
* [drf_ujson][drf_ujson] - Implements JSON rendering using the UJSON package.
* [drf_ujson2][drf_ujson2] - Implements JSON rendering using the UJSON package.
* [rest-pandas][rest-pandas] - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.
* [djangorestframework-rapidjson][djangorestframework-rapidjson] - Provides rapidjson support with parser and renderer.
@ -274,13 +146,15 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [drf-viewset-profiler][drf-viewset-profiler] - Lib to profile all methods from a viewset line by line.
* [djangorestframework-features][djangorestframework-features] - Advanced schema generation and more based on named features.
* [django-elasticsearch-dsl-drf][django-elasticsearch-dsl-drf] - Integrate Elasticsearch DSL with Django REST framework. Package provides views, serializers, filter backends, pagination and other handy add-ons.
* [django-api-client][django-api-client] - DRF client that groups the Endpoint response, for use in CBVs and FBV as if you were working with Django's Native Models..
* [fast-drf] - A model based library for making API development faster and easier.
* [django-requestlogs] - Providing middleware and other helpers for audit logging for REST framework.
* [drf-standardized-errors][drf-standardized-errors] - DRF exception handler to standardize error responses for all API endpoints.
[cite]: http://www.software-ecosystems.com/Software_Ecosystems/Ecosystems.html
[cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework
[new-repo]: https://github.com/new
[create-a-repo]: https://help.github.com/articles/create-a-repo/
[travis-ci]: https://travis-ci.org
[travis-profile]: https://travis-ci.org/profile
[pypi-register]: https://pypi.org/account/register/
[semver]: https://semver.org/
[tox-docs]: https://tox.readthedocs.io/en/latest/
@ -306,14 +180,15 @@ 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_ujson]: https://github.com/gizmag/drf-ujson-renderer
[drf_ujson2]: https://github.com/Amertz08/drf_ujson2
[rest-pandas]: https://github.com/wq/django-rest-pandas
[djangorestframework-rapidjson]: https://github.com/allisson/django-rest-framework-rapidjson
[djangorestframework-chain]: https://github.com/philipn/django-rest-framework-chain
@ -322,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
@ -358,3 +233,11 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
[drf-viewset-profiler]: https://github.com/fvlima/drf-viewset-profiler
[djangorestframework-features]: https://github.com/cloudcode-hungary/django-rest-framework-features/
[django-elasticsearch-dsl-drf]: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf
[django-api-client]: https://github.com/rhenter/django-api-client
[drf-psq]: https://github.com/drf-psq/drf-psq
[django-rest-authemail]: https://github.com/celiao/django-rest-authemail
[graphwrap]: https://github.com/PaulGilmartin/graph_wrap
[rest-framework-actions]: https://github.com/AlexisMunera98/rest-framework-actions
[fast-drf]: https://github.com/iashraful/fast-drf
[django-requestlogs]: https://github.com/Raekkeri/django-requestlogs
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors

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,18 +96,18 @@ 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
[pycon-uk-2016]: https://www.youtube.com/watch?v=FjmiGh7OqVg
[django-under-hood-2014]: https://www.youtube.com/watch?v=3cSsbe-tA0E
[integrating-pandas-drf-and-bokeh]: https://machinalis.com/blog/pandas-django-rest-framework-bokeh/
[controlling-uncertainty-on-web-apps-and-apis]: https://machinalis.com/blog/controlling-uncertainty-on-web-applications-and-apis/
[full-text-search-in-drf]: https://machinalis.com/blog/full-text-search-on-django-rest-framework/
[oauth2-authentication-with-drf]: https://machinalis.com/blog/oauth2-authentication/
[nested-resources-with-drf]: https://machinalis.com/blog/nested-resources-with-django/
[image-fields-with-drf]: https://machinalis.com/blog/image-fields-with-django-rest-framework/
[integrating-pandas-drf-and-bokeh]: https://web.archive.org/web/20180104205117/http://machinalis.com/blog/pandas-django-rest-framework-bokeh/
[controlling-uncertainty-on-web-apps-and-apis]: https://web.archive.org/web/20180104205043/https://machinalis.com/blog/controlling-uncertainty-on-web-applications-and-apis/
[full-text-search-in-drf]: https://web.archive.org/web/20180104205059/http://machinalis.com/blog/full-text-search-on-django-rest-framework/
[oauth2-authentication-with-drf]: https://web.archive.org/web/20180104205054/http://machinalis.com/blog/oauth2-authentication/
[nested-resources-with-drf]: https://web.archive.org/web/20180104205109/http://machinalis.com/blog/nested-resources-with-django/
[image-fields-with-drf]: https://web.archive.org/web/20180104205048/http://machinalis.com/blog/image-fields-with-django-rest-framework/
[chatbot-using-drf-part1]: https://chatbotslife.com/chatbot-using-django-rest-framework-api-ai-slack-part-1-3-69c7e38b7b1e#.g2aceuncf
[new-django-admin-with-drf-and-emberjs]: https://blog.levit.be/new-django-admin-with-emberjs-what-are-the-news/
[drf-schema]: https://drf-schema-adapter.readthedocs.io/en/latest/
@ -128,3 +129,4 @@ Want your Django REST Framework talk/tutorial/article to be added to our website
[anna-email]: mailto:anna@django-rest-framework.org
[pycon-us-2017]: https://www.youtube.com/watch?v=Rk6MHZdust4
[django-rest-react-valentinog]: https://www.valentinog.com/blog/tutorial-api-django-rest-react/
[doordash-implementing-rest-apis]: https://doordash.engineering/2013/10/07/implementing-rest-apis-with-embedded-privacy/

View File

@ -1,5 +1,16 @@
# Tutorial 7: Schemas & client libraries
----
**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details.
If you are looking for information regarding schemas, you might want to look at these updated resources:
1. [Schema](../api-guide/schemas.md)
2. [Documenting your API](../topics/documenting-your-api.md)
----
A schema is a machine-readable document that describes the available API
endpoints, their URLS, and what operations they support.

View File

@ -1,6 +1,17 @@
## Built-in API documentation
----
**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details.
If you are looking for information regarding schemas, you might want to look at these updated resources:
1. [Schema](../api-guide/schemas.md)
2. [Documenting your API](../topics/documenting-your-api.md)
----
The built-in API documentation includes:
* Documentation of API endpoints.
@ -19,7 +30,7 @@ To install the API documentation, you'll need to include it in your project's UR
urlpatterns = [
...
url(r'^docs/', include_docs_urls(title='My API title'))
path('docs/', include_docs_urls(title='My API title'))
]
This will include two different views:
@ -41,7 +52,7 @@ You may ensure views are given a `request` instance by calling `include_docs_url
urlpatterns = [
...
# Generate schema with valid `request` instance:
url(r'^docs/', include_docs_urls(title='My API title', public=False))
path('docs/', include_docs_urls(title='My API title', public=False))
]

View File

@ -1,8 +1,8 @@
# Legacy CoreAPI Schemas Docs
Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation in Django REST Framework v3.10.
Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10.
See the [Version 3.10 Release Announcement](/community/3.10-announcement.md) for more details.
See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details.
----

View File

@ -2,6 +2,14 @@ source: schemas.py
# Schemas
----
**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details.
You are probably looking for [this page](../api-guide/schemas.md) if you want latest information regarding schemas.
----
> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.
>
> &mdash; Heroku, [JSON Schema for the Heroku Platform API][cite]
@ -43,11 +51,12 @@ 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 = [
url('^schema$', schema_view),
path('schema', schema_view),
...
]
```
@ -292,7 +301,7 @@ The simplest way to include a schema in your project is to use the
schema_view = get_schema_view(title="Server Monitoring API")
urlpatterns = [
url('^$', schema_view),
path('', schema_view),
...
]
@ -358,7 +367,7 @@ List of url patterns to limit the schema introspection to. If you only want the
to be exposed in the schema:
schema_url_patterns = [
url(r'^api/', include('myproject.api.urls')),
path('api/', include('myproject.api.urls')),
]
schema_view = get_schema_view(
@ -411,7 +420,7 @@ return the schema.
**urls.py:**
urlpatterns = [
url('/', schema_view),
path('', schema_view),
...
]
@ -827,10 +836,17 @@ A short description of the meaning and intended usage of the input field.
[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/

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)
* Django (2.2, 3.0)
* Python (3.6, 3.7, 3.8, 3.9, 3.10)
* Django (2.2, 3.0, 3.1, 3.2, 4.0, 4.1)
We **highly recommend** and only officially support the latest patch release of
each Python and Django series.
@ -120,7 +122,7 @@ If you're intending to use the browsable API you'll probably also want to add RE
urlpatterns = [
...
url(r'^api-auth/', include('rest_framework.urls'))
path('api-auth/', include('rest_framework.urls'))
]
Note that the URL path can be whatever you want.
@ -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

@ -384,7 +384,7 @@ First, install the API documentation views. These will include the schema resour
urlpatterns = [
...
url(r'^docs/', include_docs_urls(title='My API service'), name='api-docs'),
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.
@ -453,7 +453,7 @@ For example, using the "Django REST framework JWT" package
function loginUser(username, password) {
let action = ["api-token-auth", "obtain-token"];
let params = {username: "example", email: "example@example.com"};
let params = {username: username, password: password};
client.action(schema, action, params).then(function(result) {
// On success, instantiate an authenticated client.
let auth = window.coreapi.auth.TokenAuthentication({

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

@ -142,6 +142,16 @@ This also translates into a very useful interactive documentation viewer in the
![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
@ -192,7 +202,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.
@ -209,13 +219,14 @@ To implement a hypermedia API you'll need to decide on an appropriate media type
[cite]: https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
[hypermedia-docs]: rest-hypermedia-hateoas.md
[metadata-docs]: ../api-guide/metadata/
[schemas-examples]: ../api-guide/schemas/#examples
[metadata-docs]: ../api-guide/metadata.md
[schemas-examples]: ../api-guide/schemas.md#examples
[image-drf-yasg]: ../img/drf-yasg.png
[image-self-describing-api]: ../img/self-describing.png
[drf-yasg]: https://github.com/axnsan12/drf-yasg/
[drf-spectacular]: https://github.com/tfranzel/drf-spectacular/
[markdown]: https://daringfireball.net/projects/markdown/syntax
[open-api]: https://openapis.org/
[redoc]: https://github.com/Rebilly/ReDoc

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

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

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

@ -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.
@ -137,7 +137,7 @@ We can add a login view for use with the browsable API, by editing the URLconf i
Add the following import at the top of the file:
from django.conf.urls import include
from django.urls import path, include
And, at the end of the file, add a pattern to include the login and logout views for the browsable API.

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

@ -2,7 +2,7 @@
REST framework includes an abstraction for dealing with `ViewSets`, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.
`ViewSet` classes are almost the same thing as `View` classes, except that they provide operations such as `read`, or `update`, and not method handlers such as `get` or `put`.
`ViewSet` classes are almost the same thing as `View` classes, except that they provide operations such as `retrieve`, or `update`, and not method handlers such as `get` or `put`.
A `ViewSet` class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a `Router` class which handles the complexities of defining the URL conf for you.
@ -16,7 +16,7 @@ First of all let's refactor our `UserList` and `UserDetail` views into a single
class UserViewSet(viewsets.ReadOnlyModelViewSet):
"""
This viewset automatically provides `list` and `detail` actions.
This viewset automatically provides `list` and `retrieve` actions.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
@ -27,6 +27,7 @@ Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import permissions
class SnippetViewSet(viewsets.ModelViewSet):
"""
@ -111,8 +112,8 @@ Here's our re-wired `snippets/urls.py` file.
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet)
router.register(r'users', views.UserViewSet)
router.register(r'snippets', views.SnippetViewSet, basename='snippet')
router.register(r'users', views.UserViewSet, basename='user')
# The API URLs are now determined automatically by the router.
urlpatterns = [

View File

@ -42,6 +42,7 @@ The project layout should look like:
./tutorial/quickstart/models.py
./tutorial/quickstart/tests.py
./tutorial/quickstart/views.py
./tutorial/asgi.py
./tutorial/settings.py
./tutorial/urls.py
./tutorial/wsgi.py
@ -176,12 +177,6 @@ We can now access our API, both from the command-line, using tools like `curl`..
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin"
},
{
"email": "tom@example.com",
"groups": [],
"url": "http://127.0.0.1:8000/users/2/",
"username": "tom"
}
]
}
@ -202,12 +197,6 @@ Or using the [httpie][httpie], command line tool...
"url": "http://localhost:8000/users/1/",
"username": "paul"
},
{
"email": "tom@example.com",
"groups": [],
"url": "http://127.0.0.1:8000/users/2/",
"username": "tom"
}
]
}
@ -225,4 +214,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

@ -66,6 +66,9 @@ 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'
- '3.9 Announcement': 'community/3.9-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.7.9
flake8-tidy-imports==4.1.0
pycodestyle==2.5.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,9 @@
# 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
markdown==3.3
psycopg2-binary>=2.8.5,<2.9
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.1,<7.0
pytest-cov>=2.10.1,<3.0
pytest-django>=4.1.0,<5.0
importlib-metadata<5.0

View File

@ -7,8 +7,10 @@ ______ _____ _____ _____ __
\_| \_\____/\____/ \_/ |_| |_| \__,_|_| |_| |_|\___| \_/\_/ \___/|_| |_|\_|
"""
import django
__title__ = 'Django REST framework'
__version__ = '3.11.0'
__version__ = '3.14.0'
__author__ = 'Tom Christie'
__license__ = 'BSD 3-Clause'
__copyright__ = 'Copyright 2011-2019 Encode OSS Ltd'
@ -22,12 +24,10 @@ HTTP_HEADER_ENCODING = 'iso-8859-1'
# Default datetime input and output formats
ISO_8601 = 'iso-8601'
default_app_config = 'rest_framework.apps.RestFrameworkConfig'
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

@ -136,7 +136,10 @@ class SessionAuthentication(BaseAuthentication):
"""
Enforce CSRF validation for session based authentication.
"""
check = CSRFCheck()
def dummy_get_response(request): # pragma: no cover
return None
check = CSRFCheck(dummy_get_response)
# populates request.META['CSRF_COOKIE'], which is used in process_view()
check.process_request(request)
reason = check.process_view(request, None, (), {})
@ -224,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

@ -1 +1,4 @@
default_app_config = 'rest_framework.authtoken.apps.AuthTokenConfig'
import django
if django.VERSION < (3, 2):
default_app_config = 'rest_framework.authtoken.apps.AuthTokenConfig'

View File

@ -0,0 +1,25 @@
# Generated by Django 3.1.1 on 2020-09-28 09:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('authtoken', '0002_auto_20160226_1747'),
]
operations = [
migrations.CreateModel(
name='TokenProxy',
fields=[
],
options={
'verbose_name': 'token',
'proxy': True,
'indexes': [],
'constraints': [],
},
bases=('authtoken.token',),
),
]

View File

@ -32,7 +32,8 @@ class Token(models.Model):
self.key = self.generate_key()
return super().save(*args, **kwargs)
def generate_key(self):
@classmethod
def generate_key(cls):
return binascii.hexlify(os.urandom(20)).decode()
def __str__(self):
@ -45,8 +46,9 @@ class TokenProxy(Token):
"""
@property
def pk(self):
return self.user.pk
return self.user_id
class Meta:
proxy = True
proxy = 'rest_framework.authtoken' in settings.INSTALLED_APPS
abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS
verbose_name = "token"

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,4 +1,4 @@
from django.conf.urls import include, url
from django.urls import include, path
from rest_framework.renderers import (
CoreJSONRenderer, DocumentationRenderer, SchemaJSRenderer
@ -82,7 +82,7 @@ def include_docs_urls(
permission_classes=permission_classes,
)
urls = [
url(r'^$', docs_view, name='docs-index'),
url(r'^schema.js$', schema_js_view, name='schema-js')
path('', docs_view, name='docs-index'),
path('schema.js', schema_js_view, name='schema-js')
]
return include((urls, 'api-docs'), namespace='api-docs')

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,14 +72,19 @@ class ErrorDetail(str):
return self
def __eq__(self, other):
r = super().__eq__(other)
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)' % (
@ -148,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 "
"`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):
@ -1046,6 +997,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,6 +1068,12 @@ 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())
@ -1152,21 +1114,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 +1141,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 +1157,14 @@ class DateTimeField(Field):
return self.enforce_timezone(value)
for input_format in input_formats:
if input_format.lower() == ISO_8601:
try:
with contextlib.suppress(ValueError, TypeError):
if input_format.lower() == ISO_8601:
parsed = parse_datetime(value)
if parsed is not None:
return self.enforce_timezone(parsed)
except (ValueError, TypeError):
pass
else:
try:
parsed = self.datetime_parser(value, input_format)
return self.enforce_timezone(parsed)
except (ValueError, TypeError):
pass
parsed = self.datetime_parser(value, input_format)
return self.enforce_timezone(parsed)
humanized_format = humanize_datetime.datetime_formats(input_formats)
self.fail('invalid', format=humanized_format)
@ -1238,12 +1195,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 +1261,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)
@ -1459,9 +1416,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 +1437,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 +1477,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 +1526,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 +1543,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 +1565,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 +1577,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 +1642,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 +1652,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 +1701,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,10 +1714,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)
super().__init__(*args, **kwargs)
self.decoder = kwargs.pop('decoder', None)
super().__init__(**kwargs)
def get_value(self, dictionary):
if html.is_html_input(dictionary) and self.field_name in dictionary:
@ -1777,7 +1740,7 @@ class JSONField(Field):
if self.binary or getattr(data, 'is_json_string', False):
if isinstance(data, bytes):
data = data.decode()
return json.loads(data)
return json.loads(data, cls=self.decoder)
else:
json.dumps(data, cls=self.encoder)
except (TypeError, ValueError):
@ -1845,7 +1808,7 @@ class SerializerMethodField(Field):
For example:
class ExampleSerializer(self):
class ExampleSerializer(Serializer):
extra_info = SerializerMethodField()
def get_extra_info(self, obj):

View File

@ -226,10 +226,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