Compare commits

...

449 Commits

Author SHA1 Message Date
Ülgen Sarıkavak
ea1da76196
Add pyupgrade to pre-commit hooks (#9682) 2025-04-09 06:24:18 +00:00
Yousef Abu Shanab
2fbfaae507
Add drf-restwind and update outdated images in browsable-api.md (#9680)
* add drf-restwind

* Add images of 3rd party customization packages
2025-04-08 08:32:04 +00:00
Bruno Alla
3c755794df
Cleanup dependencies and conditions for unsupported Python versions (#9681)
* Remove optional install backports.zoneinfo for unsupported Python versions and associated code

* Remove conditions in tests for unsupported Python versions

* Remove condition for unsupported Python versions
2025-04-08 08:29:40 +00:00
ren000thomas
c41314f1fc
Update Chinese translations (#9675) 2025-04-05 11:02:59 +01:00
JAEGYUN JUNG
5c21fa757c
Update test matrix to use Django 5.2 stable version (#9679) 2025-04-04 11:39:11 +01:00
Stefan
141ab8e585
Add missing & fix German translations (#9676) 2025-04-04 09:24:28 +01:00
JAEGYUN JUNG
3ba8ef967e
Update GitHub Actions to use Ubuntu 22.04 for testing (#9677) 2025-04-02 18:35:29 +01:00
JAEGYUN JUNG
9b1e8d2d43
Add missing & fix Korean translations (#9571)
* update django.po file

* update django.po translators

* Changed the translation for the word “User” from “유저” to “사용자” to make it consistent with Django's translation

reference: 5a91ad3d71/django/contrib/admin/locale/ko/LC_MESSAGES/django.po (L601)

* Add missing translation for the word “Token"

* Fix wrong translation for word "Created"

* Fix translation for "Tokens", just like django translation.

reference: 5a91ad3d71/django/contrib/auth/locale/ko/LC_MESSAGES/django.po (L235)

* Add missing translation for "Invalid Input"

* Add missing translation for throttling messages

* Add missing translation for CharField, BooleanField messages

* fix: remove unnecessary space

* Feat: add missing translation for SlugField error message

* Feat: add missing translation for UUIDField error message

* Fix: add (boolean) for booleanField message

* Feat: add missing translation for `integer to float` error message

* Feat: add & fix translation for DecimalField

* Feat: add & fix translation for DateTimeField

* Feat: add & fix translation for DurationField

* Feat: add & fix translation for Selection&FilePathField

* Feat: add & fix translation for DictField

* Feat: add missing translation for filters

* Feat: add missing translations for template

* Feat: Change end punctuation to the “~세요.” used by Django translations

* update django.po translators

* Feat: add compiled message file

* Update rest_framework/locale/ko_KR/LC_MESSAGES/django.po

Co-authored-by: taezero <51291185+overtae@users.noreply.github.com>

* Update rest_framework/locale/ko_KR/LC_MESSAGES/django.po

Co-authored-by: taezero <51291185+overtae@users.noreply.github.com>

* Feat: remove unnecessary multliline from django.po(kor translation)

* Feat: remove unnecessary multliline from django.po(kor translation)

* Feat: update Korean translations for authentication messages

* Feat: Remove unnecessary English parenthesis descriptions

* Feat: Remove unnecessary English parenthesis descriptions

* Feat: Remove unnecessary English parenthesis descriptions

* Feat: Update compiled message file for ko_KR

---------

Co-authored-by: taezero <51291185+overtae@users.noreply.github.com>
2025-04-02 18:17:04 +01:00
Michiel W. Beijen
ffadde930e
Removed reference to GitHub Issues and Discussions (#9660) 2025-03-31 15:22:15 +01:00
Matheus Oliveira
6f274ab862
Fix some typos in pt_BR translations (#9673) 2025-03-31 10:43:53 +01:00
Bruno Alla
ac50cec76c
Prepare v3.16, release notes, and announcement. (#9671)
* Start drafting release notes from 3.16 (Generated from GitHub)
* Reformat changes and split into sections
* Format GitHub PRs links for the docs
* Link new contributors in Markdown format
* Write up 3.16 announcement
* Bump version
* Add entry for removed Python 3.8 support
* Update release date to 28/03

* Minor rewording

* Add 3.16 announcement to the navbar and link to docs
2025-03-28 15:16:33 +01:00
Carlton Gibson
e96b8e49cd
Drop Python 3.8 as EOL (#9670)
Thanks to Bruno Alla for review.

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2025-03-28 13:56:54 +01:00
Paul FLORENCE
32dbd3525d
Add django-pyoidc as a third party authentication library (#9667) 2025-03-25 20:09:42 +00:00
Mike Manger
73cbb9cd4a
Fix typos (#9662)
* Fix typo of 'related' in tests

* Fix typo of permission_classes in coreapi test

* Fix some minor typos in docs

* Fix typos in tests

* Fix flake8 issue
2025-03-08 15:53:15 +06:00
Mike Manger
1e8ac7c23b
Update usage of open in setup.py (#9661) 2025-03-06 13:30:27 +00:00
Asif Saif Uddin
0e1c7d3613
Update django 5.2b1 (#9657) 2025-02-27 11:27:32 +00:00
Mojtaba A
fc98d3598d
Update relations.md (#9063)
add rest-framework-gm2m-relations package that provides read/write serialization for generic many to many field
2025-02-26 06:11:09 +00:00
Konstantin Alekseev
17e95604f5
Fix unique together validator doesn't respect condition's fields (#9360) 2025-02-17 14:01:32 +06:00
Asif Saif Uddin
f30c0e2eed
add django 5.2a1 initial support (#9634)
* add django 5.2a1 for initial testing

* declare django 5.2 support

* change in docs
2025-02-14 14:49:56 +06:00
Bruno Alla
28d0261afc
Add missing ignore_outcome=true for the Python 3.13 - Django main combination (#9637) 2025-02-01 12:24:43 +06:00
decadenza
8637b3d624
Improved description of allowed throttling rates (#9640) 2025-01-30 10:03:11 +00:00
Bruno Alla
038670a4cf
Drop deprecated AutoSchema._get_reference method (#9525)
As well the unused RemovedInDRF316Warning
2025-01-29 12:27:33 +06:00
exg1o
f8dbea1a45
Add note in 'Introspecting ViewSet actions' docs section (#9633)
* Fix `Introspecting ViewSet actions` docs section

* Update docs/api-guide/viewsets.md

---------

Co-authored-by: Bruno Alla <browniebroke@users.noreply.github.com>
2025-01-29 11:51:38 +06:00
Bruno Alla
e1c070aacc
Switch to codecov GHA (#9618)
Fix #7908
2025-01-29 11:50:08 +06:00
Tom Christie
78e0b84ac9
Update SECURITY.md (#9628)
* Update security contact
2025-01-21 15:00:02 +00:00
Deepak Angadi
b483179b93
Update strftime formats link in the documentation (#9624) 2025-01-17 12:32:29 +00:00
Oliver Sauder
4a1d773b8f
Fixed regression that tests using format still work (#9615)
* Fixed regression that tests using format still work

Error only occurred on tests which return no content and use
a renderer without charset (e.g. JSONRenderer)

* Fixed linting

* Used early return as before

* Move ret str check back to where it was
2025-01-11 00:56:36 +06:00
Julius Lange
a4f6059d50
Fix typo in renderers documentation (#9616)
It's called lUAlatex and not lAUlatex.
2025-01-07 19:19:39 +00:00
Terence Honles
089f6a6974
support django 2.1 test client json data automatically serialized (#6511) 2024-12-28 16:22:21 +06:00
Bruno Alla
a8595a8eae
Fix raising on nullable fields part of UniqueConstraint (#9531)
* Add test to reproduce problem with nullable fields part of a unique constraint

Ref #9378

* Simplify test case and add similar case for unique_together

* Add test for unique together in a better place

* Default nullable fields to null in unique constraints checks

* Remove redundant test and move other to more appropriate place
2024-12-14 15:08:22 +06:00
amansharma612
dbac145638
Removed extra <> in validators example (#9590)
Co-authored-by: Aman Sharma <210100011@iitb.ac.in>
2024-11-18 17:43:53 +06:00
Will Vincent
b31413d46d
Tutorial updates (#9589)
* update Django for APIs book cover

* remove retired course from Treehouse

* add DCUS2018 talk, update links from wsvincent.com tutorials to learndjango.com
2024-11-12 06:58:56 +01:00
chee hong
9016efe3fc
Fix docs typo in Serializers Validators (#9563) 2024-10-23 20:09:36 +06:00
Gabriel
d3dd45b3f4
Update 1-serialization.md (#9543)
Making explicit the http GET method of the httpie calls.
For some reason it is sending a POST instead of a GET request as it should be described here:
https://httpie.io/docs/cli/optional-get-and-post

Note:
I was following the docs and testing it within the Git Bash windows console app for making the requests and debugging the DRF projenct in pycharm.
2024-10-10 04:41:39 +06:00
Oliver Sauder
10b25e7d63
Use final version of Python 3.13 (#9556)
Final version of Python 3.13 has been released and is now also available on GitHub actions.
2024-10-10 04:39:36 +06:00
Gabriel Mitelman Tkacz
81613c0e51
Fixing and adding pt-br translations (#9535) 2024-09-20 11:34:37 +01:00
Peter Thomassen
9921c7554f
Fix Transifex link (#9541) 2024-09-19 14:11:31 +02:00
Bruno Alla
b25028ac8f
Add support for Python 3.13 (#9527)
* Add support for Python 3.13

* Fix extracting tox env with -dev Python versions

* Fix view description inspection in Python 3.13

Python 3.13 introduced docstrings for None: https://github.com/python/cpython/pull/117813

In Python 3.12, this is an empty string:

```
 ➜ python3.12
Python 3.12.6 (main, Sep 10 2024, 19:06:17) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> d = None
>>> d.__doc__
>>>
```

In Python 3.13, it's no longer empty:

```
 ➜ python3.13
Python 3.13.0rc2+ (heads/3.13:660baa1, Sep 10 2024, 18:57:50) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> d = None
>>> d.__doc__
'The type of the None singleton.'
>>>
```

Adding a check in the inspector that get the view description out the view function docstring to catch this edge case.
2024-09-11 15:39:52 +06:00
Bruno Alla
a59aa2dfe1
Add test covering Update view without queryset attribute (#9528) 2024-09-11 15:37:33 +06:00
Bruno Alla
61e33761eb
Docs: move path converter into a separate section (#9524)
And remove note regarding only working with Django 2.x or above, as it's been a while the feature is present, and DRF only supports Django 4.2+.

I was looking for this but couldn't see it in the docs, having it in a separate section would make it easier to find and link to.

Moreover, as it stands, one might think that the feature is limited to SimpleRouter, while it's also available for DefaultRouter.
2024-09-10 17:29:31 +06:00
Sina Amini
7141bdb2df
Spelling mistakes in Farsi language were corrected (#9521) 2024-09-07 17:30:13 +06:00
Bruno Alla
2ede857de0
Add official support for Django 5.1 (#9514)
* Add official support for Django 5.1

Following the supported Python versions:

https://docs.djangoproject.com/en/stable/faq/install/

* Add tests to cover compat with Django's 5.1 LoginRequiredMiddleware

* First pass to create DRF's LoginRequiredMiddleware

* Attempt to fix the tests

* Revert custom middleware implementation

* Disable LoginRequiredMiddleware on DRF views

* Document how to integrate DRF with LoginRequiredMiddleware

* Move login required tests under a separate test case

* Revert redundant change

* Disable LoginRequiredMiddleware on ViewSets

* Add some integrations tests to cover various view types
2024-09-07 17:21:18 +06:00
Bruno Alla
125ad42eb3
Accept integers as min/max values of DecimalField (#9515)
* Use Decimal for min/max values of DecimalField in tests

* Update docs to mention that min/max values should be Decimal objects

* Accept integer values for DecimalField min and max values

* Update expected error messages in tests

* Update expected warning message in tests
2024-09-07 17:07:28 +06:00
rafaelgramoschi
f593f5752c
Update browsable-api.md (#9509)
* Update browsable-api.md

Deprecated url(), use re_path(). Show imports.

* Update docs/topics/browsable-api.md

* Update docs/topics/browsable-api.md

---------

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2024-08-27 13:44:04 +06:00
Noam
5cc1028c2f
Fix "Converter is already registered" deprecation warning. (#9512) 2024-08-26 17:32:50 +02:00
akkuman
f6ea019bd9
Update django.po (#9505) 2024-08-26 10:31:07 +01:00
Pedro Schlickmann Mendes
2f28e7086d
Update jobs.md (#9480) 2024-08-26 10:28:15 +01:00
Dave Kalu
f113ab6b68
Update tutorials-and-resources.md (#9479)
Included the remaining parts (part 3 and 4) of Andrea Grandi's tutorial on creating production ready APIs with DRF.
2024-08-05 14:26:41 +01:00
Yuekui
518eb22e67
Fix unique_together validation with source (#9482) 2024-08-05 16:36:50 +06:00
James McHugh
8e304e1adb
Fixed AttributeError raised by data property being silently ignored (#9455)
Signed-off-by: James Riley McHugh <mchugh_james@bah.com>
Co-authored-by: James Riley McHugh <mchugh_james@bah.com>
2024-07-17 22:51:39 +06:00
Andrea Grandi
b6ea11028f
Update tutorials-and-resources.md (#9476) 2024-07-17 22:50:09 +06:00
Devid
f74185b6dd
Fix get_template_context to handle also lists (#9467) 2024-07-15 22:03:40 +06:00
Tom Christie
ccfe0a9637
Add Zuplo to sponsors (#9460) 2024-07-05 16:56:58 +01:00
Alvaro Vega
e9f3fd250a
Update release-notes.md (#9451) 2024-06-29 13:48:31 +06:00
Francesco Cataldo
4d0662663a
fix(release-notes): fix wronk link PR(#9435) on release-notes 3.15.2 (#9444)
Co-authored-by: Francesco <francesco.cataldo@spinforward.it>
2024-06-27 13:19:59 +01:00
Martijn Jacobs
7297f19701
Add adrf as a third party package for Django REST framework (#9198) 2024-06-24 10:31:49 +01:00
Devid
e13688f0c0
Remove long deprecated code from request wrapper (#9441) 2024-06-19 00:03:37 +06:00
Ivan Studinsky
1e9b5c15ec
Provide tests for hashing of OperandHolder (#9437) 2024-06-15 14:00:28 +06:00
Tom Christie
c7a7eae551
Version 3.15.2 (#9439) 2024-06-14 16:34:21 +01:00
Seokchan Yoon
3b41f01241
Fix potential XSS vulnerability in break_long_headers template filter (#9435)
The header input is now properly escaped before splitting and joining with <br> tags. This prevents potential XSS attacks if the header contains unsanitized user input.
2024-06-14 10:52:02 +01:00
Ivan Studinsky
fe92f0dd0d
Add __hash__ method for permissions.OperandHolder class (#9417)
`OperandHolder` is not hashable, so need to add `__hash__` method
2024-06-10 12:19:06 +06:00
wkwkhautbois
fbdab09c77
docs: Correct some evaluation results and a httpie option in Tutorial1 (#9421)
* Tutorial 1: Added --unsorted option to httpie calls to prevent automatic json key sorting

* Tutorial 1: Changed evaluation results accurate
2024-06-02 10:14:37 +06:00
Stanislav Levin
36d5c0e74f
tests: Check urlpatterns after cleanups (#9400)
According to docs:
https://docs.python.org/3/library/unittest.html#unittest.TestCase.addClassCleanup

> Add a function to be called after tearDownClass() to cleanup resources
  used during the test class. Functions will be called in reverse order to
  the order they are added (LIFO).

This was revealed with recent change in pytest (`8.2.0`):
> pytest-dev/pytest#11728: For unittest-based tests, exceptions during
  class cleanup (as raised by functions registered with
  TestCase.addClassCleanup) are now reported instead of silently failing.

`check_urlpatterns` is called before `cleanup_url_patterns` and fails
(problem was hidden by `pytest < 8.2.0`).

`doClassCleanups` can be used instead to check after-cleanup state:

https://docs.python.org/3/library/unittest.html#unittest.TestCase.doClassCleanups

> This method is called unconditionally after tearDownClass(), or after
  setUpClass() if setUpClass() raises an exception.

  It is responsible for calling all the cleanup functions added by
  addClassCleanup(). If you need cleanup functions to be called prior to
  tearDownClass() then you can call doClassCleanups() yourself.

Fixes: https://github.com/encode/django-rest-framework/issues/9399

Signed-off-by: Stanislav Levin <slev@altlinux.org>
2024-05-07 13:05:03 +06:00
Peter Thomassen
9d4ed054bf
Don't use Windows line endings 2024-04-30 18:28:27 +02:00
Peter Thomassen
b34bde47d7
Fix typo in setup.cfg setting 2024-04-30 18:28:26 +02:00
Peter Thomassen
ab681f2d5e
Update requirements in docs 2024-04-30 18:28:25 +02:00
Peter Thomassen
22377241a8
bump pygments (security hygiene)
Addresses https://github.com/encode/django-rest-framework/security/dependabot/9
2024-04-30 18:28:24 +02:00
Peter Thomassen
d58b8da591
Update deprecation hints 2024-04-30 18:28:23 +02:00
Peter Thomassen
d38aab39e4
Remove unused code 2024-04-30 18:28:22 +02:00
Peter Thomassen
82d91a85ff
Fix tox config 2024-04-30 18:28:21 +02:00
Peter Thomassen
1f2daaf53c
Drop support for Django < 4.2 and Python < 3.8
Discussion: https://github.com/encode/django-rest-framework/discussions/8814#discussioncomment-9237791
2024-04-30 18:28:19 +02:00
Peter Thomassen
91bbac1f67
bump mkdocs, no longer need to pin jinja2
Addresses https://github.com/encode/django-rest-framework/security/dependabot/11
2024-04-30 18:28:04 +02:00
Peter Thomassen
7900778fbe
Remove obsolete sentence from docs 2024-04-30 18:24:23 +02:00
Peter Thomassen
861b7ac42b
Adapt issue/PR template to better reflect contribution policy 2024-04-30 18:24:22 +02:00
Peter Thomassen
52bfe20dec
Adapt docs to reflect stability-focused contribution policy 2024-04-30 18:24:21 +02:00
Peter Thomassen
f642d85be2
Fix docs typo 2024-04-30 18:24:20 +02:00
Peter Thomassen
430de731e7
Clean up project management docs 2024-04-30 18:24:19 +02:00
Terence Honles
e596f43c4e
use warnings rather than logging a warning for DecimalField warnings (#9367) 2024-04-27 17:15:06 +06:00
Max Muoto
7f18ec1b53
Revert "Ensure CursorPagination respects nulls in the ordering field (#8912)" (#9381)
This reverts commit b1cec517ff.
2024-04-27 17:07:05 +06:00
Tom Christie
f96c065607
Update README.md (#9375)
Drop unnecessary self-serving promo text. (blergh) 😅
2024-04-27 16:58:44 +06:00
Jakub Szaredko
97c5617edc
Docs: Add Python 3.12 to the requirements (#9382) 2024-04-27 16:57:48 +06:00
Christian Bläul
f4daa98f48
Remove an unnecessary step from quickstart.md (#9387)
Since django is a dependency of djangorestframework, we don’t need to install it manually.
2024-04-26 13:18:16 +01:00
JAEGYUN JUNG
9864c47018
Removing live examples of tutorial code that are no longer hosted (#9363)
* docs: Removing live examples of tutorial code that are no longer hosted

* docs: Remove all references to tutorial links
2024-04-08 13:26:02 +02:00
Marcelo Galigniana
63063da082
Update renderers documentation example (#9362) 2024-04-04 10:12:19 +03:00
John-Anthony G. Thevos
085b7e166b
Apply black formatting to caching markdown (#9341)
It _looks_ like blacken-docs is failing on this file.
Running black locally fails with a failed to reformat.
This is because it expects python code, and  when it
hits the ">", there's invalid python.
2024-03-27 10:39:49 +00:00
John-Anthony G. Thevos
f4194c4684
Update docstring (#9340) 2024-03-22 19:37:20 +00:00
Bradley Wells
6df509863d
Add @api_view example to caching documentation (#9131) 2024-03-22 18:33:00 +00:00
Tom Christie
328591693d
Version 3.15.1 (#9339)
* Version 3.15.1
2024-03-22 11:47:50 +00:00
Tom Christie
eb361d289d
SearchFilter.get_search_terms returns list. (#9338) 2024-03-22 10:52:43 +00:00
Asif Saif Uddin
400b4c5441
Revert "Fix NamespaceVersioning ignoring DEFAULT_VERSION on non-None namespac…" (#9335)
This reverts commit 71f87a5864.
2024-03-22 09:39:30 +00:00
Tom Christie
4ef3aaf0ad
Revert #9030 (#9333)
* Revert #9030

* Fix test case
2024-03-22 09:40:34 +01:00
Tom Christie
4f10c4e43e
Revert "Fix Respect can_read_model permission in DjangoModelPermissions (#8…" (#9332)
This reverts commit 0618fa88e1.
2024-03-21 22:45:12 +00:00
Tom Christie
a4d58077a0
Revert "feat: Add some changes to ValidationError to support django style vad…" (#9330)
This reverts commit 4abfa28e08.
2024-03-21 22:26:50 +00:00
Asif Saif Uddin
da78a147f2
Revert "Re-prefetch related objects after updating (#8043)" (#9327)
This reverts commit 2b34aa4291.
2024-03-21 22:23:30 +00:00
Asif Saif Uddin
0e4ed81627
Revert "feat: Add some changes to ValidationError to support django style vad…" (#9326)
This reverts commit 4abfa28e08.

Co-authored-by: Tom Christie <tom@tomchristie.com>
2024-03-21 17:09:43 +01:00
Aristotelis Mikropoulos
56a5b354d0
Add drf-sendables to third-party-packages.md (#9261) 2024-03-21 14:10:10 +00:00
Alex Laird
d7c8dcfc7e
Revert PR that adds autocomplete_fields to TokenAdmin, as this break some use cases. (#9301) 2024-03-21 12:46:06 +00:00
Bruno Alla
77ef27f18f
Fix broken links in release notes for 3.15 (#9305)
* Fix broken links in release notes for 3.15

A few links aren't rendered properly in the docs, seems to be due to extra spaces.

* Remove duplicate mention of PR number
2024-03-19 08:24:55 +01:00
Bruno Alla
2f66c294e3
Make inflection package truly optional (#9303)
* Make inflection package truly optional

Fix #9291

* Make inflection compat layer consistent with the others

Co-authored-by: T. Franzel <13507857+tfranzel@users.noreply.github.com>

---------

Co-authored-by: T. Franzel <13507857+tfranzel@users.noreply.github.com>
2024-03-18 23:29:02 +01:00
Nguyễn Anh Bình
337ba211e8
- Update the message to be consistent with the Django HttpResponseBase class. (#9287) 2024-03-17 14:22:03 +01:00
Tom Christie
2d8e9ad819
3.15 Release (#9210)
* Release Notes for 3.15

- Add docs/community/3.15-announcement.md
- Update docs/community/release-notes.md
- Update mkdocs.yml

Co-authored-by: Bruno Alla <browniebroke@users.noreply.github.com>

* Release date pending

bump

* Changes to docs should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to docs should not be included in release notes.

* Fix typo

* Changes to tests should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to tests should not be included in release notes.

* Changes to tests should not be included in release notes.

* Fix typo in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to tests should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Improve changelog entry

* Changes to docs should not be included in release notes.

* Changes to docs should not be included in release notes.

* Changes to project workflow should not be included in release notes.

* Changes to docs should not be included in release notes.

* Update docs/community/3.15-announcement.md

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>

* Update docs/community/3.15-announcement.md

* Update docs/community/3.15-announcement.md

* Update docs/community/release-notes.md

* Update docs/community/release-notes.md

Co-authored-by: Christian Clauss <cclauss@me.com>

* Update docs/community/release-notes.md

Co-authored-by: Christian Clauss <cclauss@me.com>

* Update docs/community/3.15-announcement.md

Co-authored-by: JAEGYUN JUNG <twicegoddessana1229@gmail.com>

* Update docs/community/release-notes.md

* Update docs/community/release-notes.md

Co-authored-by: JAEGYUN JUNG <twicegoddessana1229@gmail.com>

* Update release version

* Update supported Python and Django versions

---------

Co-authored-by: Rodrigo <rodrigo@crowdbotics.com>
Co-authored-by: Bruno Alla <browniebroke@users.noreply.github.com>
Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
Co-authored-by: Christian Clauss <cclauss@me.com>
Co-authored-by: JAEGYUN JUNG <twicegoddessana1229@gmail.com>
2024-03-16 17:21:02 +00:00
Asif Saif Uddin
a677b09729
Revert "Fix validation for ListSerializer (#8979)" (#9283)
This reverts commit e2a4559c03.
2024-03-13 15:15:43 +00:00
TAKAHASHI Shuuji
09a0c551ca
Revert "Register Django urls (#8778)" (#9254)
This reverts commit 3bf611787a.
2024-03-10 12:50:53 +01:00
JAEGYUN JUNG
730d216794
fix: Remove the _delegate_text attribute, which is being removed in django 5.0 (#9278) 2024-03-08 13:14:27 +00:00
şuayip üzülmez
a2eabfc867
Improve integration with Django Debug Toolbar (#9213) 2024-03-07 10:58:59 +01:00
dependabot[bot]
4c7c693f15
Bump the github-actions group with 1 update (#9272)
Bumps the github-actions group with 1 update: [actions/checkout](https://github.com/actions/checkout).


Updates `actions/checkout` from 3 to 4
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-06 16:06:24 +01:00
Christian Clauss
b7cccff943
Keep GitHub Actions up to date with GitHub's Dependabot (#9237)
* https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot
* https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem
2024-03-06 15:41:19 +01:00
Christian Clauss
6cbd4b7789
GitHub Actions: Upgrade pre-commit and drop the removed token (#9267)
* https://github.com/pre-commit/action/releases
* https://github.com/actions/checkout/releases
* https://github.com/actions/setup-python/releases

https://github.com/pre-commit/action#using-this-action-in-private-repositories explains why `token` was removed but is a bit difficult to understand.

Moving to running pre-commit on https://pre-commit.ci has proved to be the best solution on other projects.
2024-03-06 14:27:46 +01:00
Yaroslav Halchenko
fb03dd977e
Add codespell: config + workflow to detect new typos. Get some typos fixed (#9234)
* Do not ignore .codespellrc from git

* Add rudimentary codespell config

* Add pre-commit definition for codespell

* more custom skips for codespell - long lines, lines with ú etc

* [DATALAD RUNCMD] Do interactive fixing of some ambigous typos

=== Do not change lines below ===
{
 "chain": [],
 "cmd": "codespell -w -i 3 -C 2 ./docs/community/release-notes.md",
 "exit": 0,
 "extra_inputs": [],
 "inputs": [],
 "outputs": [],
 "pwd": "."
}
^^^ Do not change lines above ^^^

* BF: pre-commit needs to duplicate some of the skips for codespell

Known issue -- yet to be addressed:

https://github.com/codespell-project/codespell/issues/3196

* Move codespell configuration into setup.cfg
2024-02-28 12:01:49 +01:00
KanchiMoe
3c9490be22
resolve deprecation warnings for setup-python (#9266) 2024-02-28 11:57:33 +01:00
Rodrigo
d4016d8ec1
Add Django 5.0 support (#9233)
* Update tox.ini

* Update tests for Django 5.0

* Update documentation

* Update setup.py
2024-02-28 11:52:22 +01:00
willeM_ Van Onsem
a45432b54d
refactor removing parameters from kwargs when creating a ListSerializer (#9245)
* refactor removing parameters from kwargs when creating a ListSerializer

* insert child

* small rewrite

---------

Co-authored-by: Willem Van Onsem <willem.vanonsem@prosafco.be>
2024-02-20 15:08:19 +01:00
Rodrigo
37ec04d518
Add Python 3.12 support (#9230)
* added python 3.12 to CI

* Update setup.py

---------

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2024-02-20 14:16:03 +01:00
Yousef Abu Shanab
4773d737b9
docs: Update third-party-packages.md to rename customization packages (#9248)
* Add 2 customization packages, rest-framework-redesign and rest-framework-material

* docs: Update third-party-packages.md to rename customization packages
2024-02-20 14:14:13 +01:00
Asif Saif Uddin
336e7addb6
added python 3.12 to CI (#9157)
* added python 3.12 to CI

* Update tox.ini

* Update tox.ini

* Update tox.ini
2024-02-20 14:12:07 +01:00
şuayip üzülmez
2ef77b1833
Use POST method instead of GET to perform logout in browsable API (#9208)
* Use POST method instead of GET to perform logout in browsable API

* Add a test that checks the presence of the logout form
2024-02-19 23:28:04 +01:00
Victorien
df89f32b88
Fix typo in 3.14 announcement (#9255) 2024-02-14 11:02:02 +00:00
iamkorniichuk
5ad467aa2c
Remove read_only deprecated behaviour from documentation (#9239) 2024-01-29 09:30:29 +01:00
Yuekui
41edb3b9dd
Avoid unnecessary unique together checking (#9154) 2024-01-26 11:36:18 +01:00
Marcelo Galigniana
2797c0f216
Add missing import in /api-guide/viewsets/ example (#9235) 2024-01-25 12:01:06 +01:00
Christian Clauss
ab694eccde
Fix typo (#9231) 2024-01-24 23:17:01 +01:00
Christian Clauss
74689b1f44
pre-commit autoupdate (#9232) 2024-01-24 22:47:46 +01:00
Kien Dang
f85d8cb81a
Fix comment syntax error in doc that fails pre-commit blacken-docs (#9225)
* Fix comment syntax in doc

* Pre-commit
2024-01-24 22:44:46 +01:00
Kien Dang
552a67acde
Skip coreapi tests in GenerateSchemaTests if coreapi is not installed (#9229) 2024-01-19 11:10:56 +01:00
Viicos
c4f9d432dd
Update 3.11-announcement.md (#9227) 2024-01-18 15:35:57 +01:00
Kien Dang
21bb21b65b
Fix use of ip_address_validators for Django 5.1+ (#9180)
* Fix use of ip_address_validators for Django 5.0+

* Change affected django version to 5.1
2024-01-11 13:34:46 +01:00
Code Apprentice
047bec1288
Add documentation to show how to add authentication for the browseable api (#9137) 2024-01-04 14:16:57 +00:00
Matt George
f4175b4b07
Update quickstart.md (#9185)
add .order_by() to eliminate Pagination UnorderedObjectListWarning
2024-01-04 13:10:53 +00:00
Yousef Abu Shanab
530baa23cd
Add 2 customization packages, rest-framework-redesign and rest-framework-material (#9088) 2024-01-04 12:42:54 +00:00
HGZahn
4c231d5b97
Clarifying the file to edit (#9189) 2024-01-04 12:36:49 +00:00
Asif Saif Uddin
0f39e0124d
Update requirements-optionals.txt (#9181)
* Update requirements-optionals.txt

* Update requirements-optionals.txt
2023-12-06 22:44:47 +06:00
Krishna2864
0abb84fa39
removed hyperlink for web browsable API on homepage (#9174) 2023-11-30 11:07:36 +00:00
Tom Christie
06022e788e
Update README.md 2023-11-29 14:15:53 +00:00
Tom Christie
15f619ade0
Add Svix to sponsors (#9173) 2023-11-29 14:13:36 +00:00
Asif Saif Uddin
1db19f4b2d
Update pytest version in requirements-testing.txt (#9158) 2023-11-05 11:59:10 +06:00
Asif Saif Uddin
f56b85b7dd
Update pygments>=2.12.0,<2.14.0 in requirements-optionals (#9142)
* Update pygments>=2.12.0,<2.16.1 in requirements-optionals

* Update requirements/requirements-optionals.txt

* Update requirements/requirements-optionals.txt

* Update requirements/requirements-optionals.txt
2023-10-17 16:13:10 +06:00
Asif Saif Uddin
2c59206b3e
Update requirements-documentation.txt (#9141) 2023-10-17 15:40:12 +06:00
J.V. Zammit
e794e5e5e4
blacken-docs (#8906)
* blacken-docs: Manual fixes for command to pass without errors

* blacken-docs: Adds blacken-docs step to precommit hook.

* blacken-docs: Adds changes made by command itself.

* blacken-docs: Modifies blacken-docs step to only process files under "docs" directory

* blacken-docs: Updates pre-commit config file to exclude all directories other than "docs" to be compatible with "--all-files" flag.

* blacken-docs: Adds commas at the end to make it look identical to pre-black version
2023-10-13 12:44:45 +01:00
Viicos
18b02ce00e
Add missing DEFAULT_VERSIONING_CLASS entry to API docs (#9126) 2023-10-08 13:30:10 +06:00
Marko
8da6b696ab
docs: update django requirement to 4.2 (#9128) 2023-10-07 14:55:25 +06:00
Michael Herman
d181511155
add courses section to community resources (#8845) 2023-10-05 10:06:07 +01:00
Terence Honles
4296189283
fix dist test by moving --no-pkgroot to runtests.py (#9129)
This change fixes the dist test by moving the --no-pkgroot option from
pytest to the runtests script.

The current "filterwarnings" setting for pytest includes rest_framework,
which causes an early import of the module. As a result the current
--no-pkgroot behavior fails with an assertion error. Trying to remove
the module from sys.modules will cause the warning filter to not apply,
so this change moves this code before pytest parses the config and loads
the "filterwarnings".
2023-10-05 12:33:53 +06:00
Viicos
d32346bae5
Fix type name of FieldInfo namedtuple (#9124)
* Fix type name of `FieldInfo` namedtuple

* Add test
2023-10-04 23:03:10 +06:00
Marcelo Galigniana
605cc4f736
Updated links to CSRF/AJAX Django documentation (#9118) 2023-09-29 15:06:16 +06:00
Asif Saif Uddin
4bbfa8d455
Updated Checkout action version & Ubuntu OS version (#9097)
* Updated Checkout action version & Ubuntu OS version

* Update .github/workflows/main.yml
2023-09-09 13:55:32 +06:00
Asif Saif Uddin
b6e3a22f7c
added jQuery 3.7.1 support & dropped previous version (#9094)
* added jQuery 3.7.1 support & dropped previous version

* added jQuery 3.7.1 support & dropped previous version
2023-09-09 13:51:05 +06:00
Daniel
5a01a4c8a9
Update CONTRIBUTING.md (#9095)
Removed apostrophe from "it's".
2023-08-31 14:19:25 +06:00
Harald Nezbeda
40eccb0d6c
Fixes documentation link test (#9076) 2023-08-17 16:21:03 +06:00
Devid
5c07060ce0
Use str as default path converter (#9066) 2023-08-16 20:11:50 +06:00
Ori Roza
9e05aa5962
Update third-party-packages.md (#9026)
added https://github.com/Ori-Roza/drf-api-action to third packages docs
2023-08-15 11:58:06 +06:00
Pavel Král
a47adbcd0f
Document support for http.HTTPMethod in the @action decorator added in Python 3.11. (#9067)
* Implement tests for HTTPMethod from Python 3.11

* Update documentation to mention HTTPMethod support in @action
2023-08-15 11:50:02 +06:00
Denis Surkov
2843b925f9
Add note for HiddenField behavior (#9055)
* Add note for HiddenField behavior

* Update docs/api-guide/fields.md

* Update docs/api-guide/validators.md

---------

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2023-08-15 11:20:05 +06:00
Harald Nezbeda
a2430a8cce
Add docs validation to release process (#6967)
* Add ci stage to test for broken links in documentation

* Add docs validation to release process

* Update .github/workflows/main.yml

* Update .github/workflows/main.yml

---------

Co-authored-by: Ryan P Kilby <kilbyr@gmail.com>
Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2023-08-15 11:17:08 +06:00
rexes-aka
6ebe6f2600
Update exceptions.md (#9071) 2023-08-15 10:56:42 +06:00
Denis Orehovsky
da9288878b
Partial serializer should not have required fields (#7563) 2023-08-13 10:36:19 +06:00
rizwanshaikh
7a9db57eaf
Propagate 'default' from model_field to serializer field. (#9030)
* Propagate 'default' from model_field to serializer field

Fix #7469.

Co-authored-by: Nikhil Benesch <nikhil.benesch@gmail.com>

* updated field default on serializer according to openapi generation and added that to options action response

* added notes regarding default value propagation from model to serializer field

* updated note

* Update docs/api-guide/fields.md

* Update docs/api-guide/fields.md

* Update docs/api-guide/fields.md

* Update docs/api-guide/fields.md

* Update docs/api-guide/fields.md

* Update docs/api-guide/fields.md

---------

Co-authored-by: John Parton <john.parton.iv@gmail.com>
Co-authored-by: Nikhil Benesch <nikhil.benesch@gmail.com>
Co-authored-by: Rizwan Shaikh <rshaikh@ces-ltd.com>
Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2023-08-07 12:35:54 +06:00
Pierre Chiquet
589b5dca9e
Allow to override child.run_validation call in ListSerializer (#8035)
* Separated run_child_validation method in ListSerializer

* fix typo

* Add test_update_allow_custom_child_validation

---------

Co-authored-by: Pierre Chiquet <pierre.chiquet@ubikey.fr>
2023-07-26 10:27:49 +06:00
Devid
b99df0cf78
Align SearchFilter behaviour to django.contrib.admin search (#9017)
* Use subquery to remove duplicates in SearchFilter

* Align SearchFilter behaviour to django.contrib.admin

* Add compatibility with older django/python versions

* Allow search to split also by comma after smart split

* Use generator to build search conditions to reduce iterations

* Improve search documentation

* Update docs/api-guide/filtering.md

---------

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2023-07-25 19:01:23 +06:00
Amin Aminian
5c3b6e496c
class name added to unkown field error (#9019) 2023-07-25 13:51:25 +06:00
Sergey Klyuykov
7658ffd71d
Fix: Pagination response schemas. (#9049) 2023-07-15 15:26:56 +06:00
Burson
66d86d0177
Fix choices in ChoiceField to support IntEnum (#8955)
Python support Enum in version 3.4, but changed __str__ to int.__str__ until version 3.11 to better support the replacement of existing constants use-case.
[https://docs.python.org/3/library/enum.html#enum.IntEnum](https://docs.python.org/3/library/enum.html#enum.IntEnum)

rest_frame work support Python 3.6+, this commit will support the Enum in choices of Field.
2023-07-13 18:50:49 +06:00
Andrew
4f7e9ed3bb
Fix SearchFilter renders field with invalid value (#9023)
Co-authored-by: Andrii Tarasenko <andrii.tarasenko@py-t.com>
2023-07-02 13:57:20 +06:00
Samiul Sk
8dd4250d02
remove unnecessary line which was causing isort error (#9014) 2023-06-21 11:05:44 +06:00
Samiul Sk
8b7e6f2e34
Update pre-commit.yml (#9012) 2023-06-20 17:43:33 +06:00
rizwanshaikh
9cfa4bd7cc
Fix OpenAPI Schema yaml rendering for timedelta (#9007)
* fix OpenAPIRenderer for timedelta

* added test for rendering openapi with timedelta

* fix OpenAPIRenderer for timedelta

* added test for rendering openapi with timedelta

* Removed usage of field.choices that triggered full table load (#8950)

Removed the `{{ field.choices|yesno:",disabled" }}` block because this triggers the loading of full database table worth of objects just to determine whether the multi-select widget should be set as disabled or not.

Since this "disabled" marking feature is not present in the normal select field, then I propose to remove it also from the multi-select.

* Added Deprecation Warnings for CoreAPI (#7519)

* Added Deprecation Warnings for CoreAPI

* Bumped removal to DRF315

* Update rest_framework/__init__.py

* Update rest_framework/filters.py

* Update rest_framework/filters.py

* Update tests/schemas/test_coreapi.py

* Update rest_framework/filters.py

* Update rest_framework/filters.py

* Update tests/schemas/test_coreapi.py

* Update tests/schemas/test_coreapi.py

* Update setup.cfg

* Update rest_framework/pagination.py

---------

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>

* Update copy right timeline

* Fix NamespaceVersioning ignoring DEFAULT_VERSION on non-None namespaces (#7278)

* Fix the case where if the namespace is not None and there's no match,
  NamespaceVersioning always raises NotFound even if DEFAULT_VERSION
  is set or None is in ALLOWED_VERSIONS

* Add test cases

* fix OpenAPIRenderer for timedelta

* added test for rendering openapi with timedelta

* added testcase for rendering yaml with minvalidator for duration field (timedelta)

---------

Co-authored-by: Rizwan Shaikh <rshaikh@ces-ltd.com>
Co-authored-by: Lenno Nagel <lenno@namespace.ee>
Co-authored-by: David Smith <39445562+smithdc1@users.noreply.github.com>
Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
Co-authored-by: Konstantin Kuchkov <konstantin.kuchkov@gmail.com>
2023-06-17 09:18:25 +06:00
Konstantin Kuchkov
71f87a5864
Fix NamespaceVersioning ignoring DEFAULT_VERSION on non-None namespaces (#7278)
* Fix the case where if the namespace is not None and there's no match,
  NamespaceVersioning always raises NotFound even if DEFAULT_VERSION
  is set or None is in ALLOWED_VERSIONS

* Add test cases
2023-06-14 19:24:09 +06:00
Asif Saif Uddin
aed7761a8d
Update copy right timeline 2023-06-13 15:01:29 +06:00
David Smith
a16dbfd110
Added Deprecation Warnings for CoreAPI (#7519)
* Added Deprecation Warnings for CoreAPI

* Bumped removal to DRF315

* Update rest_framework/__init__.py

* Update rest_framework/filters.py

* Update rest_framework/filters.py

* Update tests/schemas/test_coreapi.py

* Update rest_framework/filters.py

* Update rest_framework/filters.py

* Update tests/schemas/test_coreapi.py

* Update tests/schemas/test_coreapi.py

* Update tests/schemas/test_coreapi.py

* Update tests/schemas/test_coreapi.py

* Update rest_framework/pagination.py

* Update rest_framework/pagination.py

* Update rest_framework/pagination.py

* Update rest_framework/pagination.py

* Update rest_framework/schemas/coreapi.py

* Update rest_framework/schemas/coreapi.py

* Update rest_framework/schemas/coreapi.py

* Update rest_framework/schemas/coreapi.py

* Update rest_framework/schemas/coreapi.py

* Update tests/schemas/test_coreapi.py

* Update setup.cfg

* Update tests/schemas/test_coreapi.py

* Update tests/schemas/test_coreapi.py

* Update tests/schemas/test_coreapi.py

* Update tests/schemas/test_coreapi.py

* Update tests/schemas/test_coreapi.py

* Update tests/schemas/test_coreapi.py

* Update rest_framework/pagination.py

---------

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2023-06-13 12:55:22 +06:00
Lenno Nagel
833313496c
Removed usage of field.choices that triggered full table load (#8950)
Removed the `{{ field.choices|yesno:",disabled" }}` block because this triggers the loading of full database table worth of objects just to determine whether the multi-select widget should be set as disabled or not.

Since this "disabled" marking feature is not present in the normal select field, then I propose to remove it also from the multi-select.
2023-06-13 10:27:37 +06:00
Nancy Eckenthal
a180bde0fd
Permit mixed casing of string values for BooleanField validation (#8970)
* be more permissive of mixed casing in validating strings for BooleanField values

* undo unnecessary change

* lint
2023-06-12 21:21:18 +06:00
Niyaz
02d9bfc2dd
Fixes BrowsableAPIRenderer for usage with ListSerializer. (#7530)
Renders list of items in raw_data_form and does not renders form in
template while using with `ListSerializer` (`many=True`).
2023-06-12 19:28:28 +06:00
Mathieu Dupuy
376a5cbbba
remove dependency on pytz (#8984)
* remove pytz

* Revert "remove pytz"

This reverts commit 393609dfaa.

* remove pytz, more subtly
2023-06-04 11:24:07 +06:00
Alasdair Nicol
03e2ecc9a5
Add NullBooleanField deprecation to docs (#8999) 2023-06-02 06:29:11 +06:00
Vladimir Kasatkin
ff5f647df0
Fix example of requires_context attribute (#8952) 2023-05-31 10:36:21 +06:00
Saad Aleem
e2a4559c03
Fix validation for ListSerializer (#8979)
* fix: Make the instance variable of child serializer point to the correct list object instead of the entire list when validating ListSerializer

* fix formatting issues for list serializer validation fix

* fix imports sorting for list serializer tests

* remove django 2.2 from docs index (#8982)

* Declared Django 4.2 support in README.md (#8985)

* Fix Links in Documentation to Django `reverse` and `reverse_lazy` (#8986)

* Fix Django Docs url in reverse.md

Django URLs of the documentation of `reverse` and `reverse_lazy` were wrong.

* Update reverse.md

* fix URLPathVersioning reverse fallback (#7247)

* fix URLPathVersioning reverse fallback

* add test for URLPathVersioning reverse fallback

* Update tests/test_versioning.py

---------

Co-authored-by: Jorn van Wier <jorn.van.wier@thunderbyte.ai>
Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>

* Make set_value a method within `Serializer` (#8001)

* Make set_value a static method for Serializers

As an alternative to #7671, let the method be overridden if needed. As
the function is only used for serializers, it has a better place in the
Serializer class.

* Set `set_value` as an object (non-static) method

* Add tests for set_value()

These tests follow the examples given in the method.

* fix: Make the instance variable of child serializer point to the correct list object instead of the entire list when validating ListSerializer

* Make set_value a method within `Serializer` (#8001)

* Make set_value a static method for Serializers

As an alternative to #7671, let the method be overridden if needed. As
the function is only used for serializers, it has a better place in the
Serializer class.

* Set `set_value` as an object (non-static) method

* Add tests for set_value()

These tests follow the examples given in the method.

* fix: Make the instance variable of child serializer point to the correct list object instead of the entire list when validating ListSerializer

* fix: Make the instance variable of child serializer point to the correct list object instead of the entire list when validating ListSerializer

* fix formatting issues for list serializer validation fix

* fix: Make the instance variable of child serializer point to the correct list object instead of the entire list when validating ListSerializer

* fix formatting issues for list serializer validation fix

* fix linting

* Update rest_framework/serializers.py

Co-authored-by: Sergei Shishov <sshishov@users.noreply.github.com>

* Update rest_framework/serializers.py

Co-authored-by: Sergei Shishov <sshishov@users.noreply.github.com>

* fix: instance variable in list serializer, remove commented code

---------

Co-authored-by: Mathieu Dupuy <deronnax@gmail.com>
Co-authored-by: Mehraz Hossain Rumman <59512321+MehrazRumman@users.noreply.github.com>
Co-authored-by: Dominik Bruhn <dominik@dbruhn.de>
Co-authored-by: jornvanwier <mail@jornvanwier.com>
Co-authored-by: Jorn van Wier <jorn.van.wier@thunderbyte.ai>
Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
Co-authored-by: Étienne Beaulé <beauleetienne0@gmail.com>
Co-authored-by: Sergei Shishov <sshishov@users.noreply.github.com>
2023-05-29 20:03:11 +06:00
Étienne Beaulé
d252d22343
Make set_value a method within Serializer (#8001)
* Make set_value a static method for Serializers

As an alternative to #7671, let the method be overridden if needed. As
the function is only used for serializers, it has a better place in the
Serializer class.

* Set `set_value` as an object (non-static) method

* Add tests for set_value()

These tests follow the examples given in the method.
2023-05-24 19:59:42 +06:00
jornvanwier
a25aac7d67
fix URLPathVersioning reverse fallback (#7247)
* fix URLPathVersioning reverse fallback

* add test for URLPathVersioning reverse fallback

* Update tests/test_versioning.py

---------

Co-authored-by: Jorn van Wier <jorn.van.wier@thunderbyte.ai>
Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2023-05-18 09:46:40 +06:00
Dominik Bruhn
332e9560ab
Fix Links in Documentation to Django reverse and reverse_lazy (#8986)
* Fix Django Docs url in reverse.md

Django URLs of the documentation of `reverse` and `reverse_lazy` were wrong.

* Update reverse.md
2023-05-17 11:46:48 +06:00
Mehraz Hossain Rumman
7bebe97724
Declared Django 4.2 support in README.md (#8985) 2023-05-15 21:02:17 +06:00
Mathieu Dupuy
001d6ec2c9
remove django 2.2 from docs index (#8982) 2023-05-14 06:00:13 +06:00
Ismael Jiménez Sánchez
99e8b4033e
feat: enforce Decimal type in min_value and max_value arguments of DecimalField (#8972)
* add warning when min_value and max_value are not decimal

* remove redundant module name in log

---------

Co-authored-by: ismaeljs <>
2023-05-09 20:50:29 +06:00
Saad Aleem
e08e606c82
Fix mapping for choice values (#8968)
* fix mapping for choice values

* fix tests for ChoiceField IntegerChoices

* fix imports

* fix imports in tests

* Check for multiple choice enums

* fix formatting

* add tests for text choices class
2023-05-03 13:08:07 +06:00
Mahdi Rahimi
d14eb7555d
Refactor read function to use context manager for file handling (#8967)
Co-authored-by: Mahdi <mahdi@Mahdis-MacBook-Pro.local>
2023-05-02 22:09:19 +06:00
fdomain
f1a11d41cb
fix: fallback on CursorPagination ordering if unset on the view (#8954)
* this commit fixes the usage of a CursorPagination combined with a view
  implementing an ordering filter, without a default ordering value.
* former behavior was to fetch the ordering value from the filter, and
  raises an error if the value was None, preventing the fallback on the
  ordering set on the CursorPagination class itself.
* we reversed the logic by getting first the value set on the class,
  and override it by the ordering filter if the parameter is present
2023-05-02 06:55:59 +06:00
suayip uzulmez
54307a4394
Replaced OrderedDict with dict (#8964) 2023-04-30 15:20:02 +06:00
Mahdi Rahimi
1ce0853ac5
Refactor get_field_info method to include max_digits and decimal_places attributes in SimpleMetadata class (#8943)
* Refactor get_field_info method to include max_digits and decimal_places attributes in SimpleMetadata class

* Add new test to check decimal_field_info_type

* Update rest_framework/metadata.py

---------

Co-authored-by: Mahdi <mahdi@Mahdis-MacBook-Pro.local>
Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2023-04-27 10:24:13 +06:00
Asif Saif Uddin
38a74b42da
Revert "test codecov gha (#8946)" (#8947)
This reverts commit 684522807f.
2023-04-15 12:11:35 +06:00
Asif Saif Uddin
684522807f
test codecov gha (#8946) 2023-04-13 21:48:45 +06:00
Maxwell Muoto
0d6ef034d2
Implement __eq__ for validators (#8925)
* Implement equality operator and add test coverage

* Add documentation on implementation
2023-04-09 14:53:47 +06:00
ddelange
b1cec517ff
Ensure CursorPagination respects nulls in the ordering field (#8912)
* Ensure CursorPagination respects nulls in the ordering field

* Lint

* Fix pagination tests

* Add test_ascending with nulls

* Push tests for nulls

* Test pass

* Add comment

* Fix test for django30
2023-04-08 16:42:28 +06:00
Maxwell Muoto
62abf6ac1f
Use ZoneInfo as primary source of timezone data (#8924)
* Use ZoneInfo as primary source of timezone data

* Update tests/test_fields.py

---------

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2023-04-08 15:16:00 +06:00
Nikita Reznikov
4842ad1b6a
Add username search field for TokenAdmin (#8927) (#8934)
* Add username search field for TokenAdmin (#8927)

* Sort imports in a proper order (#8927)
2023-04-08 14:56:49 +06:00
Arnab Kumar Shil
959085c145
Handle Nested Relation in SlugRelatedField when many=False (#8922)
* Update relations.py

Currently if you define the slug field as a nested relationship in a `SlugRelatedField` while many=False, it will cause an attribute error. For example:

For this code:
```
class SomeSerializer(serializers.ModelSerializer):
    some_field= serializers.SlugRelatedField(queryset=SomeClass.objects.all(), slug_field="foo__bar")
```
The POST request (or save operation) should work just fine, but if you use GET, then it will fail with Attribute error:

> AttributeError: 'SomeClass' object has no attribute 'foo__bar'

Thus I am handling nested relation here. Reference: https://stackoverflow.com/questions/75878103/drf-attributeerror-when-trying-to-creating-a-instance-with-slugrelatedfield-and/75882424#75882424

* Fixed test cases

* code comment changes related to slugrelatedfield

* changes based on pre-commit and removed comma which was added accidentally

* fixed primary keys of the mock object

* added more test cases based on review

---------

Co-authored-by: Arnab Shil <arnab.shil@thermofisher.com>
2023-04-08 12:27:14 +06:00
Christian Franke
ea03e95174
docs: Fix authentication / authorization mixup (#8930)
`IsAuthenticatedOrReadOnly` authorizes users that are not
authenticated for read-only access to resources.

Therefore, they are unauthenticated users, not unauthorized users.
2023-04-04 14:44:59 +06:00
Christian Franke
3428cec194
Use consistent spelling for "authorization" (#8929)
Apart from a few exceptions, django-rest-framework uses the American
English spelling "authorization"/"authorized".

    $ git grep -oi authorised | wc -l
    2
    $ git grep -oi authorized | wc -l
    30

Replace the few occurences of the British English spelling with the
American English one.
2023-04-04 13:38:23 +06:00
Asif Saif Uddin
b60fbf3374
test django 4.2 stable release (#8932) 2023-04-03 22:35:11 +06:00
Asif Saif Uddin
6b73acc173
Update requirements-packaging.txt (#8921) 2023-03-28 16:35:44 +06:00
Asif Saif Uddin
59430111bd
Update tox with django 4.2rc1 (#8920) 2023-03-28 16:08:27 +06:00
Asif Saif Uddin
29b6dd8ed2
Bump version of jQuery to 3.6.4 & updated ref links (#8909) 2023-03-28 15:43:25 +06:00
Mathieu Dupuy
c9e7b68a4c
minor documentation improvements and fixes (#8903)
* minor documentation improvements and fixes

* Update docs/api-guide/fields.md

---------

Co-authored-by: Tom Christie <tom@tomchristie.com>
2023-03-14 13:31:34 +00:00
Konstantin Alekseev
b7523f4b9f
Support UniqueConstraint (#7438) 2023-03-03 13:04:47 +06:00
Asif Saif Uddin
9882207c16
test django 4.2b1 (#8892) 2023-02-28 22:02:12 +06:00
Jayant
3f8ab538c1
docs: add missing renderer import in tutorial 6 (#8885) 2023-02-27 00:06:48 +06:00
Jameel Al-Aziz
15c613a9eb
Allow generic requests, responses, fields, views (#8825)
Allow Request, Response, Field, and GenericAPIView to be subscriptable.
This allows the classes to be made generic for type checking.

This is especially useful since monkey patching DRF can be problematic
as seen in this [issue][1].

[1]: https://github.com/typeddjango/djangorestframework-stubs/issues/299
2023-02-22 21:39:01 +06:00
Jameel Al-Aziz
390daf7a92
Upgrade isort version in pre-commit (#8882)
This fixes recent issues with installing isort via pre-commit that was
introduced in recent versions of poetry-core.

See https://github.com/PyCQA/isort/pull/2078
2023-02-22 12:05:45 +06:00
Özgür
34953774f3
docs: fix code example (#8880) 2023-02-16 12:48:34 +06:00
Ehsan200
4abfa28e08
feat: Add some changes to ValidationError to support django style vadation errors (#8863) 2023-02-06 17:30:48 +06:00
piotrszyma
22d206c1e0
Inherit from faked classes in tests to satisfy mypy (#8859)
* tests: inherit FakeResolverMatcher from django.urls.ResolverMatcher in tests/test_versioning.py

* tests: inherit from rest_framework.versioning.BaseVersioning in tests/test_reverse.py

* fix: isort

---------

Co-authored-by: Piotr Szyma <pszyma@opera.com>
2023-01-28 17:18:58 +06:00
Asif Saif Uddin
2db0c0bf0a
initial django 4.2a1 testing (#8846)
* initial django 4.2a1 testing

* django 4.2 in classifier
2023-01-19 20:47:50 +06:00
Manish Kumar Shah
0618fa88e1
Fix Respect can_read_model permission in DjangoModelPermissions (#8009)
* Fix Respect `can_read_model` permission in DjangoModelPermissions

FIXES: #6324

* Updated documentation and simplified code
2023-01-13 14:52:54 +06:00
Devid
2d19f233ab
Add SimplePathRouter (#6789)
* Allow usage of Django 2.x path in SimpleRouter

* Use path in Default router

* Update docs/api-guide/routers.md

Co-authored-by: Éric <merwok@netwok.org>

* Update docs/api-guide/routers.md

Co-authored-by: Éric <merwok@netwok.org>

* Add tests also for default router with path

* Use a more relevant attribute for lookup when using path converters

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
Co-authored-by: Éric <merwok@netwok.org>
2023-01-12 14:16:48 +06:00
Yuekui
2b34aa4291
Re-prefetch related objects after updating (#8043)
* Re-prefetch related objects after updating

* Fix flake8 format

* Use _prefetch_related_lookups and refine test cases

* Add more test cases and refine prefetch checking
2023-01-11 15:30:15 +06:00
totycro
bfce663a60
Update documentation regarding arguments of ValidationError (#8807)
The documentation used to state that the `detail` argument was
mandatory, but in fact it currently is not.
2023-01-10 00:53:49 +06:00
Radosław Kowalski
89d6ce7d43
fix FilePathField required argument (#8805) 2023-01-05 01:21:57 +06:00
johnthagen
069c701ebf
Update docs to maintained djangorestframework-guardian2 (#8817)
* Update docs to maintained django-rest-framework-guardian2

* Update to updated GitHub project name
2023-01-03 19:18:05 +06:00
Asif Saif Uddin
b3d2753308
Revert "Fix bug in validators documentation (#8779)" (#8811)
This reverts commit 614bd87b60.
2023-01-03 17:59:36 +06:00
Asif Saif Uddin
bf4c6e78d4
try update django-filter==22.1 (#8813)
* try update django-filter==22.1

* Update requirements/requirements-optionals.txt
2023-01-03 17:45:28 +06:00
Asif Saif Uddin
118543769f
upddate setup python action to v4 (#8806) 2023-01-03 17:41:40 +06:00
Asif Saif Uddin
dd81eec2fd
attrs==22.1.0 (#8828) 2023-01-03 10:30:04 +00:00
Waqas Ali
406988ba7b
- fix transifex-client version in packaging requirements. (#8827) 2023-01-03 14:31:30 +06:00
David Graves
48a21aa0eb
raise ImproperlyConfigured exception if basename is not unique (#8438)
* raise ImproperlyConfigured if basename already exists

* rename already_registered function; return True/False

* additional basename tests

* additional basename tests

* Update rest_framework/routers.py

Co-authored-by: David Graves <dgraves@lrtcapitalgroup.com>
Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2022-12-10 22:50:41 +06:00
kanazawa
b79099f7ba
Use PrimaryKeyRelatedField pkfield in openapi (#8315) 2022-12-10 22:48:43 +06:00
Adam Johnson
59ae95b22f
Upgrade to tox 4 (#8795) 2022-12-08 08:01:07 +00:00
Jakub Bodek
1355890f9f
replace partition with split in BasicAuthentication (#8790)
* replace partition with split in BasicAuthentication

* test if basic auth without provided password fails
2022-12-08 09:52:35 +06:00
Rodrigo
1fbe16a8d2
Fix BooleanField's allow_null behavior (#8614)
* Fix BooleanField's allow_null behavior

* Update rest_framework.fields

- Use .get with default value for 'allow_null' kwarg in BooleanField's
  init
2022-12-06 15:04:50 +06:00
Sigve Sebastian Farstad
ee15731cbc
Handle Django's ValidationErrors in ListField (#6423)
Without this, Django's ValidationErrors will bypass the error collection
from ListField's children.

Here is an example that illustrates this change.

Consider a Serializer that uses ListField like this:

```python
class SomeSerializer(serializers.Serializer):
    uuids = serializers.ListField(
	child=serializers.PrimaryKeyRelatedField(
	    queryset=Model.objects.something(),
	    validators=[SomeCustomValidator()]
	)
    )
```

Validating data that looks like this works fine:

```python
{uuids: ['some-valid-uuid', 'some-valid-uuid']}
```

Raising a DRF ValidationError for one of the children works fine, giving
an error object like:

```python
{'uuids': {0: ErrorDetail(string='Some validation error')}}
```

Raising a Django ValidationError for one of the children works
differently (which serializers.PrimaryKeyRelatedField can do in some
cases, like when the uuid is malformed). It gives an error object like:

```python
{'uuids': ["'X' is not a valid UUID."]}
```

Handling Django's ValidationErrors in ListField explicitly (like in this
pull request), will maintain a regular error interface in this case:

```python
{'uuids': {0: ErrorDetail(string="'X' is not a valid UUID.")}}
```
2022-12-04 20:37:47 +06:00
juspence
cc3c89a11c
Remove a bit of inline CSS. Add CSP nonce where it might be required and is available. (#8783)
Co-authored-by: Craig Anderson <craiga@craiga.id.au>
2022-12-02 11:47:04 +06:00
Tom Christie
a02bb79d87
Update admin.py (#8534)
Use `autocomplete_fields` to keep the select user field manageable.
2022-12-02 11:40:15 +06:00
Floris Hoogenboom
614bd87b60
Fix bug in validators documentation (#8779)
Function validators seem to have to return their value (which will become part of `validated_data`) as part of their signature.
2022-12-01 22:13:14 +06:00
juspence
1ae812ea20
Make browsable API compatbile with strong CSP (#8784)
Co-authored-by: Alexander Bliskovsky <abliskovsky@fusionbox.com>
2022-11-29 20:49:41 +00:00
Luka Jeran
6ec6ddea9b
Avoid inline script execution for injecting CSRF token (#7016)
Scripts with type="application/json" or "text/plain" are not executed, so we can
use them to inject dynamic CSRF data, without allowing inline-script execution
in Content-Security-Policy.
2022-11-29 16:10:32 +00:00
T. Franzel
f0095b4de2
Remove Core API mentions from docs (#8780)
* remove coreapi generator mentions & hidden docs

* remove coreapi doc & redirect broken links to github snapshot
2022-11-28 14:41:08 +01:00
T. Franzel
5435b2c9f0
mitigate global dependency on inflection #8017 (#8781) 2022-11-28 09:11:10 +06:00
Thomas Irgang
3bf611787a
Register Django urls (#8778)
Without adding the URLs manually, the users and groups APIs were not usable.

My env:
(venv) ➜  tutorial pip freeze
asgiref==3.5.2
astroid==2.12.13
autopep8==2.0.0
dill==0.3.6
Django==4.1.3
djangorestframework==3.14.0
isort==5.10.1
lazy-object-proxy==1.8.0
mccabe==0.7.0
platformdirs==2.5.4
pycodestyle==2.10.0
pylint==2.15.6
pylint-django==2.5.3
pylint-plugin-utils==0.7
pytz==2022.6
sqlparse==0.4.3
tomli==2.0.1
tomlkit==0.11.6
wrapt==1.14.1
2022-11-27 18:53:48 +06:00
Giebisch
4ef0fc1ca0
Implemented Verbose Name Translation for TokenProxy (#8713) 2022-11-27 16:45:54 +06:00
Peter Thomassen
52f4139674
Properly handle OverflowError in DurationField deserialization (#8042)
Related: https://github.com/django/django/pull/8870/files
2022-11-24 17:27:45 +06:00
Shinya Ohyanagi
9e328a9549
Fix OpenAPI operation name plural appropriately (#8017) 2022-11-24 13:48:05 +06:00
hashlash
ebde56b932
Represent SafeString as plain string on schema rendering. (#8429)
* Use SafeString.represent_str to represent SafeString as str

* Add SafeString yaml rendering test
2022-11-23 20:42:06 +06:00
Denny Biasiolli
c0d95cb967
Fix #8771 - Checking for authentication even if _ignore_model_permissions = True (#8772) 2022-11-22 20:21:16 +06:00
T. Franzel
b87699c034
Update schema generation doc & add deprecation notice #8453 (#8773)
* Update schema generation doc & add deprecation notice #8453

* Update docs/topics/documenting-your-api.md

Co-authored-by: Tom Christie <tom@tomchristie.com>

* Update docs/topics/documenting-your-api.md

Co-authored-by: Tom Christie <tom@tomchristie.com>

* Update docs/topics/documenting-your-api.md

Co-authored-by: Tom Christie <tom@tomchristie.com>

Co-authored-by: T. Franzel <13507857+tfranzel@users.noreply.github.com>
Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
Co-authored-by: Tom Christie <tom@tomchristie.com>
2022-11-22 19:53:54 +06:00
Géry Ogam
fd7d3a7b92
Update 6-viewsets-and-routers.md (#8590)
* Update 6-viewsets-and-routers.md

* Update docs/tutorial/6-viewsets-and-routers.md

* Update docs/tutorial/6-viewsets-and-routers.md

* Update docs/tutorial/6-viewsets-and-routers.md

* Update docs/tutorial/6-viewsets-and-routers.md

* Update docs/tutorial/6-viewsets-and-routers.md

* Update docs/tutorial/6-viewsets-and-routers.md

* Update docs/tutorial/6-viewsets-and-routers.md

* Update docs/tutorial/6-viewsets-and-routers.md

* Update docs/tutorial/6-viewsets-and-routers.md

* Update docs/tutorial/6-viewsets-and-routers.md

* Update docs/tutorial/6-viewsets-and-routers.md

* Update docs/tutorial/6-viewsets-and-routers.md

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2022-11-22 14:39:26 +06:00
Subin Kim
8175f05c89
Added pagination settings test case (#8362) 2022-11-22 14:18:47 +06:00
Shi Pengtao
0ae3323bd2
fix 404 when page query parameter is empty string (#8578)
* fix 404 when page query parameter is empty string

* Update pagination.py

* Update pagination.py

Co-authored-by: Tom Christie <tom@tomchristie.com>
2022-11-22 12:37:31 +06:00
954
03c2ef1787
Fixes instance check in ListSerializer.to_representation (#8726) (#8727)
* Fixes 'RelatedManager' object is not iterable in ListSerializer.to_representation.(#8726)

* Change to only BaseManager

* Commit unit test

* Update tests/test_serializer_lists.py

* Update tests/test_serializer_lists.py

* Update tests/test_serializer_lists.py

* Update tests/test_serializer_lists.py

* Update tests/test_serializer_lists.py

* Update tests/test_serializer_lists.py

* Format import

* Format import

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2022-11-22 12:01:01 +06:00
Jason Joy Atsu Winmorre
9e56f54efb
FloatField will crash if the input is a number that is too big (#8725)
* FloatField will crash if the input is a number that is too big

* Added Unit test for float field overflow error catch

* Removed random import

* Removed additional imported ValidationError

* Update rest_framework/fields.py

* Update tests/test_fields.py

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
2022-11-22 11:15:25 +06:00
smt-insens
dc300aa4e0
[FIX] add missing DurationField to SimpleMetada label_lookup (#8702) 2022-11-21 20:33:19 +06:00
Asif Saif Uddin
751808c59b
converted assertion to pytest style in test status (#8769) 2022-11-21 11:32:07 +00:00
Paolo Melchiorre
2a2b092864
Fix #8751 - Add support to Python 3.11 (#8752) 2022-11-21 11:47:21 +01:00
Asif Saif Uddin
cac89ae65d
update minimum version to psycopg2-binary>=2.9.5 (#8767) 2022-11-18 15:32:10 +00:00
Asif Saif Uddin
21fdf066b4
pytest versions update (#8745)
* pytest versions update

* pytest>=7.0.0,<8.0

* pytest>=7.2.0,<8.0

* pytest>=6.2.0,<8.0
2022-11-18 11:09:05 +00:00
Manos
df60510db5
Add 3rd party entry for rest-framework-roles (#8755) 2022-11-17 14:13:18 +00:00
Ilaletdinov Almaz
3e052376ac
Added http 102, 103, 421, and 425 status codes in documentation (#8763) 2022-11-17 13:13:09 +00:00
Clemens Wolff
759fc6f42e
Make request consistently available in pagination classes (#8764)
* Store request in CursorPagination field

* Define request at start of pagination entrypoint
2022-11-17 12:47:47 +00:00
Henrik Wahlgren
d5f228dd00
Possibility to remove trailing zeros on DecimalFields representation (#6514)
* Added normalize parameter to DecimalField to be able to strip trailing zeros. Fixes #6151.

* Updated docs to include normalize option on DecimalField

* Fixed linting error in test_fields

* Removed comment and renamed normalize to normalize_output as suggested in code review

Co-authored-by: Tom Christie <tom@tomchristie.com>
2022-11-16 14:31:50 +00:00
Stanislav Levin
78cdae6999
Fix Pytest's deprecation warnings about nose usage (#8758)
Pytest 7.2.0 deprecated plain `setup` and `teardown` functions and
methods as nose idioms:
https://docs.pytest.org/en/latest/changelog.html#pytest-7-2-0-2022-10-23

`setup` can be safely replaced with `setup_method`:
https://docs.pytest.org/en/stable/deprecations.html#setup-teardown

Fixes: https://github.com/encode/django-rest-framework/issues/8757
Signed-off-by: Stanislav Levin <slev@altlinux.org>

Signed-off-by: Stanislav Levin <slev@altlinux.org>
2022-11-15 12:29:15 +00:00
Lewis M. Kabui
ae7a2b0dfa
Remove extraneous word "Both" (#8740)
* Remove extraneous word "Both"

* Update Multiparser docs

Co-authored-by: Lewis Kabui <lewisemm@users.noreply.github.com>
2022-11-10 10:31:06 +00:00
Thomas
1142ee5fc1
Update jobs.md (#8737)
Update remoteok.io to remoteok.com
Add pyjobs.com
2022-11-02 11:10:45 +00:00
Géry Ogam
2510456817
Update quickstart.md (#8575)
* Update quickstart.md

* Use PEP 8 compliant import

* Remove unauthorized password by Django (too common)
2022-10-20 15:32:25 +01:00
Francisco Couzo
041b88f8bb
Improve style, fix some typos (#8405)
* Improve style, fix some typos

* Update docs/api-guide/fields.md

Co-authored-by: Tom Christie <tom@tomchristie.com>

Co-authored-by: Tom Christie <tom@tomchristie.com>
2022-10-19 11:20:11 +01:00
Elton Maiyo
e354331743
Fixes typo (#8719) 2022-10-19 11:11:09 +01:00
Den
35c5be6ec2
Add a method for getting serializer field name (OpenAPI) (#7493)
* Add a method for getting serializer field name

* Add docs and test

Co-authored-by: Tom Christie <tom@tomchristie.com>
2022-10-17 10:47:45 +01:00
Jan Lis
0cb693700f
add __eq__ method for OperandHolder class (#8710) 2022-10-17 10:20:59 +01:00
mka142
b221aa2cf6
Update schemas.md (#8707) 2022-10-17 09:54:48 +01:00
Ran Benita
9407833a83
Avoid importing django.test package when not testing (#8699)
Importing anything `rest_framework` causes `django.test` to be imported.
This is because DRF registers a receiver on the
`django.test_signals.setting_changed` signal.

This is not really a problem, but it is good to avoid this because it
bloats the memory with unnecessary modules (e.g. `django.test`,
`django.core.servers.basehttp`, `socketserver`) and increases the
startup time. It also doesn't feel right to import test code into
non-test code.

Try to import the signal from a core module if possible.

Note that there's another `django.test` import in `MultiPartRenderer`,
however this import is done lazily only if the functionality is used so
can be easily avoided.
2022-10-14 16:30:26 +01:00
Shyamkumar Yadav
1fd268ae2b
Docs: use asterisk for unordered list (#8697) 2022-10-14 11:22:19 +01:00
Shyamkumar Yadav
20d347a806
Docs: Convert all tabs into spaces (#8692) 2022-10-12 11:23:45 +01:00
Klaas van Schelven
56946fac8f
Preserve exception messages for wrapped Django exceptions (#8051)
* Preserve messages for wrapped Django exceptions

* Fix the test

* Update test_generics.py

* Update test_generics.py

Co-authored-by: Tom Christie <tom@tomchristie.com>
2022-10-11 12:48:57 +00:00
Norbert Schuler
911b207fa1
Added examples to schema of CursorPagination (#8687)
* Added examples to schema of CursorPagination

Fix https://github.com/encode/django-rest-framework/issues/8686

Added missing examples for CursorPagination class to disable warnings in https://github.com/tfranzel/drf-spectacular and make it consistent with other pagination classes.

* Adapted test case for paginated response schema
2022-10-11 11:50:33 +01:00
Markus Legner
d507cd851c
Fix infinite recursion with deepcopy on Request (#8684) 2022-10-07 11:58:38 +01:00
Ahzam Ahmed
c10f226622
Refactor: Replace try/except with contextlib.suppress() (#8676) 2022-10-05 11:02:00 +01:00
mschmidm
99cf2c415f
Docs: Updated browsable-api.md (#8678)
- Replace the broken Bootswatch-Link with an Jsdelivr-Link as suggested at https://bootswatch.com/help/
- Updated the stated Bootstrap version
- Added a note that the Bootstrap version must match the default one

Co-authored-by: Tom Christie <tom@tomchristie.com>
2022-10-04 12:15:51 +01:00
Sardorbek Imomaliev
e7777cb1ee
Add spaces to router example in 6-viewsets-and-routers.md (#8448) 2022-10-03 11:48:18 +01:00
Tom Christie
ca75300ae9
Update requirements-testing.txt (#8680)
* Update requirements-testing.txt

* Update requirements-testing.txt
2022-10-03 11:39:32 +01:00
manelbdacosta
79de112d62
Minor fix to SerializeMethodField docstring (#8629) 2022-10-03 10:36:51 +01:00
Ahzam Ahmed
9e398c59ab
Minor refactor: Unnecessary use of list() function (#8672) 2022-09-27 16:08:40 +01:00
Allie
3e51ba4d51
Update documentation on dependency installation (#8566)
We depend on pytz, but until late last year we got it implicitly through
depending on Django. Since their release 4.0, however, they no longer
depend on pytz; commit 250479dc3 added the dependency directly to our
metadata in setup.py, but the documentation about dependencies (most
importantly, the instructions for new contributors) was left untouched.

This commit updates the new contributor instructions to suggest an
"editable installation" of the project at the step that previously had
users manually install Django. In this mode, pip fetches and installs
the project dependencies automatically (so in the unlikely event we grow
another dependency, that doc doesn't need to be changed again) and makes
the project available to the virtualenv's python as a normal package,
but doesn't require reinstallation for mundane edits.
2022-09-27 13:54:52 +01:00
Ahzam Ahmed
73f4835a53
Unnecessary list comprehension (#8670) 2022-09-26 13:05:53 +01:00
David Cain
2de5081829
Use correct class to indicate present deprecation (#8665)
`PendingDeprecationWarning` means "we plan to deprecate, but haven't
yet." A feature that's to be deleted in the next release is not planned
to be deprecated; it **is** deprecated.

> Base class for warnings about features which are obsolete and expected
> to be deprecated in the future, but are not deprecated at the moment.
>
> This class is rarely used as emitting a warning about a possible
> upcoming deprecation is unusual, and DeprecationWarning is preferred for
> already active deprecations.

https://docs.python.org/3/library/exceptions.html#PendingDeprecationWarning

Co-authored-by: Tom Christie <tom@tomchristie.com>
2022-09-22 14:07:43 -04:00
Tom Christie
2da473c8c8 Add 3.14 announcement to the docs 2022-09-22 12:37:51 +01:00
Tom Christie
58e0a698e3
Update setup.py to drop Django 2.2 and update release notes (#8666) 2022-09-22 12:31:43 +01:00
Gulshan Ramnath Prajapati
11bfda92ba
both statement have dupplicate bodies (#8633) 2022-09-22 10:50:56 +01:00
Aaron Taajik
058424c16a
docs: delete duplicate explanation (#8641) 2022-09-22 10:50:23 +01:00
Cihan Eran
eb88dfc4b4
Add --api-version CLI option to generateschema (#8663)
* Add --version CLI option to generateschema

* fix conflicting argument name
2022-09-22 10:36:01 +01:00
David Cain
f34f1562ff
Remove old deprecation classes for 3.14 release (#8664)
When DRF 3.14 is released, these exception classes will be meaningless,
so we can delete them (this has always been done).

A previous PR removed the last incidence of `RemovedInDRF313Warning`,
but didn't outright delete the class for fear of shipping a breaking
change: https://github.com/encode/django-rest-framework/pull/8589
2022-09-22 10:32:26 +01:00
Tom Christie
c6cafc9725
Update release-notes.md 2022-09-21 14:33:41 +01:00
Tom Christie
f8b3f38b57
Update supported versions for 3.14 release (#8662)
* Update supported versions for 3.14 release

* Fix up test case for Django 3.0
2022-09-21 14:32:02 +01:00
Tim Schilling
b658915846
Version 3.14.0 proposal (#8599)
* Version 3.14.0

* Update docs/community/release-notes.md to use proper links.

Co-authored-by: Adam Johnson <me@adamj.eu>

* Add community announcement page for version 3.14

* Remove deprecated NullBooleanField.

* Change openapi _get_reference removal to 3.15

This deprecation was never released in the 3.13.x series and therefore
can't be removed at the same time the replacement is released.

* Removing deprecated openapi methods.

Co-authored-by: Adam Johnson <me@adamj.eu>
2022-09-21 14:08:12 +01:00
Tom Christie
51f1aff162
Revert 8552 (#8661) 2022-09-21 14:03:39 +01:00
Cihan Eran
3401ef56f8
Add --version CLI option to generateschema (#8552) 2022-09-21 13:08:21 +01:00
David Smith
4aea8dd65a
Change semantic of OR of two permission classes (#7522)
* Change semantic of OR of two permission classes

The original semantic of OR is defined as: the request pass either of the two has_permission() check, and pass either of the two has_object_permission() check, which could lead to situations that a request passes has_permission() but fails on has_object_permission() of Permission Class A, fails has_permission() but passes has_object_permission() of Permission Class B, passes the OR permission check. This should not be the desired permission check semantic in applications, because such a request should fail on either Permission Class (on Django object permission) alone, but passes the OR or the two.

My code fix this by changing the semantic so that the request has to pass either class's has_permission() and has_object_permission() to get the Django object permission of the OR check.

* Update rest_framework/permissions.py

* Update setup.cfg

Co-authored-by: Mark Yu <markyu98@outlook.com>
Co-authored-by: Tom Christie <tom@tomchristie.com>
2022-09-21 12:19:33 +01:00
willbeaufoy
354ae73ffb
Make APIClient.force_authenticate() work with user=None (#8212)
* Fix testing with token

* Add unit test

* Split unit test into 3

* Fix linting error
2022-09-15 09:35:48 +01:00
Aaron Taajik
acf6582de4
Docs: edit headings in Authentication (#8644) 2022-09-09 15:27:15 +01:00
Aaron Taajik
5b616c503f
docs: fix level of some headings (#8636) 2022-09-05 13:02:12 +01:00
Aaron Taajik
1ca1583513
docs: add the missing module name (#8635) 2022-09-05 11:20:23 +01:00
gabn88
54d52c66fd
Fixes that namespaced views now also appear in the extra actions (#8598)
* Fixes that namespaced views now also appear in the extra actions

Before this fix, namespaced views would not appear in the extra actions. With this fix they do.

* Flake fix
2022-08-31 11:17:19 +01:00
Daian Gan
c7acdd6006
Use .get() to find correct kwargs field and avoid KeyError (#8607)
In the "Creating custom mixins" documentation, the code example recommends using
```python
if self.kwargs[field]
```
However, if the correct field is not present in kwargs, a KeyError arises.
A more secure option is tu use .get() to validate that the field is contained in the kwargs dictionary:
```python
if self.kwargs.get(field)
```
2022-08-31 10:18:17 +01:00
Géry Ogam
5bf338ea88
Update README.md (#8592)
* Update README.md

* revert ViewSet change

Co-authored-by: Adam Johnson <me@adamj.eu>
2022-08-30 12:30:42 +01:00
Aaron Taajik
72e66e4d67
fix minor typo (#8626) 2022-08-30 12:27:48 +01:00
WillowP
dca4d7c027
Docs: Clarify model used in DjangoModelPermissions (#8615)
I found it unclear how the model was determined for `DjangoModelPermissions`. The docs say you need a `queryset` or `get_queryset`, but not that the value returned from those is what determines the model that is used.
2022-08-22 12:32:54 +01:00
MaertHaekkinen
0a10556548
Update README.md (#8611)
Update twitter of the project's author
2022-08-22 11:35:23 +01:00
Youngkwang Yang
9043df6be7
Add trailing slash (#8604) 2022-08-22 10:52:34 +01:00
Jonas Lundberg
df584350b4
Prevent head method mapping to coerce action name (#7729) 2022-08-12 12:00:55 +01:00
ProstoMaxim
791d48c690
Enforce is_valid(raise_exception=False) as a keyword-only argument. (#7952)
* make raise_exception a keyword-only argument

* make raise_exception keyword-only in metaclass
2022-08-10 14:00:30 +01:00
Adam Johnson
35a6d65e22
Fix setuptools warning about license_files (#8595) 2022-08-10 13:47:39 +01:00
Adam Johnson
20d106d8a3
Upgraded Bootstrap to 3.4.1 and added CSS source maps (#8591) 2022-08-10 11:53:21 +01:00
David Cain
8b2ccccbe5
Stop calling set_context, planned for 3.13 drop (#8589)
Per the deprecation warnings (which have been raised since DRF 3.11),
`set_context()` was planned not to be supported in DRF 3.13. I think we
can safely delete it, in favor of `requires_context`.

From the 3.11 announcement:

> Previous our approach to this was that implementations could include a
> `set_context` method, which would be called prior to validation. However
> this approach had issues with potential race conditions. We have now
> move this approach into a pending deprecation state. It will continue to
> function, but will be escalated to a deprecated state in 3.12, and
> removed entirely in 3.13.

Why keep `RemovedInDRF313Warning` around?
=========================================
It's a bit odd that version 3.13 includes an exception class describing
things which are to be deleted in 3.13, but I've opted to keep the (now
unreferenced) class around, for fear of breaking others' setup.

(For example, if projects have a `filterwarnings` setup meant to
intercept `rest_framework.RemovedInDRF313Warning`, an error will be
thrown due to an unresolvable reference).
2022-08-08 11:18:49 +01:00
Łukasz Wieczorek
fd8adb32ce
Refactor short names in exceptions (#8585) 2022-08-01 16:28:05 +01:00
Allan Lewis
224168a28f
exceptions.ErrorDetail: Handle NotImplemented correctly in __ne__ (#8538)
PR #7531 resolved issue #7433 by updating `ErrorDetails.__eq__` to correctly
handle the `NotImplemented` case. However, Python 3.9 continues to issue the
following warning:

    DeprecationWarning: NotImplemented should not be used in a boolean context

This is because `__ne__` still doesn't handle the `NotImplemented` case
correctly. In order to avoid this warning, this commit makes the same change
for `__ne__` as previously made for `__eq__`.
2022-08-01 15:18:22 +01:00
Sergey Lyapustin
a1b35bb44b
Use example.com domain in tests. (#8571)
* Use example.com domain for the samples.

* Fixed typo.
2022-07-25 10:28:41 +01:00
Carlton Gibson
ad282da97c
Replaced parse_header with parse_header_parameters. (#8556)
Add a backwards compatibility shim for Django versions that have no (or an incompatible)
django.utils.http.parse_header_parameters implementation.

Thanks to Shai Berger for review. 

Co-authored-by: Jaap Roes <jroes@leukeleu.nl>
2022-07-14 14:20:36 +02:00
Stanislav Khlud
101aff6c43
Make autogenerated read only fields to be able to be nullable (#8536) 2022-06-28 15:22:46 +01:00
Burak Kadir Er
9f07d9edeb
Make minor corrections in docs (#8525) 2022-06-24 14:21:51 +01:00
Felix Viernickel
129890ab1b
Fix error in throttling when request.user is None (#8370)
Check to see if request.user is set before proceeding with further
authentication checks.
2022-06-24 13:02:11 +01:00
Yuekui
2051a79da3
Fix "`" typo (#8529) 2022-06-24 12:08:18 +01:00
Stian Jensen
dba9493a90
Don't evaluate default_timezone unless needed (#8531)
If you set a custom timezone for a DateTimeField, the function
self.default_timezone() is still called, since fallback params to
getattr are still evaluated.

This rewrites to use hasattr, so the fallback case is only executed if
it will actually be used. If you render a lot of DateTimeFields in a
serializer, the time spent evaluating default_timezone() once for each
of them can accumulate to quite a bit, which is just unused work in the
case where timezone is already specified on the field.
2022-06-24 11:28:00 +01:00
Tom Christie
fa9d516ee2
Update docstring test for more recent pygments version (#8530)
* Update docstring test for more recent pygments version

* Drop unused import
2022-06-20 10:44:27 +01:00
Burak Kadir Er
2506d0b4f2
Update include and namespace URLs (#8520) 2022-06-09 15:30:47 +01:00
Alessandro
82475c232b
Made relative URLs clickable as well. (#8464) 2022-06-08 15:03:00 +01:00
Stephen Finucane
5185cc9348
Handle unset fields with 'many=True' (#7574)
* Handle unset fields with 'many=True'

The docs note:

  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.

However, this doesn't work for fields with 'many=True'. When using
these, the default is simply ignored.

The solution is simple: do in 'ManyRelatedField' what we were already
doing for 'Field', namely, catch possible 'AttributeError' and
'KeyError' exceptions and return the default if there is one set.

Signed-off-by: Stephen Finucane <stephen@that.guru>
Closes: #7550

* Add test cases for #7550

Signed-off-by: Stephen Finucane <stephen@that.guru>
2022-06-08 14:46:19 +01:00
Marti Raudsepp
26830c3d2d
Fix QueryDict type error in test (#8475)
QueryDict takes a `str` argument. Discovered while working on
djangorestframework-stubs.
2022-06-08 14:37:46 +01:00
itsdkey
e7af8d662b
tests for #5127 (#7715)
* tests for #5127

* Resolves #5127
2022-06-08 13:41:26 +01:00
Patrick Daley
f8a03b096b
Remove pluralisation from basenames (#8517)
HyperlinkIdentityFields in serializers reference 'snippet-highlight' and 'snippet-detail', router basenames updated to match.
2022-06-07 12:35:01 +01:00
Grigory
1396f6886a
Respect model error_messages for relation (#7599) 2022-06-06 13:53:42 +01:00
Alan Crosswell
563a20a040
make get_reference public (#7515) 2022-06-06 13:44:02 +01:00
Daniel Gilge
bb7dcef19b
Update get_schema in docs (#7402) 2022-06-06 13:31:00 +01:00
Krukov D
281fc074ba
improve performance for noncallble attributes (#8502)
Co-authored-by: Dima Kryukov <dmitry.kryukov@pandadoc.com>
2022-06-06 12:54:57 +01:00
ghazi-git
292ead1fe0
add drf-standardized-errors to third party packages (#8487)
Co-authored-by: Tom Christie <tom@tomchristie.com>
2022-06-06 12:46:11 +01:00
Leonardo Gregianin
5471f8a1d9
Added django-requestlogs in third party packages (#8497) 2022-06-06 12:39:36 +01:00
Mariusz Felisiak
333f1ffb94
Confirmed support for Django 4.1. (#8498) 2022-06-06 12:39:06 +01:00
Tom Christie
7069083b0f Promote Spacinov to premium sponsorship 2022-06-06 11:07:25 +01:00
Tom Christie
ce21454a43 Update homepage sponsors 2022-06-06 11:00:01 +01:00
Tom Christie
e5fb9af0ea Add FEZTO as a premium sponsor 2022-05-26 11:19:09 +01:00
Tom Christie
449ce6cc75 Resize sponsor images 2022-05-26 10:48:08 +01:00
Tom Christie
ed00e11cc5 Add FEZTO 2022-05-26 10:40:46 +01:00
Tom Christie
33b86a8e53
Recommend Django REST Knox (#8490)
* Recommend Django REST Knox

* Pin jinja2 to fix docs builds
2022-05-18 13:10:38 +01:00
Q_back
cdc956a96c
Update description of docs/api-guide/fields.md -> required (#8476)
fix: Documentation did not point out that default value of `required`
`Field` parameter is `False` depending on the Django's `Model.field`.
2022-05-03 11:10:37 +01:00
Aarni Koskela
b1004a4733
docs: Add a note on concurrency and races (#6950)
Refs #5181

Co-authored-by: Adam Johnson <me@adamj.eu>
2022-04-24 23:16:18 +01:00
Kojo Idrissa
86673a337a
corrected grammar to improve clarity (#8466) 2022-04-14 21:00:38 +01:00
hashlash
df92e57ad6
Added test client support for HTTP 307 and 308 redirects (#8419)
* Add retain test data on follow=True

* Simplify TestAPITestClient.test_follow_redirect

Inspired from Django's ClientTest.test_follow_307_and_308_redirect

* Add 307 308 follow redirect test
2022-03-24 09:57:42 +00:00
Tom Christie
df4d16d2f1
Add StaleBot (#8423) 2022-03-24 09:23:16 +00:00
Wagner de Lima
7e4e6d2070
docs: include drf-social-oauth2 to docs. (#8310)
django-rest-framework-social-oauth2 is not a maintained library anymore.
2022-03-23 12:09:05 +00:00
Shivendra Pratap Kushwaha
4464ce7270
Link added for Test Case Classes and corrected stable link for Refresh from DB (#8381)
Link added for Test Case Classes and corrected stable link for Refresh from DB.
2022-03-23 12:07:44 +00:00
Tom Christie
a4334a8126
Update contribution guidelines (#8422) 2022-03-23 11:52:45 +00:00
Tom Christie
75f1998123
Update throttling docs (#8424) 2022-03-23 11:52:26 +00:00
Mariusz Felisiak
0b88583a10
Bumped versions in Github actions configuration to v3. (#8414) 2022-03-23 11:28:46 +00:00
Tom Christie
070c32f4a6
Update SECURITY.md (#8412) 2022-03-16 12:12:25 +00:00
baseplate-admin
b521160c92
Fix code block in README.md (#8408)
Hi there,

The code block below show imply `Python` as it lives in `settings.py`

```
INSTALLED_APPS = [
    ...
    'rest_framework',
]
```

This pull request essentially fixes that.
2022-03-16 11:35:24 +00:00
Tom Christie
b3083d83ae
Update index.md (#8411)
Update security email.
2022-03-16 11:35:04 +00:00
Tom Christie
0e3bc2b1e0
Throttling disclaimer (#8403)
* Throttling disclaimer

* Expand throttling disclaimer.
2022-03-11 10:58:59 +00:00
Timothy Allen
a53e523f93
We've renamed the drf-renderer-xlsx package to drf-excel. (#8396) 2022-03-08 10:39:16 +00:00
Josh
efc7c1d664
Update accepted_media_type argument in Renderer docs (#8364) 2022-02-12 16:21:59 +00:00
Partho Kumar Rajvor
5bea22f321
Added http 102, 103, 421, and 425 status codes (#8350) 2022-02-03 11:57:47 +00:00
Bhuwan Panta
c26ec5a3b8
Update 6-viewsets-and-routers.md (#8349)
# Basename key missing in the tutorial
```diff
+router.register(r'snippets', views.SnippetViewSet,basename="snippets")
+router.register(r'users', views.UserViewSet,basename="users")
-router.register(r'snippets', views.SnippetViewSet)
-router.register(r'users', views.UserViewSet)
```
2022-02-01 13:48:22 +00:00
Tom Christie
a5d741aba4
Update renderers.py 2022-02-01 09:42:43 +00:00
Sevdimali
f378f98a40
if else optimization (#8340)
Removed redundant parentheses
2022-01-27 15:02:20 +00:00
denniskloyn
02eeb6fa00
Change MIDDLEWARE_CLASSES to MIDDLEWARE (#8333)
The `MIDDLEWARE_CLASSES` setting got changed to `MIDDLEWARE` in [Django 1.10](https://docs.djangoproject.com/en/1.10/topics/http/middleware/).
2022-01-18 08:52:11 +00:00
Shivendra Pratap Kushwaha
94eb804abe
Update filtering.md (#8331) 2022-01-17 09:41:23 +00:00
Tom Christie
c5be86a6db
Update sponsor URL (#8328)
* Update sponsor URL

* Update index.md
2022-01-11 13:01:25 +00:00
Suntae Kim
f9ccbad4d9
minor update on tutorial serialization (#8323) 2022-01-06 13:55:44 +00:00
kaushik kothiya
5b2abbed25
Correct variable name (#8306)
urlpatterns name variable name in space remove.
2021-12-22 15:17:57 +00:00
Luke Plant
bce9df9b5e
Make ReturnDict support dict union operators on Python 3.9 and later (#8302)
Fixes issue #8301
2021-12-22 15:08:58 +00:00
Guilouf
45082b3936
Fixed missing "fields" meta argument in docs (#8243)
* Fixed missing "fields" meta argument in docs, leading to an assertion error

* Update docs/api-guide/serializers.md

Co-authored-by: Tom Christie <tom@tomchristie.com>

Co-authored-by: Tom Christie <tom@tomchristie.com>
2021-12-17 15:20:14 +00:00
Tom Christie
f4cf0260bf Version 3.13.1 2021-12-15 15:18:24 +00:00
Tom Christie
a780e80deb
Revert "Make api_view respect standard wrapper assignments (#8291)" (#8297)
This reverts commit 9c97946531.
2021-12-15 15:16:38 +00:00
juliangeissler
2d52c9e8bc
Update Tutorial - quickstart (#7943)
* Tutorial - Adjust quickstart

Add asgi.py file
Also add paragraph for the second user, which is later displayed

* Tutorial - Adjust quickstart

It seems that there is no CLI command to easily create a user
Remove the second user from the Markdown
Image next

* Tutorial - quickstart - Update browsable API image

Only show the admin user
New Image has similar width and is compressed
2021-12-13 14:08:55 +00:00
Abhineet
f3bb5b9cdc
Add missing commas in pagination response samples (#8185) 2021-12-13 14:04:04 +00:00
Jameel Al-Aziz
b3beb15b00
Fix CursorPagination parameter schema type (#7708)
The CursorPagination's cursor query parameter expects a string and not
an integer.

Fixes #7691
2021-12-13 14:03:09 +00:00
Tom Christie
7a84dc749c
Version 3.13 (#8285)
* Version 3.12.5

* Version 3.13

* Version 3.13
2021-12-13 13:10:17 +00:00
tim-mccurrach
9c97946531
Make api_view respect standard wrapper assignments (#8291) 2021-12-13 13:08:40 +00:00
Tom Christie
d0bb4d877f
Tweak test_description (#8293) 2021-12-13 09:33:03 +00:00
Alexander Clausen
ba25869045
Fix REQUIRED_PYTHON in setup.py (#8292)
Just a left-over from #8288 to sync the "Unsupported Python version" message with `python_requires`.
2021-12-13 08:57:55 +00:00
Paolo Melchiorre
773f479719
Python/Django compatibility updates (#8288)
* Update python and django versions in tox.ini

* Update  python requires in setup.py

* Update tox.ini

Co-authored-by: Tom Christie <tom@tomchristie.com>
2021-12-10 15:31:01 +00:00
Tom Christie
217b0bf3af
Add Python 3.10 to test matrix (#8287)
* Add Python 3.10 to test matrix

* Update README, docs homepage to properly reflect Python versions that we test against
2021-12-10 12:04:27 +00:00
Tom Christie
16ca0c24d3 Add 3.10 to tox.ini and setup.py 2021-12-10 11:53:48 +00:00
Jet Li
1cb3fa2e81
Test Django 4.0 (#8280)
* Test Django 4.0

Django 4.0 released today.

* Test Django 4.0

* Test Django 4.0

* Test Django 4.0
2021-12-10 09:31:05 +00:00
Tom Christie
c05998f5dd Add CryptAPI to docs homepage 2021-12-08 15:11:55 +00:00
Tom Christie
d1bab643ab
Update README.md 2021-12-08 14:53:45 +00:00
Tom Christie
6e0cb8a7aa
Add CryptAPI sponsorship (#8283) 2021-12-08 14:53:06 +00:00
Chen Wen Kang
47ee3fc9a9
Update docs related to coreapi to include deprecation notice (#8186)
* Update docs related to coreapi to include deprecation notice

* Update docs to use reference to version 3.10 release notes instead of 3.9
2021-12-08 14:38:42 +00:00
Alexander Klimenko
b0d407fd63
Made api_setting.UNICODE_JSON/ensure_ascii affecting json schema (#7991) 2021-12-08 14:37:32 +00:00
Matthew Pull
3a762d9aac
Update permissions.md (#8260)
I might just be misunderstanding something (always a strong possibility!), but it seems to me that the table on the Permissions page is slightly inaccurate.

For `permission_classes`, wouldn't it have global-level permissions for list actions (rather than no permission control, as is currently listed)?
2021-12-08 14:35:06 +00:00
Jeremy Langley
37b73ef46e
IsAdmin permissions changed to IsAdminUser (#8227)
Documentation change to keep up with the code permission changes.

Co-authored-by: Jeremy Langley <jlangley2code@gmail.com>
2021-12-08 14:33:41 +00:00
Jaap Roes
dabf2216c3
Update django-cors-headers links (#8176) 2021-12-08 14:30:34 +00:00
Yecine Megdiche
380ac8e79d
Remove old-style super calls (#8226) 2021-12-06 15:32:33 +00:00
Asif Saif Uddin
580bf45ccf
test v4 beta 1 (#8222)
* test v4 beta 1

* django 4 rc1
2021-11-22 10:48:58 +00:00
Dmytro Litvinov
0d5250cffa
Fix link to installation of httpie (#8257)
Right now httpie moved to "httpie" organization (https://github.com/httpie/httpie) and they don't have "installation" at their GitHub. Instead of that, they have "Getting started" section with link to "Installation instructions".
2021-11-15 08:54:19 +00:00
Anton Burnashev
060a3b632f
Docs: fix broken link (#8245) 2021-11-10 16:31:15 +00:00
Sébastien Lavoie
781890b7df
docs(api-guide-testing): Fix typo 'CRSF' and plural of word (#8238) 2021-11-08 09:59:32 +00:00
rgermain
00cd4ef864
add third packages nested-multipart-parser (#8208) 2021-10-15 15:13:20 +01:00
Uzair Ali
ddc5cd7e4b
Imported Response (#8207) 2021-10-07 15:52:44 +01:00
Edmund
53a0585dac
Update permissions.md to fix garden path sentences (#8206) 2021-10-07 09:09:00 +01:00
thetarby
6ea95b6ad1
Highlight select_related and prefetch_related usage in documentation (#7610)
* docs updated to highlight use of select_related and prefetch related to avoid n+1 problems

* Apply suggestions from code review

cosmetic changes

Co-authored-by: Xavier Ordoquy <xordoquy@linovia.com>

* cosmetic changes

Co-authored-by: Xavier Ordoquy <xordoquy@linovia.com>
2021-10-05 15:33:55 +01:00
Phil Leggetter
605a624da6
Add PostHog as premium sponsors (#8193)
* Add PostHog as premium sponsors

* Adding 275x250 PostHog image
2021-10-05 14:02:34 +01:00
Akhil Kokani
1fa5bc31c0
Update serializers.md (#8189)
* Update serializers.md

Removed unwanted word, "neither".

* Update docs/api-guide/serializers.md

Co-authored-by: Tom Christie <tom@tomchristie.com>
2021-09-27 10:01:47 +01:00
Carlton Gibson
c62e3ca764 Added Django 4.0 to test matrix. 2021-09-23 11:57:03 +02:00
Carlton Gibson
f46c33e4e2 Fixed TestDefaultTZDateTimeField to allow multiple tzinfo implementations.
zoneinfo was made the default time zone implementation in
306607d5b9.
2021-09-23 11:57:03 +02:00
Carlton Gibson
19b6091554 Adjusted authentication test for internal CSRF changes.
Private _get_new_csrf_token() was removed in
231de683d8.
2021-09-23 11:57:03 +02:00
Carlton Gibson
4916854492 Removed USE_L10N setting from Django 4.0.
USE_L10N defaults to True from Django 4.0, and will be removed in Django 5.0.
2021-09-23 11:57:03 +02:00
Carlton Gibson
2d9eee5d02 Adjusted URLPatternsTestCase to use addClassCleanup() from Django 4.0.
Refs faba5b702a.

addClassCleanup() is available from Python 3.8, which is the minimum supported
Python from Django 4.0.
2021-09-22 10:23:47 +02:00
Carlton Gibson
f651878df3 Adjusted DateTimeField docs for zoneinfo. 2021-09-22 10:23:46 +02:00
Carlton Gibson
250479dc37 Added pytz to install_requires.
pytz will not automatically be installed with Django from v4.0.
2021-09-22 09:57:17 +02:00
Dan Lousqui
f0a5b958a1
Add max_length and min_length options to ListSerializer (#8165) 2021-09-14 13:45:55 +01:00
Tom Christie
761f56ef40 Update stream.io link 2021-09-10 14:45:06 +01:00
Tom Christie
73f3325f80
Update stream.io link (#8161) 2021-09-10 11:32:27 +01:00
Tom Christie
9ce541e909
Revert "Fix arguments (#7995)" (#8156)
This reverts commit 9716b1b6b7.
2021-09-06 12:19:20 +01:00
Ivan Trushin
9716b1b6b7
Fix arguments (#7995)
`path()` has no argument `namespace`, it has `name` argument
2021-09-06 12:18:13 +01:00
Peter Uittenbroek
655e803adf
#7157: Fix RemoteUserAuthentication calling django authenticate with request argument (#7158) 2021-09-03 14:37:03 +01:00
Anthony Randall
96001c5de6
Added an article - implementing rest apis with embedded privacy from doordash engineering blog (#7956)
* Update tutorials-and-resources.md

* Update tutorials-and-resources.md
2021-09-03 13:23:19 +01:00
Juan Benitez
cb206e4701
fix: change View class to Throttle class on SimpleRateThrottle Docstring (#8147) 2021-09-03 13:00:23 +01:00
Ryan Nowakowski
4632b5daae
Fix subtitle of schemas for filtering (#8145)
Fix a likely copy/paste error
2021-08-31 14:18:49 +01:00
Aditya Mitra
6b392a46ea
[FIX] Typo in api-guide/authentication (#8144) 2021-08-31 13:57:02 +01:00
Asif Saif Uddin
88666629a7
stop testing django 3.0 as its EOL (#8136) 2021-08-31 13:56:08 +01:00
jefcolbi
c927053d4b
Replacing django-rest-auth with dj-rest-auth (#8146) 2021-08-31 12:51:47 +01:00
Mark
c5d9144aef
fix typo (#8122)
Co-authored-by: mgold <mgold@iponweb.net>
2021-08-11 11:30:09 +01:00
juliangeissler
cdd53c7de9
Update Tutorial - Relationships & Hyperlinked APIs (#7950)
unnecessary import, because it is already added in the previous section
2021-08-08 14:45:00 +01:00
Ben Hampson
e95e91ccf2
Use correct link for httpie (#8005)
Before it was linking to a fork of a fork of httpie. I've changed it to the right URL.
2021-08-06 16:49:41 +01:00
Thomas Grainger
b824b33dc3
add changelog project_url (#8085) 2021-08-06 16:46:57 +01:00
Paul Wayper
c4404f3d5d
We now use Libera.chat rather than Freenode for IRC (#8049)
Signed-off-by: Paul Wayper <paulway@redhat.com>

Co-authored-by: Tom Christie <tom@tomchristie.com>
2021-08-06 16:46:26 +01:00
Paul Wayper
cba24464e8
Botbot has been acquired, all paths now point to startupresources (#8050)
Signed-off-by: Paul Wayper <paulway@redhat.com>
2021-08-06 16:45:15 +01:00
Ma77heus
2942590ee3
fix: broken cite (#8086)
Co-authored-by: MattheusHenrique <mattheushenrique@gmail.com>
2021-08-06 16:39:58 +01:00
Aarni Koskela
fdb4931475
Make Field constructors keyword-only (#7632) 2021-08-06 10:14:52 +01:00
Nikhil Benesch
b215375125
Propagate nullability in ModelSerializer (#8116)
Propagate the nullability of underlying model fields in ModelSerializer
when those fields are marked as read only. This ensures the correct
generation of OpenAPI schemas.

Fix #8041.
2021-08-06 10:10:58 +01:00
Evgeny Panfilov
98e56e0327
fix empty string as a value for a validated DecimalField (#8064) (#8067) 2021-07-01 15:04:44 +01:00
Nikita Sobolev
d2977cff98
Fixes inconsistent headers in serializer docs (#8056)
Some headers were using `.`, some - were not.
Now, all of them are the same with `.`, because it was easier to fix.
2021-06-28 13:07:41 +01:00
Burak Kadir Er
c8a9c856c2
fix a small typo (#8060) 2021-06-28 12:51:21 +01:00
Adam Johnson
e92016ac2e
Stop ignoring test outcome for Django 3.2 (#7927) 2021-06-21 11:33:43 +01:00
Finn Gundlach
24a938abaa
Update documentation to include Django 3.2 as supported version (#8037) 2021-06-16 14:53:29 +01:00
Ian De Bie
61e7a993bd
fix comments by using correct css comment syntax (#8019)
these intended comments were causing errors in sonarqube scans due to using wrong css comment syntax
2021-06-07 10:30:23 +01:00
Abduaziz
9d149f2317
Fixed some punctuation marks & small typos (#8015) 2021-06-02 10:02:11 +01:00
Mariusz Felisiak
bc075212cb
Fix running runtests.py without arguments. (#7954)
Regression in aa12a5f967.
2021-05-24 09:47:44 +02:00
Ishu Kumar
3875d3284e
Punctuations and missing "to" preposition (#7966)
Changes made in lines 221, 222, 223, and 224 for better readability.
2021-05-10 12:26:26 +01:00
Julien Palard
a0083f7f98
FIX: Broken cite. (#7951) 2021-04-26 09:30:41 +01:00
Łukasz Skarżyński
431f7dfa3d
fix typo in packaging requirements (#7949) 2021-04-23 09:34:58 +01:00
Denis Orehovsky
8812394ed8
Add distinction between request and response serializers for OpenAPI (#7424)
* Add distinction between request and response serializers

* Add docs

* document new functions in schemas.md

* add a test case for different request vs response objects

* Correct formatting for flake8

Co-authored-by: Shaun Gosse <shaun.gosse@emburse.com>
2021-04-20 15:03:16 +01:00
Adam Johnson
010c8d4f08
Use tox-py in CI (#7925) 2021-04-16 17:59:27 +01:00
Adam Johnson
67b5093ca5
Fix pytest warnings (#7928)
* Use `--strict-markers` instead of `--strict`, as per this warning:

  ```
  /.../_pytest/config/__init__.py:1183: PytestDeprecationWarning: The --strict option is deprecated, use --strict-markers instead.
  ```

* Remove config option 'testspath' - pytest is logging a warning about this being unknown:

  ```
  /.../_pytest/config/__init__.py:1233: PytestConfigWarning: Unknown config option: testspath
  ```

  I can't find any reference to it in the pytest docs or changelog.
2021-04-16 17:47:21 +01:00
Terence Honles
a0a2c5cb37
Fix tests with mock timezone (#7911)
After django/django#13877, Django no longer checks for `hasattr(timezone, 'localize')` and instead does an inheritance check.
2021-04-16 17:27:22 +01:00
Adam Johnson
f628db383a
Fix GitHub Actions to run on 'master' branch (#7926)
The config I copied in #7903 was from a repo with the new name 'main', so tests have not been running on master since.
2021-04-16 17:23:18 +01:00
Terence Honles
1c494e3d94
Update references to Travis CI after moving to Github Actions (#7909)
x-ref: https://github.com/encode/django-rest-framework/pull/7903
2021-04-12 13:14:26 +01:00
Lalit Suthar
9bdd6125a1
fix broken article link (#7918)
Co-authored-by: lalit97 <lalit.suthar@redhuntlabs.com>
2021-04-12 11:59:58 +01:00
Adam Johnson
fd017d00f9
Move CI to GitHub Actions (#7903)
* Recreate all the jobs on GitHub Actions
* Upgrade to Ubuntu 20.04
* Upgrade base/docs/dist to Python 3.9
2021-04-06 18:34:18 +01:00
Adam Johnson
90635c138f
Update pre-commit for flake8 move (#7907)
See: https://twitter.com/codewithanthony/status/1378746934928699396
2021-04-06 17:49:17 +01:00
Adam Johnson
37ef62b0e6
Remove link to third party cookiecutter template (#7902)
The template has not been maintained for six years, so it's out of date on versions and various "best practices" (e.g. pre-commit). I also think any template should be documented on its own repo rather than here, especially if it's not an official maintained project.
2021-04-05 18:18:35 +01:00
Adam Johnson
aa12a5f967
Lint with pre-commit (#7900)
Following [my comment here](https://github.com/encode/django-rest-framework/pull/7589#issuecomment-813301322) and [Django's own move to pre-commit](https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/#pre-commit-checks).

* Add pre-commit config file to run flake8 and isort.
* Add extra "common sense" hooks.
* Run pre-commit on GitHub actions using the [official action](https://github.com/pre-commit/action/). This is a good way to get up-and-running but it would be better if we activated [pre-commit.ci](https://pre-commit.ci/), which is faster and will auto-update the hooks for us going forwards.
* Remove `runtests.py` code for running linting tools.
* Remove `runtests.py --fast` flag, since that would now just run `pytest -q`, which can be done with `runtests.py -q` instead.
* Remove tox configuration and requirements files for linting.
* Update the contributing guide to mention setting up pre-commit.
2021-04-05 12:08:52 +01:00
Adam Johnson
846fe70cff
De-duplicate contributing guide (#7901)
The contributing guide from `docs/community/contributing.md` was copy-pasted to `CONTRIBUTING.md` and the two have drifted apart over time. The docs page seems to have been updated a bit more so let's leave only that version.
2021-04-05 11:12:28 +01:00
David Smith
d82519bf8a
Updated dependencies (#7589) 2021-04-05 10:28:03 +01:00
dependabot[bot]
78da1a824f
Bump pygments from 2.4.2 to 2.7.4 in /requirements (#7886)
Bumps [pygments](https://github.com/pygments/pygments) from 2.4.2 to 2.7.4.
- [Release notes](https://github.com/pygments/pygments/releases)
- [Changelog](https://github.com/pygments/pygments/blob/master/CHANGES)
- [Commits](https://github.com/pygments/pygments/compare/2.4.2...2.7.4)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-04-01 16:52:19 +01:00
Tom Christie
406e6a2f35
Update MANIFEST.in (#7893) 2021-04-01 14:15:53 +01:00
David Smith
96885dd9a7
Fixed markdown test (#7892)
The pygments rendering of invalid json changed in  pygments>=2.7.3
2021-04-01 09:49:47 +01:00
239 changed files with 6464 additions and 5278 deletions

View File

@ -1,10 +0,0 @@
---
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.

View File

@ -1,6 +0,0 @@
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. 💖

13
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,13 @@
# Keep GitHub Actions up to date with GitHub's Dependabot...
# https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot
# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem
version: 2
updates:
- package-ecosystem: github-actions
directory: /
groups:
github-actions:
patterns:
- "*" # Group all Action updates into a single larger pull request
schedule:
interval: weekly

22
.github/stale.yml vendored 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

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

@ -0,0 +1,73 @@
name: CI
on:
push:
branches:
- master
pull_request:
jobs:
tests:
name: Python ${{ matrix.python-version }}
runs-on: ubuntu-24.04
strategy:
matrix:
python-version:
- '3.9'
- '3.10'
- '3.11'
- '3.12'
- '3.13'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
cache-dependency-path: 'requirements/*.txt'
- name: Upgrade packaging tools
run: python -m pip install --upgrade pip setuptools virtualenv wheel
- name: Install dependencies
run: python -m pip install --upgrade tox
- name: Run tox targets for ${{ matrix.python-version }}
run: tox run -f py$(echo ${{ matrix.python-version }} | tr -d . | cut -f 1 -d '-')
- name: Run extra tox targets
if: ${{ matrix.python-version == '3.9' }}
run: |
tox -e base,dist,docs
- name: Upload coverage
uses: codecov/codecov-action@v5
with:
env_vars: TOXENV,DJANGO
test-docs:
name: Test documentation links
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.9'
- name: Install dependencies
run: pip install -r requirements/requirements-documentation.txt
# Start mkdocs server and wait for it to be ready
- run: mkdocs serve &
- run: WAIT_TIME=0 && until nc -vzw 2 localhost 8000 || [ $WAIT_TIME -eq 5 ]; do sleep $(( WAIT_TIME++ )); done
- run: if [ $WAIT_TIME == 5 ]; then echo cannot start mkdocs server on http://localhost:8000; exit 1; fi
- name: Check links
continue-on-error: true
run: pylinkvalidate.py -P http://localhost:8000/
- run: echo "Done"

22
.github/workflows/pre-commit.yml vendored Normal file
View File

@ -0,0 +1,22 @@
name: pre-commit
on:
push:
branches:
- master
pull_request:
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: "3.10"
- uses: pre-commit/action@v3.0.1

4
.gitignore vendored
View File

@ -15,6 +15,6 @@
MANIFEST
coverage.*
!.github
!.gitignore
!.travis.yml
!.isort.cfg
!.pre-commit-config.yaml

39
.pre-commit-config.yaml Normal file
View File

@ -0,0 +1,39 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-added-large-files
- id: check-case-conflict
- id: check-json
- id: check-merge-conflict
- id: check-symlinks
- id: check-toml
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
- repo: https://github.com/PyCQA/flake8
rev: 7.0.0
hooks:
- id: flake8
additional_dependencies:
- flake8-tidy-imports
- repo: https://github.com/adamchainz/blacken-docs
rev: 1.16.0
hooks:
- id: blacken-docs
exclude: ^(?!docs).*$
additional_dependencies:
- black==23.1.0
- repo: https://github.com/codespell-project/codespell
# Configuration for codespell is in .codespellrc
rev: v2.2.6
hooks:
- id: codespell
exclude: locale|kickstarter-announcement.md|coreapi-0.1.1.js
- repo: https://github.com/asottile/pyupgrade
rev: v3.19.1
hooks:
- id: pyupgrade
args: ["--py39-plus", "--keep-percent-format"]

View File

@ -1,56 +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=3.2 }
- { 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=3.2 }
- { python: "3.8", env: DJANGO=3.0 }
- { python: "3.8", env: DJANGO=3.1 }
- { python: "3.8", env: DJANGO=3.2 }
- { python: "3.8", env: DJANGO=main }
- { python: "3.9", env: DJANGO=3.1 }
- { python: "3.9", env: DJANGO=3.2 }
- { python: "3.9", env: DJANGO=main }
- { 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=main
- env: DJANGO=3.2
install:
- pip install tox tox-travis
script:
- tox
after_success:
- pip install codecov
- codecov -e TOXENV,DJANGO
notifications:
email: false

View File

@ -1,207 +1,5 @@
# 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 its lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes.
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.
## 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,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 a code change, 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,16 @@ 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]
[![][svix-img]][svix-url]
[![][zuplo-img]][zuplo-url]
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [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], [FEZTO][fezto-url], [Svix][svix-url], and [Zuplo][zuplo-url].
---
@ -36,14 +40,12 @@ Django REST framework is a powerful and flexible toolkit for building Web APIs.
Some reasons you might want to use REST framework:
* The [Web browsable API][sandbox] is a huge usability win for your developers.
* The Web browsable API is a huge usability win for your developers.
* [Authentication policies][authentication] including optional packages for [OAuth1a][oauth1-section] and [OAuth2][oauth2-section].
* [Serialization][serializers] that supports both [ORM][modelserializer-section] and [non-ORM][serializer-section] data sources.
* Customizable all the way down - just use [regular function-based views][functionview-section] if you don't need the [more][generic-views] [powerful][viewsets] [features][routers].
* [Extensive documentation][docs], and [great community support][group].
There is a live example API for testing purposes, [available here][sandbox].
**Below**: *Screenshot from the browsable API*
![Screenshot][image]
@ -52,8 +54,8 @@ There is a live example API for testing purposes, [available here][sandbox].
# Requirements
* Python (3.5, 3.6, 3.7, 3.8, 3.9)
* Django (2.2, 3.0, 3.1)
* Python 3.9+
* Django 4.2, 5.0, 5.1, 5.2
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,7 +112,6 @@ 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 = [
@ -168,40 +171,44 @@ Or to create a new user:
Full documentation for the project is available at [https://www.django-rest-framework.org/][docs].
For questions and support, use the [REST framework discussion group][group], or `#restframework` on freenode IRC.
You may also want to [follow the author on Twitter][twitter].
For questions and support, use the [REST framework discussion group][group], or `#restframework` on libera.chat IRC.
# Security
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
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[sandbox]: https://restframework.herokuapp.com/
[funding]: https://fund.django-rest-framework.org/topics/funding/
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[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
[svix-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/svix-premium.png
[zuplo-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/zuplo-readme.png
[sentry-url]: https://getsentry.com/welcome/
[stream-url]: https://getstream.io/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
[svix-url]: https://www.svix.com/?utm_source=django-REST&utm_medium=sponsorship
[zuplo-url]: https://zuplo.link/django-gh
[oauth1-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth
[oauth2-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit

View File

@ -2,8 +2,6 @@
## 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**.
**Please report security issues by emailing security@encode.io**.
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
[security-mail]: mailto:rest-framework-security@googlegroups.com
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].
---
@ -90,6 +90,12 @@ The kind of response that will be used depends on the authentication scheme. Al
Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a `403 Permission Denied` response will always be used, regardless of the authentication scheme.
## Django 5.1+ `LoginRequiredMiddleware`
If you're running Django 5.1+ and use the [`LoginRequiredMiddleware`][login-required-middleware], please note that all views from DRF are opted-out of this middleware. This is because the authentication in DRF is based authentication and permissions classes, which may be determined after the middleware has been applied. Additionally, when the request is not authenticated, the middleware redirects the user to the login page, which is not suitable for API requests, where it's preferable to return a 401 status code.
REST framework offers an equivalent mechanism for DRF views via the global settings, `DEFAULT_AUTHENTICATION_CLASSES` and `DEFAULT_PERMISSION_CLASSES`. They should be changed accordingly if you need to enforce that API requests are logged in.
## Apache mod_wsgi specific configuration
Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.
@ -120,6 +126,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 +143,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 +158,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 +179,9 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
---
#### Generating Tokens
### Generating Tokens
##### By using signals
#### By using signals
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
@ -193,7 +205,7 @@ If you've already created some users, you can generate tokens for all existing u
for user in User.objects.all():
Token.objects.get_or_create(user=user)
##### By exposing an api endpoint
#### By exposing an api endpoint
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
@ -210,7 +222,7 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.
By default there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
By default, there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
and include them using the `throttle_classes` attribute.
If you need a customized version of the `obtain_auth_token` view, you can do so by subclassing the `ObtainAuthToken` view class, and using that in your url conf instead.
@ -242,9 +254,9 @@ And in your `urls.py`:
]
##### With Django admin
#### With Django admin
It is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
`your_app/admin.py`:
@ -279,11 +291,11 @@ If successfully authenticated, `SessionAuthentication` provides the following cr
Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response.
If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
If you're using an AJAX-style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behavior is not suitable for login views, which should always have CSRF validation applied.
## RemoteUserAuthentication
@ -293,7 +305,7 @@ environment variable.
To use it, you must have `django.contrib.auth.backends.RemoteUserBackend` (or a subclass) in your
`AUTHENTICATION_BACKENDS` setting. By default, `RemoteUserBackend` creates `User` objects for usernames that don't
already exist. To change this and other behaviour, consult the
already exist. To change this and other behavior, consult the
[Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/).
If successfully authenticated, `RemoteUserAuthentication` provides the following credentials:
@ -301,7 +313,7 @@ If successfully authenticated, `RemoteUserAuthentication` provides the following
* `request.user` will be a Django `User` instance.
* `request.auth` will be `None`.
Consult your web server's documentation for information about configuring an authentication method, e.g.:
Consult your web server's documentation for information about configuring an authentication method, for example:
* [Apache Authentication How-To](https://httpd.apache.org/docs/2.4/howto/auth.html)
* [NGINX (Restricting Access)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)
@ -316,7 +328,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 +344,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 +365,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 [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 +400,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`.
@ -404,11 +420,11 @@ The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let y
## HTTP Signature Authentication
HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] (outdated) package which provides an easy to use HTTP Signature Authentication mechanism. You can use the updated fork version of [djangorestframework-httpsignature][djangorestframework-httpsignature], which is [drf-httpsig][drf-httpsig].
HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] (outdated) package which provides an easy-to-use HTTP Signature Authentication mechanism. You can use the updated fork version of [djangorestframework-httpsignature][djangorestframework-httpsignature], which is [drf-httpsig][drf-httpsig].
## Djoser
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.
## django-rest-auth / dj-rest-auth
@ -420,21 +436,17 @@ 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-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
@ -442,13 +454,19 @@ There are currently two forks of this project.
More information can be found in the [Documentation](https://django-rest-durin.readthedocs.io/en/latest/index.html).
## django-pyoidc
[dango-pyoidc][django_pyoidc] adds support for OpenID Connect (OIDC) authentication. This allows you to delegate user management to an Identity Provider, which can be used to implement Single-Sign-On (SSO). It provides support for most uses-cases, such as customizing how token info are mapped to user models, using OIDC audiences for access control, etc.
More information can be found in the [Documentation](https://django-pyoidc.readthedocs.io/latest/index.html).
[cite]: https://jacobian.org/writing/rest-worst-practices/
[http401]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
[http403]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4
[basicauth]: https://tools.ietf.org/html/rfc2617
[permission]: permissions.md
[throttling]: throttling.md
[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax
[csrf-ajax]: https://docs.djangoproject.com/en/stable/howto/csrf/#using-csrf-protection-with-ajax
[mod_wsgi_official]: https://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGIPassAuthorization.html
[django-oauth-toolkit-getting-started]: https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html
[django-rest-framework-oauth]: https://jpadilla.github.io/django-rest-framework-oauth/
@ -473,8 +491,10 @@ More information can be found in the [Documentation](https://django-rest-durin.r
[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
[login-required-middleware]: https://docs.djangoproject.com/en/stable/ref/middleware/#django.contrib.auth.middleware.LoginRequiredMiddleware
[django-pyoidc] : https://github.com/makinacorpus/django_pyoidc

View File

@ -28,37 +28,60 @@ from rest_framework import viewsets
class UserViewSet(viewsets.ViewSet):
# With cookie: cache requested url for each user for 2 hours
@method_decorator(cache_page(60*60*2))
@method_decorator(cache_page(60 * 60 * 2))
@method_decorator(vary_on_cookie)
def list(self, request, format=None):
content = {
'user_feed': request.user.get_user_feed()
"user_feed": request.user.get_user_feed(),
}
return Response(content)
class ProfileView(APIView):
# With auth: cache requested url for each user for 2 hours
@method_decorator(cache_page(60*60*2))
@method_decorator(vary_on_headers("Authorization",))
@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()
"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))
@method_decorator(cache_page(60 * 60 * 2))
def get(self, request, format=None):
content = {
'title': 'Post title',
'body': 'Post content'
"title": "Post title",
"body": "Post content",
}
return Response(content)
```
## Using cache with @api_view decorator
When using @api_view decorator, the Django-provided method-based cache decorators such as [`cache_page`][page],
[`vary_on_cookie`][cookie] and [`vary_on_headers`][headers] can be called directly.
```python
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie
from rest_framework.decorators import api_view
from rest_framework.response import Response
@cache_page(60 * 15)
@vary_on_cookie
@api_view(["GET"])
def get_user_list(request):
content = {"user_feed": request.user.get_user_feed()}
return Response(content)
```
**NOTE:** The [`cache_page`][page] decorator only caches the
`GET` and `HEAD` responses with status 200.

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

@ -101,7 +101,7 @@ Note that the exception handler will only be called for responses generated by r
The **base class** for all exceptions raised inside an `APIView` class or `@api_view`.
To provide a custom exception, subclass `APIException` and set the `.status_code`, `.default_detail`, and `default_code` attributes on the class.
To provide a custom exception, subclass `APIException` and set the `.status_code`, `.default_detail`, and `.default_code` attributes on the class.
For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so:
@ -179,7 +179,7 @@ By default this exception results in a response with the HTTP status code "403 F
**Signature:** `NotFound(detail=None, code=None)`
Raised when a resource does not exists at the given URL. This exception is equivalent to the standard `Http404` Django exception.
Raised when a resource does not exist at the given URL. This exception is equivalent to the standard `Http404` Django exception.
By default this exception results in a response with the HTTP status code "404 Not Found".
@ -217,11 +217,10 @@ By default this exception results in a response with the HTTP status code "429 T
## ValidationError
**Signature:** `ValidationError(detail, code=None)`
**Signature:** `ValidationError(detail=None, code=None)`
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. 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.')`
@ -260,6 +259,15 @@ Set as `handler400`:
handler400 = 'rest_framework.exceptions.bad_request'
# Third party packages
The following third-party packages are also available.
## DRF Standardized Errors
The [drf-standardized-errors][drf-standardized-errors] package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.
[cite]: https://doughellmann.com/blog/2009/06/19/python-exception-handling-techniques/
[authentication]: authentication.md
[django-custom-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors

View File

@ -42,11 +42,11 @@ Set to false if this field is not required to be present during deserialization.
Setting this to `False` also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.
Defaults to `True`.
Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer) default value will be `False` if you have specified `blank=True` or `default` or `null=True` at your field in your `Model`.
### `default`
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
@ -78,7 +78,14 @@ Defaults to `False`
### `source`
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal.
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`.
When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal. Beware of possible n+1 problems when using source attribute if you are accessing a relational orm model. For example:
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField(source="user.email")
This case would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related].
The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
@ -144,7 +151,7 @@ Prior to Django 2.1 `models.BooleanField` fields were always `blank=True`. Thus
since Django 2.1 default `serializers.BooleanField` instances will be generated
without the `required` kwarg (i.e. equivalent to `required=True`) whereas with
previous versions of Django, default `BooleanField` instances will be generated
with a `required=False` option. If you want to control this behaviour manually,
with a `required=False` option. If you want to control this behavior manually,
explicitly declare the `BooleanField` on the serializer class, or use the
`extra_kwargs` option to set the `required` flag.
@ -152,14 +159,6 @@ Corresponds to `django.db.models.fields.BooleanField`.
**Signature:** `BooleanField()`
## NullBooleanField
A boolean representation that also accepts `None` as a valid value.
Corresponds to `django.db.models.fields.NullBooleanField`.
**Signature:** `NullBooleanField()`
---
# String fields
@ -172,10 +171,10 @@ Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.T
**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)`
- `max_length` - Validates that the input contains no more than this number of characters.
- `min_length` - Validates that the input contains no fewer than this number of characters.
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
* `max_length` - Validates that the input contains no more than this number of characters.
* `min_length` - Validates that the input contains no fewer than this number of characters.
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
* `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.
@ -223,11 +222,11 @@ A field that ensures the input is a valid UUID string. The `to_internal_value` m
**Signature:** `UUIDField(format='hex_verbose')`
- `format`: Determines the representation format of the uuid value
- `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
- `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
- `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
- `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
* `format`: Determines the representation format of the uuid value
* `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
* `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
* `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
* `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value`
## FilePathField
@ -238,11 +237,11 @@ Corresponds to `django.forms.fields.FilePathField`.
**Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)`
- `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
- `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
- `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
- `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
- `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
* `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
* `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
* `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
* `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
* `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
## IPAddressField
@ -252,8 +251,8 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen
**Signature**: `IPAddressField(protocol='both', unpack_ipv4=False, **options)`
- `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
- `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
* `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case-insensitive.
* `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
---
@ -267,8 +266,8 @@ Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.
**Signature**: `IntegerField(max_value=None, min_value=None)`
- `max_value` Validate that the number provided is no greater than this value.
- `min_value` Validate that the number provided is no less than this value.
* `max_value` Validate that the number provided is no greater than this value.
* `min_value` Validate that the number provided is no less than this value.
## FloatField
@ -278,8 +277,8 @@ Corresponds to `django.db.models.fields.FloatField`.
**Signature**: `FloatField(max_value=None, min_value=None)`
- `max_value` Validate that the number provided is no greater than this value.
- `min_value` Validate that the number provided is no less than this value.
* `max_value` Validate that the number provided is no greater than this value.
* `min_value` Validate that the number provided is no less than this value.
## DecimalField
@ -289,13 +288,14 @@ Corresponds to `django.db.models.fields.DecimalField`.
**Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)`
- `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
- `decimal_places` The number of decimal places to store with the number.
- `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
- `max_value` Validate that the number provided is no greater than this value.
- `min_value` Validate that the number provided is no less than this value.
- `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
- `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
* `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
* `decimal_places` The number of decimal places to store with the number.
* `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
* `max_value` Validate that the number provided is no greater than this value. Should be an integer or `Decimal` object.
* `min_value` Validate that the number provided is no less than this value. Should be an integer or `Decimal` object.
* `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
* `rounding` Sets the rounding mode used when quantizing to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
* `normalize_output` Will normalize the decimal value when serialized. This will strip all trailing zeroes and change the value's precision to the minimum required precision to be able to represent the value without losing data. Defaults to `False`.
#### Example usage
@ -307,10 +307,6 @@ And to validate numbers up to anything less than one billion with a resolution o
serializers.DecimalField(max_digits=19, decimal_places=10)
This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer.
If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise.
---
# Date and time fields
@ -325,13 +321,13 @@ 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`) representing the timezone. If not specified and the `USE_TZ` setting is enabled, this defaults to the [current timezone][django-current-timezone]. If `USE_TZ` is disabled, then datetime objects will be naive.
#### `DateTimeField` format strings.
Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`)
When a value of `None` is used for the format `datetime` objects will be returned by `to_representation` and the final output representation will determined by the renderer class.
When a value of `None` is used for the format `datetime` objects will be returned by `to_representation` and the final output representation will be determined by the renderer class.
#### `auto_now` and `auto_now_add` model fields.
@ -385,8 +381,8 @@ The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu
**Signature:** `DurationField(max_value=None, min_value=None)`
- `max_value` Validate that the duration provided is no greater than this value.
- `min_value` Validate that the duration provided is no less than this value.
* `max_value` Validate that the duration provided is no greater than this value.
* `min_value` Validate that the duration provided is no less than this value.
---
@ -400,10 +396,10 @@ Used by `ModelSerializer` to automatically generate fields if the corresponding
**Signature:** `ChoiceField(choices)`
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
@ -413,10 +409,10 @@ A field that can accept a set of zero, one or many values, chosen from a limited
**Signature:** `MultipleChoiceField(choices)`
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
@ -437,9 +433,9 @@ Corresponds to `django.forms.fields.FileField`.
**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
- `max_length` - Designates the maximum length for the file name.
- `allow_empty_file` - Designates if empty files are allowed.
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
* `max_length` - Designates the maximum length for the file name.
* `allow_empty_file` - Designates if empty files are allowed.
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
## ImageField
@ -449,9 +445,9 @@ Corresponds to `django.forms.fields.ImageField`.
**Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
- `max_length` - Designates the maximum length for the file name.
- `allow_empty_file` - Designates if empty files are allowed.
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
* `max_length` - Designates the maximum length for the file name.
* `allow_empty_file` - Designates if empty files are allowed.
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained.
@ -465,10 +461,10 @@ A field class that validates a list of objects.
**Signature**: `ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)`
- `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
- `allow_empty` - Designates if empty lists are allowed.
- `min_length` - Validates that the list contains no fewer than this number of elements.
- `max_length` - Validates that the list contains no more than this number of elements.
* `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
* `allow_empty` - Designates if empty lists are allowed.
* `min_length` - Validates that the list contains no fewer than this number of elements.
* `max_length` - Validates that the list contains no more than this number of elements.
For example, to validate a list of integers you might use something like the following:
@ -489,8 +485,8 @@ A field class that validates a dictionary of objects. The keys in `DictField` ar
**Signature**: `DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
- `allow_empty` - Designates if empty dictionaries are allowed.
* `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
* `allow_empty` - Designates if empty dictionaries are allowed.
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
@ -507,8 +503,8 @@ A preconfigured `DictField` that is compatible with Django's postgres `HStoreFie
**Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
- `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
- `allow_empty` - Designates if empty dictionaries are allowed.
* `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
* `allow_empty` - Designates if empty dictionaries are allowed.
Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings.
@ -518,8 +514,8 @@ A field class that validates that the incoming data structure consists of valid
**Signature**: `JSONField(binary, encoder)`
- `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
- `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
* `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
* `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
---
@ -554,6 +550,12 @@ The `HiddenField` class is usually only needed if you have some validation that
For further examples on `HiddenField` see the [validators](validators.md) documentation.
---
**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request).
---
## ModelField
A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.
@ -570,7 +572,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:
@ -776,7 +778,7 @@ Here the mapping between the target and source attribute pairs (`x` and
`x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField`
declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`.
Our new `DataPointSerializer` exhibits the same behaviour as the custom field
Our new `DataPointSerializer` exhibits the same behavior as the custom field
approach.
Serializing:
@ -836,7 +838,7 @@ the [djangorestframework-recursive][djangorestframework-recursive] package provi
## django-rest-framework-gis
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
## django-rest-framework-hstore
@ -855,3 +857,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

@ -213,19 +213,23 @@ This will allow the client to filter the items in the list by making queries suc
You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:
search_fields = ['username', 'email', 'profile__profession']
For [JSONField][JSONField] and [HStoreField][HStoreField] fields you can filter based on nested values within the data structure using the same double-underscore notation:
search_fields = ['data__breed', 'data__owner__other_pets__0__name']
By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.
By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. Searches may contain _quoted phrases_ with spaces, each phrase is considered as a single search term.
The search behavior may be restricted by prepending various characters to the `search_fields`.
* '^' 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/).)
* '$' Regex search.
The search behavior may be specified by prefixing field names in `search_fields` with one of the following characters (which is equivalent to adding `__<lookup>` to the field):
| Prefix | Lookup | |
| ------ | --------------| ------------------ |
| `^` | `istartswith` | Starts-with search.|
| `=` | `iexact` | Exact matches. |
| `$` | `iregex` | Regex search. |
| `@` | `search` | Full-text search (Currently only supported Django's [PostgreSQL backend][postgres-search]). |
| None | `icontains` | Contains search (Default). |
For example:
@ -241,7 +245,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].
@ -253,7 +257,7 @@ The `OrderingFilter` class supports simple query parameter controlled ordering o
![Ordering Filter](../img/ordering-filter.png)
By default, the query parameter is named `'ordering'`, but this may by overridden with the `ORDERING_PARAM` setting.
By default, the query parameter is named `'ordering'`, but this may be overridden with the `ORDERING_PARAM` setting.
For example, to order users by username:
@ -269,7 +273,7 @@ Multiple orderings may also be specified:
### Specifying which fields may be ordered against
It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an `ordering_fields` attribute on the view, like so:
It's recommended that you explicitly specify which fields the API should allow in the ordering filter. You can do this by setting an `ordering_fields` attribute on the view, like so:
class UserListView(generics.ListAPIView):
queryset = User.objects.all()
@ -335,15 +339,6 @@ Generic filters may also present an interface in the browsable API. To do so you
The method should return a rendered HTML string.
## Pagination & schemas
You can also make the filter controls available to the schema autogeneration
that REST framework provides, by implementing a `get_schema_fields()` method. This method should have the following signature:
`get_schema_fields(self, view)`
The method should return a list of `coreapi.Field` instances.
# Third party packages
The following third party packages provide additional filter implementations.
@ -374,3 +369,4 @@ The [djangorestframework-word-filter][django-rest-framework-word-search-filter]
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
[HStoreField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#hstorefield
[JSONField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#jsonfield
[postgres-search]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/search/

View File

@ -23,8 +23,8 @@ Returns a URL pattern list which includes format suffix patterns appended to eac
Arguments:
* **urlpatterns**: Required. A URL pattern list.
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
Example:
@ -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

@ -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,16 +218,16 @@ To set these attributes you should override the `CursorPagination` class, and th
# Custom pagination styles
To create a custom pagination serializer class you should subclass `pagination.BasePagination` and override the `paginate_queryset(self, queryset, request, view=None)` and `get_paginated_response(self, data)` methods:
To create a custom pagination serializer class, you should inherit the subclass `pagination.BasePagination`, override the `paginate_queryset(self, queryset, request, view=None)`, and `get_paginated_response(self, data)` methods:
* The `paginate_queryset` method is passed the initial queryset and should return an iterable object that contains only the data in the requested page.
* The `get_paginated_response` method is passed the serialized page data and should return a `Response` instance.
* The `paginate_queryset` method is passed to the initial queryset and should return an iterable object. That object contains only the data in the requested page.
* The `get_paginated_response` method is passed to the serialized page data and should return a `Response` instance.
Note that the `paginate_queryset` method may set state on the pagination instance, that may later be used by the `get_paginated_response` method.
## Example
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
class CustomPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
@ -240,7 +240,7 @@ Suppose we want to replace the default pagination output style with a modified f
'results': data
})
We'd then need to setup the custom class in our configuration:
We'd then need to set up the custom class in our configuration:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination',
@ -262,16 +262,7 @@ API responses for list endpoints will now include a `Link` header, instead of in
![Link Header][link-header]
*A custom pagination style, using the 'Link' header'*
## Pagination & schemas
You can also make the pagination controls available to the schema autogeneration
that REST framework provides, by implementing a `get_schema_fields()` method. This method should have the following signature:
`get_schema_fields(self, view)`
The method should return a list of `coreapi.Field` instances.
*A custom pagination style, using the 'Link' header*
---
@ -312,7 +303,7 @@ The [`drf-proxy-pagination` package][drf-proxy-pagination] includes a `ProxyPagi
## link-header-pagination
The [`django-rest-framework-link-header-pagination` package][drf-link-header-pagination] includes a `LinkHeaderPagination` class which provides pagination via an HTTP `Link` header as described in [Github's developer documentation](github-link-pagination).
The [`django-rest-framework-link-header-pagination` package][drf-link-header-pagination] includes a `LinkHeaderPagination` class which provides pagination via an HTTP `Link` header as described in [GitHub REST API documentation][github-traversing-with-pagination].
[cite]: https://docs.djangoproject.com/en/stable/topics/pagination/
[link-header]: ../img/link-header-pagination.png
@ -322,3 +313,4 @@ The [`django-rest-framework-link-header-pagination` package][drf-link-header-pag
[drf-link-header-pagination]: https://github.com/tbeadle/django-rest-framework-link-header-pagination
[disqus-cursor-api]: https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api
[float_cursor_pagination_example]: https://gist.github.com/keturn/8bc88525a183fd41c73ffb729b8865be#file-fpcursorpagination-py
[github-traversing-with-pagination]: https://docs.github.com/en/rest/guides/traversing-with-pagination

View File

@ -11,11 +11,11 @@ sending more complex data than simple forms
>
> &mdash; Malcom Tredinnick, [Django developers group][cite]
REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.
REST framework includes a number of built-in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.
## How the parser is determined
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
---
@ -87,7 +87,7 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
## MultiPartParser
Parses multipart HTML form content, which supports file uploads. Both `request.data` will be populated with a `QueryDict`.
Parses multipart HTML form content, which supports file uploads. `request.data` and `request.FILES` will be populated with a `QueryDict` and `MultiValueDict` respectively.
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.

View File

@ -24,9 +24,9 @@ A slightly less strict style of permission would be to allow full access to auth
Permissions in REST framework are always defined as a list of permission classes.
Before running the main body of the view each permission in the list is checked.
If any permission check fails an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run.
If any permission check fails, an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run.
When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
When the permission checks fail, either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
* The request was successfully authenticated, but permission was denied. *&mdash; An HTTP 403 Forbidden response will be returned.*
* The request was not successfully authenticated, and the highest priority authentication class *does not* use `WWW-Authenticate` headers. *&mdash; An HTTP 403 Forbidden response will be returned.*
@ -165,19 +165,19 @@ This permission is suitable if you want your API to only be accessible to a subs
## IsAuthenticatedOrReadOnly
The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`.
The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthenticated users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`.
This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.
## DjangoModelPermissions
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property or `get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned.
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property or `get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned. The appropriate model is determined by checking `get_queryset().model` or `queryset.model`.
* `POST` requests require the user to have the `add` permission on the model.
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
* `DELETE` requests require the user to have the `delete` permission on the model.
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
The default behavior can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
@ -201,7 +201,7 @@ As with `DjangoModelPermissions` you can use custom model permissions by overrid
---
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian` package][django-rest-framework-guardian]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian2` package][django-rest-framework-guardian2]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.
---
@ -286,7 +286,7 @@ The following table lists the access restriction methods and the level of contro
| | `queryset` | `permission_classes` | `serializer_class` |
|------------------------------------|------------|----------------------|--------------------|
| Action: list | global | no | object-level* |
| 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 |
@ -324,6 +324,10 @@ The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to
The [Django Rest Framework Roles][django-rest-framework-roles] package makes it easier to parameterize your API over multiple types of users.
## Rest Framework Roles
The [Rest Framework Roles][rest-framework-roles] makes it super easy to protect views based on roles. Most importantly allows you to decouple accessibility logic from models and views in a clean human-readable way.
## Django REST Framework API Key
The [Django REST Framework API Key][djangorestframework-api-key] package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. _machines_) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.
@ -349,8 +353,9 @@ The [Django Rest Framework PSQ][drf-psq] package is an extension that gives supp
[rest-condition]: https://github.com/caxap/rest_condition
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
[django-rest-framework-roles]: https://github.com/computer-lab/django-rest-framework-roles
[rest-framework-roles]: https://github.com/Pithikos/rest-framework-roles
[djangorestframework-api-key]: https://florimondmanca.github.io/djangorestframework-api-key/
[django-rest-framework-role-filters]: https://github.com/allisson/django-rest-framework-role-filters
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
[django-rest-framework-guardian2]: https://github.com/johnthagen/django-rest-framework-guardian2
[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.
@ -215,7 +246,7 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e
## HyperlinkedIdentityField
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
@ -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.
@ -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`.
@ -597,12 +628,16 @@ The [drf-nested-routers package][drf-nested-routers] provides routers and relati
The [rest-framework-generic-relations][drf-nested-relations] library provides read/write serialization for generic foreign keys.
The [rest-framework-gm2m-relations][drf-gm2m-relations] library provides read/write serialization for [django-gm2m][django-gm2m-field].
[cite]: http://users.ece.utexas.edu/~adnan/pike.html
[reverse-relationships]: https://docs.djangoproject.com/en/stable/topics/db/queries/#following-relationships-backward
[routers]: https://www.django-rest-framework.org/api-guide/routers#defaultrouter
[generic-relations]: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/#id1
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
[drf-nested-relations]: https://github.com/Ian-Foote/rest-framework-generic-relations
[drf-gm2m-relations]: https://github.com/mojtabaakbari221b/rest-framework-gm2m-relations
[django-gm2m-field]: https://github.com/tkhyn/django-gm2m
[django-intermediary-manytomany]: https://docs.djangoproject.com/en/stable/topics/db/models/#intermediary-manytomany
[dealing-with-nested-objects]: https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
[to_internal_value]: https://www.django-rest-framework.org/api-guide/serializers/#to_internal_valueself-data

View File

@ -105,7 +105,7 @@ The TemplateHTMLRenderer will create a `RequestContext`, using the `response.dat
---
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionay and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example:
**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}
@ -192,7 +192,7 @@ By default the response content will be rendered with the highest priority rende
def get_default_renderer(self, view):
return JSONRenderer()
## AdminRenderer
## AdminRenderer
Renders data into HTML for an admin-like display:
@ -257,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.
@ -267,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.
@ -283,7 +283,7 @@ By default this will include the following keys: `view`, `request`, `response`,
The following is an example plaintext renderer that will return a response with the `data` parameter as the content of the response.
from django.utils.encoding import smart_text
from django.utils.encoding import smart_str
from rest_framework import renderers
@ -291,8 +291,8 @@ The following is an example plaintext renderer that will return a response with
media_type = 'text/plain'
format = 'txt'
def render(self, data, media_type=None, renderer_context=None):
return smart_text(data, encoding=self.charset)
def render(self, data, accepted_media_type=None, renderer_context=None):
return smart_str(data, encoding=self.charset)
## Setting the character set
@ -303,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.
@ -318,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
---
@ -332,7 +332,7 @@ You can do some pretty flexible things using REST framework's renderers. Some e
* Specify multiple types of HTML representation for API clients to use.
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
## Varying behaviour by media type
## Varying behavior by media type
In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
@ -470,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.
@ -488,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
@ -525,10 +525,10 @@ Comma-separated values are a plain-text tabular data format, that can be easily
## LaTeX
[Rest Framework Latex] provides a renderer that outputs PDFs using Laulatex. It is maintained by [Pebble (S/F Software)][mypebble].
[Rest Framework Latex] provides a renderer that outputs PDFs using Lualatex. It is maintained by [Pebble (S/F Software)][mypebble].
[cite]: https://docs.djangoproject.com/en/stable/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
@ -549,7 +549,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
[mjumbewu]: https://github.com/mjumbewu
[flipperpa]: https://github.com/flipperpa
[wharton]: https://github.com/wharton
[drf-renderer-xlsx]: https://github.com/wharton/drf-renderer-xlsx
[drf-excel]: https://github.com/wharton/drf-excel
[vbabiy]: https://github.com/vbabiy
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/

View File

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

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
@ -54,5 +54,5 @@ As with the `reverse` function, you should **include the request as a keyword ar
api_root = reverse_lazy('api-root', request=request)
[cite]: https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5
[reverse]: https://docs.djangoproject.com/en/stable/topics/http/urls/#reverse
[reverse-lazy]: https://docs.djangoproject.com/en/stable/topics/http/urls/#reverse-lazy
[reverse]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse
[reverse-lazy]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse-lazy

View File

@ -142,6 +142,24 @@ The above example would now generate the following URL pattern:
* URL path: `^users/{pk}/change-password/$`
* URL name: `'user-change_password'`
### Using Django `path()` with routers
By default, the URLs created by routers use regular expressions. This behavior can be modified by setting the `use_regex_path` argument to `False` when instantiating the router, in this case [path converters][path-converters-topic-reference] are used. For example:
router = SimpleRouter(use_regex_path=False)
The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset or `lookup_value_converter` if using path converters. For example, you can limit the lookup to valid UUIDs:
class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
lookup_field = 'my_model_id'
lookup_value_regex = '[0-9a-f]{32}'
class MyPathModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
lookup_field = 'my_model_uuid'
lookup_value_converter = 'uuid'
Note that path converters will be used on all URLs registered in the router, including viewset actions.
# API Guide
## SimpleRouter
@ -160,19 +178,13 @@ This router includes routes for the standard set of `list`, `create`, `retrieve`
<tr><td>{prefix}/{lookup}/{url_path}/</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=True)` decorated method</td><td>{basename}-{url_name}</td></tr>
</table>
By default the URLs created by `SimpleRouter` are appended with a trailing slash.
By default, the URLs created by `SimpleRouter` are appended with a trailing slash.
This behavior can be modified by setting the `trailing_slash` argument to `False` when instantiating the router. For example:
router = SimpleRouter(trailing_slash=False)
Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.
The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs:
class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
lookup_field = 'my_model_id'
lookup_value_regex = '[0-9a-f]{32}'
## DefaultRouter
This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes.
@ -338,5 +350,6 @@ 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
[path-converters-topic-reference]: https://docs.djangoproject.com/en/2.0/topics/http/urls/#path-converters

View File

@ -9,6 +9,23 @@ source:
>
> &mdash; Heroku, [JSON Schema for the Heroku Platform API][cite]
---
**Deprecation notice:**
REST framework's built-in support for generating OpenAPI schemas is
**deprecated** in favor of 3rd party packages that can provide this
functionality instead. The built-in support will be moved into a separate
package and then subsequently retired over the next releases.
As a full-fledged replacement, we recommend the [drf-spectacular] package.
It has extensive support for generating OpenAPI 3 schemas from
REST framework APIs, with both automatic and customisable options available.
For further information please refer to
[Documenting your API](../topics/documenting-your-api.md#drf-spectacular).
---
API schemas are a useful tool that allow for a range of use cases, including
generating reference documentation, or driving dynamic client libraries that
can interact with your API.
@ -39,10 +56,11 @@ The following sections explain more.
### Install dependencies
pip install pyyaml uritemplate
pip install pyyaml uritemplate inflection
* `pyyaml` is used to generate schema into YAML-based OpenAPI format.
* `uritemplate` is used internally to get parameters in path.
* `inflection` is used to pluralize operations more appropriately in the list endpoints.
### Generating a static schema with the `generateschema` management command
@ -77,11 +95,13 @@ urlpatterns = [
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
# * `title` and `description` parameters are passed to `SchemaGenerator`.
# * Provide view name for use with `reverse()`.
path('openapi', get_schema_view(
title="Your Project",
description="API for all things …",
version="1.0.0"
), name='openapi-schema'),
path(
"openapi",
get_schema_view(
title="Your Project", description="API for all things …", version="1.0.0"
),
name="openapi-schema",
),
# ...
]
```
@ -122,6 +142,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 +186,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:
@ -241,11 +262,13 @@ class CustomSchema(AutoSchema):
"""
AutoSchema subclass using schema_extra_info on the view.
"""
...
class CustomView(APIView):
schema = CustomSchema()
schema_extra_info = ... some extra info ...
schema_extra_info = ... # some extra info
```
Here, the `AutoSchema` subclass goes looking for `schema_extra_info` on the
@ -260,10 +283,13 @@ class BaseSchema(AutoSchema):
"""
AutoSchema subclass that knows how to use extra_info.
"""
...
class CustomSchema(BaseSchema):
extra_info = ... some extra info ...
extra_info = ... # some extra info
class CustomView(APIView):
schema = CustomSchema()
@ -284,15 +310,14 @@ class CustomSchema(BaseSchema):
self.extra_info = kwargs.pop("extra_info")
super().__init__(**kwargs)
class CustomView(APIView):
schema = CustomSchema(
extra_info=... some extra info ...
)
schema = CustomSchema(extra_info=...) # some extra info
```
This saves you having to create a custom subclass per-view for a commonly used option.
Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for
Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for
the more commonly needed options do.
### `AutoSchema` methods
@ -300,7 +325,7 @@ the more commonly needed options do.
#### `get_components()`
Generates the OpenAPI components that describe request and response bodies,
deriving their properties from the serializer.
deriving their properties from the serializer.
Returns a dictionary mapping the component name to the generated
representation. By default this has just a single pair but you may override
@ -313,6 +338,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 +405,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 +451,7 @@ If your views have related customizations that are needed frequently, you can
create a base `AutoSchema` subclass for your project that takes additional
`__init__()` kwargs to save subclassing `AutoSchema` for each view.
[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api
[openapi]: https://github.com/OAI/OpenAPI-Specification
[openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions
[openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject
@ -417,3 +462,4 @@ create a base `AutoSchema` subclass for your project that takes additional
[openapi-generator]: https://github.com/OpenAPITools/openapi-generator
[swagger-codegen]: https://github.com/swagger-api/swagger-codegen
[info-object]: https://swagger.io/specification/#infoObject
[drf-spectacular]: https://drf-spectacular.readthedocs.io/en/latest/readme.html

View File

@ -116,7 +116,7 @@ Calling `.save()` will either create a new instance, or update an existing insta
# .save() will update the existing `comment` instance.
serializer = CommentSerializer(comment, data=data)
Both the `.create()` and `.update()` methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.
Both the `.create()` and `.update()` methods are optional. You can implement either none, one, or both of them, depending on the use-case for your serializer class.
#### Passing additional attributes to `.save()`
@ -226,14 +226,14 @@ Individual fields on a serializer can include validators, by declaring them on t
raise serializers.ValidationError('Not a multiple of ten')
class GameRecord(serializers.Serializer):
score = IntegerField(validators=[multiple_of_ten])
score = serializers.IntegerField(validators=[multiple_of_ten])
...
Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner `Meta` class, like so:
class EventSerializer(serializers.Serializer):
name = serializers.CharField()
room_number = serializers.IntegerField(choices=[101, 102, 103, 201])
room_number = serializers.ChoiceField(choices=[101, 102, 103, 201])
date = serializers.DateField()
class Meta:
@ -524,6 +524,7 @@ You can add extra fields to a `ModelSerializer` or override the default fields b
class Meta:
model = Account
fields = ['url', 'groups']
Extra fields can correspond to any property or callable on the model.
@ -593,15 +594,15 @@ The ModelSerializer class also exposes an API that you can override in order to
Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.
### `.serializer_field_mapping`
### `serializer_field_mapping`
A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
### `.serializer_related_field`
### `serializer_related_field`
This property should be the serializer field class, that is used for relational fields by default.
For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`.
For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`.
For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`.
@ -621,13 +622,13 @@ Defaults to `serializers.ChoiceField`
The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`.
### `.build_standard_field(self, field_name, model_field)`
### `build_standard_field(self, field_name, model_field)`
Called to generate a serializer field that maps to a standard model field.
The default implementation returns a serializer class based on the `serializer_field_mapping` attribute.
### `.build_relational_field(self, field_name, relation_info)`
### `build_relational_field(self, field_name, relation_info)`
Called to generate a serializer field that maps to a relational model field.
@ -635,7 +636,7 @@ The default implementation returns a serializer class based on the `serializer_r
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
### `.build_nested_field(self, field_name, relation_info, nested_depth)`
### `build_nested_field(self, field_name, relation_info, nested_depth)`
Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set.
@ -645,17 +646,17 @@ The `nested_depth` will be the value of the `depth` option, minus one.
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
### `.build_property_field(self, field_name, model_class)`
### `build_property_field(self, field_name, model_class)`
Called to generate a serializer field that maps to a property or zero-argument method on the model class.
The default implementation returns a `ReadOnlyField` class.
### `.build_url_field(self, field_name, model_class)`
### `build_url_field(self, field_name, model_class)`
Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class.
### `.build_unknown_field(self, field_name, model_class)`
### `build_unknown_field(self, field_name, model_class)`
Called when the field name did not map to any model field or model property.
The default implementation raises an error, although subclasses may customize this behavior.
@ -755,6 +756,14 @@ The following argument can also be passed to a `ListSerializer` field or a seria
This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
### `max_length`
This is `None` by default, but can be set to a positive integer if you want to validate 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 validate 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:
@ -836,8 +845,6 @@ Here's an example of how you might choose to implement multiple updates:
class Meta:
list_serializer_class = BookListSerializer
It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the `allow_add_remove` behavior that was present in REST framework 2.
#### Customizing ListSerializer initialization
When a serializer with `many=True` is instantiated, we need to determine which arguments and keyword arguments should be passed to the `.__init__()` method for both the child `Serializer` class, and for the parent `ListSerializer` class.
@ -877,7 +884,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 +908,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 +916,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 +947,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 +967,7 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.
The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
The following class is an example of a generic serializer that can handle coercing arbitrary complex objects into primitive representations.
class ObjectSerializer(serializers.BaseSerializer):
"""
@ -1012,7 +1019,7 @@ Some reasons this might be useful include...
The signatures for these methods are as follows:
#### `.to_representation(self, instance)`
#### `to_representation(self, instance)`
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
@ -1024,7 +1031,7 @@ May be overridden in order to modify the representation style. For example:
ret['username'] = ret['username'].lower()
return ret
#### ``.to_internal_value(self, data)``
#### ``to_internal_value(self, data)``
Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
@ -1087,7 +1094,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 +1187,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

@ -163,6 +163,12 @@ The string that should used for any versioning parameters, such as in the media
Default: `'version'`
#### DEFAULT_VERSIONING_CLASS
The default versioning scheme to use.
Default: `None`
---
## Authentication settings
@ -454,4 +460,4 @@ Default: `None`
[cite]: https://www.python.org/dev/peps/pep-0020/
[rfc4627]: https://www.ietf.org/rfc/rfc4627.txt
[heroku-minified-json]: https://github.com/interagent/http-api-design#keep-json-minified-in-all-responses
[strftime]: https://docs.python.org/3/library/time.html#time.strftime
[strftime]: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

View File

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

View File

@ -25,9 +25,12 @@ The `APIRequestFactory` class supports an almost identical API to Django's stand
factory = APIRequestFactory()
request = factory.post('/notes/', {'title': 'new idea'})
# Using the standard RequestFactory API to encode JSON data
request = factory.post('/notes/', {'title': 'new idea'}, content_type='application/json')
#### Using the `format` argument
Methods which create a request body, such as `post`, `put` and `patch`, include a `format` argument, which make it easy to generate requests using a content type other than multipart form data. For example:
Methods which create a request body, such as `post`, `put` and `patch`, include a `format` argument, which make it easy to generate requests using a wide set of request formats. When using this argument, the factory will select an appropriate renderer and its configured `content_type`. For example:
# Create a JSON POST request
factory = APIRequestFactory()
@ -41,7 +44,7 @@ To support a wider set of request formats, or change the default format, [see th
If you need to explicitly encode the request body, you can do so by setting the `content_type` flag. For example:
request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
request = factory.post('/notes/', yaml.dump({'title': 'new idea'}), content_type='application/yaml')
#### PUT and PATCH with form data
@ -234,7 +237,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 +262,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 +302,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 +416,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.
@ -41,14 +45,14 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C
}
}
The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period.
The rates used in `DEFAULT_THROTTLE_RATES` can be specified over a period of second, minute, hour or day. The period must be specified after the `/` separator using `s`, `m`, `h` or `d`, respectively. For increased clarity, extended units such as `second`, `minute`, `hour`, `day` or even abbreviations like `sec`, `min`, `hr` are allowed, as only the first character is relevant to identify the rate.
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]
@ -79,7 +83,7 @@ Throttle classes set in this way will override any viewset level class settings.
}
return Response(content)
## How clients are identified
## 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.
@ -102,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.
---
# API Reference
@ -210,3 +220,4 @@ 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
[race]: https://en.wikipedia.org/wiki/Race_condition#Data_race

View File

@ -20,7 +20,7 @@ Validation in Django REST framework serializers is handled a little differently
With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
* It introduces a proper separation of concerns, making your code behavior more obvious.
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.
When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using `Serializer` classes instead, then you need to define the validation rules explicitly.
@ -48,12 +48,12 @@ If we open up the Django shell using `manage.py shell` we can now
CustomerReportSerializer():
id = IntegerField(label='ID', read_only=True)
time_raised = DateTimeField(read_only=True)
reference = CharField(max_length=20, validators=[<UniqueValidator(queryset=CustomerReportRecord.objects.all())>])
reference = CharField(max_length=20, validators=[UniqueValidator(queryset=CustomerReportRecord.objects.all())])
description = CharField(style={'type': 'textarea'})
The interesting bit here is the `reference` field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.
Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.
Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below. REST framework validators, like their Django counterparts, implement the `__eq__` method, allowing you to compare instances for equality.
---
@ -164,14 +164,18 @@ If you want the date field to be entirely hidden from the user, then use `Hidden
---
---
**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request).
---
# Advanced field defaults
Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that *is* available as input to the validator.
For this purposes use `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation.
Two patterns that you may want to use for this sort of validation include:
* Using `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation.
* Using a standard field with `read_only=True`, but that also includes a `default=…` argument. This field *will* be used in the serializer output representation, but cannot be set directly by the user.
**Note:** Using a `read_only=True` field is excluded from writable fields so it won't use a `default=…` argument. Look [3.8 announcement](https://www.django-rest-framework.org/community/3.8-announcement/#altered-the-behaviour-of-read_only-plus-default-on-field).
REST framework includes a couple of defaults that may be useful in this context.
@ -183,7 +187,7 @@ A default class that can be used to represent the current user. In order to use
default=serializers.CurrentUserDefault()
)
#### CreateOnlyDefault
#### CreateOnlyDefault
A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted.
@ -208,7 +212,7 @@ by specifying an empty list for the serializer `Meta.validators` attribute.
By default "unique together" validation enforces that all fields be
`required=True`. In some cases, you might want to explicit apply
`required=False` to one of the fields, in which case the desired behaviour
`required=False` to one of the fields, in which case the desired behavior
of the validation is ambiguous.
In this case you will typically need to exclude the validator from the
@ -238,7 +242,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
@ -295,13 +299,14 @@ To write a class-based validator, use the `__call__` method. Class-based validat
In some advanced cases you might want a validator to be passed the serializer
field it is being used with as additional context. You can do so by setting
a `requires_context = True` attribute on the validator. The `__call__` method
a `requires_context = True` attribute on the validator class. The `__call__` method
will then be called with the `serializer_field`
or `serializer` as an additional argument.
requires_context = True
class MultipleOf:
requires_context = True
def __call__(self, value, serializer_field):
...
def __call__(self, value, serializer_field):
...
[cite]: https://docs.djangoproject.com/en/stable/ref/validators/

View File

@ -145,6 +145,7 @@ REST framework also allows you to work with regular function based views. It pr
The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view()
def hello_world(request):
@ -152,7 +153,7 @@ The core of this functionality is the `api_view` decorator, which takes a list o
This view will use the default renderers, parsers, authentication classes etc specified in the [settings].
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behaviour, specify which methods the view allows, like so:
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so:
@api_view(['GET', 'POST'])
def hello_world(request):

View File

@ -116,7 +116,7 @@ During dispatch, the following attributes are available on the `ViewSet`.
* `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`.
* `description` - the display description for the individual view of a viewset.
You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
You may inspect these attributes to adjust behavior based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
def get_permissions(self):
"""
@ -125,9 +125,11 @@ 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]
**Note**: the `action` attribute is not available in the `get_parsers`, `get_authenticators` and `get_content_negotiator` methods, as it is set _after_ they are called in the framework lifecycle. If you override one of these methods and try to access the `action` attribute in them, you will get an `AttributeError` error.
## Marking extra actions for routing
If you have ad-hoc methods that should be routable, you can mark them as such with the `@action` decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the `detail` argument to `True` or `False`. The router will configure its URL patterns accordingly. e.g., the `DefaultRouter` will configure detail actions to contain `pk` in their URL patterns.
@ -178,6 +180,13 @@ The `action` decorator will route `GET` requests by default, but may also accept
def unset_password(self, request, pk=None):
...
Argument `methods` also supports HTTP methods defined as [HTTPMethod](https://docs.python.org/3/library/http.html#http.HTTPMethod). Example below is identical to the one above:
from http import HTTPMethod
@action(detail=True, methods=[HTTPMethod.POST, HTTPMethod.DELETE])
def unset_password(self, request, pk=None):
...
The decorator allows you to override any viewset-level configuration such as `permission_classes`, `serializer_class`, `filter_backends`...:
@ -194,15 +203,16 @@ To view all extra actions, call the `.get_extra_actions()` method.
Extra actions can map additional HTTP methods to separate `ViewSet` methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments.
```python
@action(detail=True, methods=['put'], name='Change Password')
def password(self, request, pk=None):
"""Update the user's password."""
...
@action(detail=True, methods=["put"], name="Change Password")
def password(self, request, pk=None):
"""Update the user's password."""
...
@password.mapping.delete
def delete_password(self, request, pk=None):
"""Delete the user's password."""
...
@password.mapping.delete
def delete_password(self, request, pk=None):
"""Delete the user's password."""
...
```
## Reversing action URLs
@ -213,14 +223,14 @@ Note that the `basename` is provided by the router during `ViewSet` registration
Using the example from the previous section:
```python
>>> view.reverse_action('set-password', args=['1'])
```pycon
>>> view.reverse_action("set-password", args=["1"])
'http://localhost:8000/api/users/1/set_password'
```
Alternatively, you can use the `url_name` attribute set by the `@action` decorator.
```python
```pycon
>>> view.reverse_action(view.set_password.url_name, args=['1'])
'http://localhost:8000/api/users/1/set_password'
```
@ -247,7 +257,7 @@ In order to use a `GenericViewSet` class you'll override the class and either mi
The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
#### Example
@ -303,7 +313,7 @@ You may need to provide custom `ViewSet` classes that do not have the full set o
To create a base viewset class that provides `create`, `list` and `retrieve` operations, inherit from `GenericViewSet`, and mixin the required actions:
from rest_framework import mixins
from rest_framework import mixins, viewsets
class CreateListRetrieveViewSet(mixins.CreateModelMixin,
mixins.ListModelMixin,

View File

@ -24,7 +24,7 @@ Notable features of this new release include:
* Support for overriding how validation errors are handled by your API.
* A metadata API that allows you to customize how `OPTIONS` requests are handled by your API.
* A more compact JSON output with unicode style encoding turned on by default.
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two [Kickstarter stretch goals](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.
@ -632,7 +632,7 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behavior in a way that did not simply lookup the field value from the object. For example...
def field_to_native(self, obj, field_name):
"""A custom read-only field that returns the class name."""

View File

@ -41,8 +41,8 @@ update your REST framework settings to include `DEFAULT_SCHEMA_CLASS` explicitly
```python
REST_FRAMEWORK = {
...
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
...: ...,
"DEFAULT_SCHEMA_CLASS": "rest_framework.schemas.coreapi.AutoSchema",
}
```
@ -74,10 +74,11 @@ urlpatterns = [
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
# * `title` and `description` parameters are passed to `SchemaGenerator`.
# * Provide view name for use with `reverse()`.
path('openapi', get_schema_view(
title="Your Project",
description="API for all things …"
), name='openapi-schema'),
path(
"openapi",
get_schema_view(title="Your Project", description="API for all things …"),
name="openapi-schema",
),
# ...
]
```
@ -142,6 +143,6 @@ continued development by **[signing up for a paid plan][funding]**.
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), and [Lights On Software](https://lightsonsoftware.com).*
[legacy-core-api-docs]:https://github.com/encode/django-rest-framework/blob/master/docs/coreapi/index.md
[legacy-core-api-docs]:https://github.com/encode/django-rest-framework/blob/3.14.0/docs/coreapi/index.md
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[funding]: funding.md

View File

@ -43,10 +43,11 @@ be extracted from the class docstring:
```python
class DocStringExampleListView(APIView):
"""
get: A description of my GET operation.
post: A description of my POST operation.
"""
"""
get: A description of my GET operation.
post: A description of my POST operation.
"""
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get(self, request, *args, **kwargs):
@ -63,7 +64,7 @@ In some circumstances a Validator class or a Default class may need to access th
* Uniqueness validators need to be able to determine the name of the field to which they are applied, in order to run an appropriate database query.
* The `CurrentUserDefault` needs to be able to determine the context with which the serializer was instantiated, in order to return the current user instance.
Previous our approach to this was that implementations could include a `set_context` method, which would be called prior to validation. However this approach had issues with potential race conditions. We have now move this approach into a pending deprecation state. It will continue to function, but will be escalated to a deprecated state in 3.12, and removed entirely in 3.13.
Our previous approach to this was that implementations could include a `set_context` method, which would be called prior to validation. However this approach had issues with potential race conditions. We have now move this approach into a pending deprecation state. It will continue to function, but will be escalated to a deprecated state in 3.12, and removed entirely in 3.13.
Instead, validators or defaults which require the serializer context, should include a `requires_context = True` attribute on the class.

View File

@ -30,18 +30,18 @@ in the URL path.
For example...
Method | Path | Tags
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']`
`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'])
schema = AutoSchema(tags=["users", "orders"])
...
```
@ -68,7 +68,7 @@ may be overridden if needed](https://www.django-rest-framework.org/api-guide/sch
```python
class MyOrders(APIView):
schema = AutoSchema(component_name="OrderDetails")
schema = AutoSchema(component_name="OrderDetails")
```
## More Public API
@ -118,10 +118,11 @@ class SitesSearchView(generics.ListAPIView):
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']
search_fields = ["site_name", "location__region", "location__country"]
```
### Searches against annotate fields
@ -135,14 +136,25 @@ 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'))
queryset = Publisher.objects.annotate(avg_rating=Avg("book__rating"))
serializer_class = PublisherSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['avg_rating']
search_fields = ["avg_rating"]
```
---
## Deprecations
### `serializers.NullBooleanField`
`serializers.NullBooleanField` is now pending deprecation, and will be removed in 3.14.
Instead use `serializers.BooleanField` field and set `allow_null=True` which does the same thing.
---
## Funding
REST framework is a *collaboratively funded project*. If you use

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,72 @@
<style>
.promo li a {
float: left;
width: 130px;
height: 20px;
text-align: center;
margin: 10px 30px;
padding: 150px 0 0 0;
background-position: 0 50%;
background-size: 130px auto;
background-repeat: no-repeat;
font-size: 120%;
color: black;
}
.promo li {
list-style: none;
}
</style>
# Django REST framework 3.14
## Django 4.1 support
The latest release now fully supports Django 4.1, and drops support for Django 2.2.
Our requirements are now:
* Python 3.6+
* Django 4.1, 4.0, 3.2, 3.1, 3.0
## `raise_exception` argument for `is_valid` is now keyword-only.
Calling `serializer_instance.is_valid(True)` is no longer acceptable syntax.
If you'd like to use the `raise_exception` argument, you must use it as a
keyword argument.
See Pull Request [#7952](https://github.com/encode/django-rest-framework/pull/7952) for more details.
## `ManyRelatedField` supports returning the default when the source attribute doesn't exist.
Previously, if you used a serializer field with `many=True` with a dot notated source field
that didn't exist, it would raise an `AttributeError`. Now it will return the default or be
skipped depending on the other arguments.
See Pull Request [#7574](https://github.com/encode/django-rest-framework/pull/7574) for more details.
## Make Open API `get_reference` public.
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
## Change semantic of OR of two permission classes.
When OR-ing two permissions, the request has to pass either class's `has_permission() and has_object_permission()`.
Previously, both class's `has_permission()` was ignored when OR-ing two permissions together.
See Pull Request [#7522](https://github.com/encode/django-rest-framework/pull/7522) for more details.
## Minor fixes and improvements
There are a number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing.
---
## Deprecations
### `serializers.NullBooleanField`
`serializers.NullBooleanField` was moved to pending deprecation in 3.12, and deprecated in 3.13. It has now been removed from the core framework.
Instead use `serializers.BooleanField` field and set `allow_null=True` which does the same thing.

View File

@ -0,0 +1,50 @@
<style>
.promo li a {
float: left;
width: 130px;
height: 20px;
text-align: center;
margin: 10px 30px;
padding: 150px 0 0 0;
background-position: 0 50%;
background-size: 130px auto;
background-repeat: no-repeat;
font-size: 120%;
color: black;
}
.promo li {
list-style: none;
}
</style>
# Django REST framework 3.15
At the Internet, on March 15th, 2024, with 176 commits by 138 authors, we are happy to announce the release of Django REST framework 3.15.
## Django 5.0 and Python 3.12 support
The latest release now fully supports Django 5.0 and Python 3.12.
The current minimum versions of Django still is 3.0 and Python 3.6.
## Primary Support of UniqueConstraint
`ModelSerializer` generates validators for [UniqueConstraint](https://docs.djangoproject.com/en/4.0/ref/models/constraints/#uniqueconstraint) (both UniqueValidator and UniqueTogetherValidator)
## SimpleRouter non-regex matching support
By default the URLs created by `SimpleRouter` use regular expressions. This behavior can be modified by setting the `use_regex_path` argument to `False` when instantiating the router.
## ZoneInfo as the primary source of timezone data
Dependency on pytz has been removed and deprecation warnings have been added, Django will provide ZoneInfo instances as long as USE_DEPRECATED_PYTZ is not enabled. More info on the migration can be found [in this guide](https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html).
## Align `SearchFilter` behaviour to `django.contrib.admin` search
Searches now may contain _quoted phrases_ with spaces, each phrase is considered as a single search term, and it will raise a validation error if any null-character is provided in search. See the [Filtering API guide](../api-guide/filtering.md) for more information.
## Other fixes and improvements
There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behaviour.
See the [release notes](release-notes.md) page for a complete listing.

View File

@ -0,0 +1,42 @@
<style>
.promo li a {
float: left;
width: 130px;
height: 20px;
text-align: center;
margin: 10px 30px;
padding: 150px 0 0 0;
background-position: 0 50%;
background-size: 130px auto;
background-repeat: no-repeat;
font-size: 120%;
color: black;
}
.promo li {
list-style: none;
}
</style>
# Django REST framework 3.16
At the Internet, on March 28th, 2025, we are happy to announce the release of Django REST framework 3.16.
## Updated Django and Python support
The latest release now fully supports Django 5.1 and the upcoming 5.2 LTS as well as Python 3.13.
The current minimum versions of Django is now 4.2 and Python 3.9.
## Django LoginRequiredMiddleware
The new `LoginRequiredMiddleware` introduced by Django 5.1 can now be used alongside Django REST Framework, however it is not honored for API views as an equivalent behaviour can be configured via `DEFAULT_AUTHENTICATION_CLASSES`. See [our dedicated section](../api-guide/authentication.md#django-51-loginrequiredmiddleware) in the docs for more information.
## Improved support for UniqueConstraint
The generation of validators for [UniqueConstraint](https://docs.djangoproject.com/en/stable/ref/models/constraints/#uniqueconstraint) has been improved to support better nullable fields and constraints with conditions.
## Other fixes and improvements
There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behaviour.
See the [release notes](release-notes.md) page for a complete listing.

View File

@ -64,7 +64,7 @@ These are a little subtle and probably won't affect most users, but are worth un
### ManyToMany fields and blank=True
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
As a follow-up to this we are now able to properly mirror the behavior of Django's `ModelForm` with respect to how many-to-many fields are validated.

View File

@ -38,7 +38,7 @@ The AJAX based support for the browsable API means that there are a number of in
* To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.
* The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class][accept-headers].
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.

View File

@ -89,7 +89,7 @@ Name | Support | PyPI pa
---------------------------------|-------------------------------------|--------------------------------
[Core JSON][core-json] | Schema generation & client support. | Built-in support in `coreapi`.
[Swagger / OpenAPI][swagger] | Schema generation & client support. | The `openapi-codec` package.
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
[API Blueprint][api-blueprint] | Not yet available. | Not yet available.
---
@ -187,7 +187,7 @@ The full set of itemized release notes [are available here][release-notes].
[api-blueprint]: https://apiblueprint.org/
[tut-7]: ../tutorial/7-schemas-and-client-libraries/
[schema-generation]: ../api-guide/schemas/
[api-clients]: ../topics/api-clients.md
[api-clients]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md
[milestone]: https://github.com/encode/django-rest-framework/milestone/35
[release-notes]: release-notes#34
[metadata]: ../api-guide/metadata/#custom-metadata-classes

View File

@ -64,14 +64,10 @@ from rest_framework.schemas import get_schema_view
from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer
schema_view = get_schema_view(
title='Example API',
renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]
title="Example API", renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]
)
urlpatterns = [
path('swagger/', schema_view),
...
]
urlpatterns = [path("swagger/", schema_view), ...]
```
There have been a large number of fixes to the schema generation. These should

View File

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

View File

@ -89,7 +89,7 @@ for a complete listing.
We're currently working towards moving to using [OpenAPI][openapi] as our default schema output. We'll also be revisiting our API documentation generation and client libraries.
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
[funding]: funding.md
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886

View File

@ -65,15 +65,12 @@ from rest_framework.renderers import JSONOpenAPIRenderer
from django.urls import path
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/',
renderer_classes=[JSONOpenAPIRenderer]
title="Server Monitoring API",
url="https://www.example.org/api/",
renderer_classes=[JSONOpenAPIRenderer],
)
urlpatterns = [
path('schema.json', schema_view),
...
]
urlpatterns = [path("schema.json", schema_view), ...]
```
And here's how you can use the `generateschema` management command:
@ -110,7 +107,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

@ -4,7 +4,9 @@
>
> &mdash; [Tim Berners-Lee][cite]
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 its lifespan we consider Django REST framework to be feature-complete. We focus on pull requests that track the continued development of Django versions, and generally do not accept new features or code formatting changes.
## Community
@ -26,25 +28,8 @@ 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].
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, bugfixes, 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.
* Django REST framework is considered feature-complete. Please do not file requests to change behavior, unless it is required for security reasons or to maintain compatibility with upcoming Django or Python versions.
* Feature requests will typically be closed with a recommendation that they be implemented outside the core REST framework library (e.g. as third-party libraries). This approach allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability and great documentation.
# Development
@ -54,11 +39,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 +60,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 +72,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 +104,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
@ -208,9 +189,8 @@ If you want to draw attention to a note or warning, use a pair of enclosing line
[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/
[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

@ -1,398 +1,398 @@
<script>
// Imperfect, but easier to fit in with the existing docs build.
// Hyperlinks should point directly to the "fund." subdomain, but this'll
// handle the nav bar links without requiring any docs build changes for the moment.
if (window.location.hostname == "www.django-rest-framework.org") {
window.location.replace("https://fund.django-rest-framework.org/topics/funding/");
}
</script>
<style>
.promo li a {
float: left;
width: 130px;
height: 20px;
text-align: center;
margin: 10px 30px;
padding: 150px 0 0 0;
background-position: 0 50%;
background-size: 130px auto;
background-repeat: no-repeat;
font-size: 120%;
color: black;
}
.promo li {
list-style: none;
}
.chart {
background-color: #e3e3e3;
background: -webkit-linear-gradient(top, #fff 0, #e3e3e3 100%);
border: 1px solid #E6E6E6;
border-radius: 5px;
box-shadow: 0px 0px 2px 0px rgba(181, 181, 181, 0.3);
padding: 40px 0px 5px;
position: relative;
text-align: center;
width: 97%;
min-height: 255px;
position: relative;
top: 37px;
margin-bottom: 20px
}
.quantity {
text-align: center
}
.dollar {
font-size: 19px;
position: relative;
top: -18px;
}
.price {
font-size: 49px;
}
.period {
font-size: 17px;
position: relative;
top: -8px;
margin-left: 4px;
}
.plan-name {
text-align: center;
font-size: 20px;
font-weight: 400;
color: #777;
border-bottom: 1px solid #d5d5d5;
padding-bottom: 15px;
width: 90%;
margin: 0 auto;
margin-top: 8px;
}
.specs {
margin-top: 20px;
min-height: 130px;
}
.specs.freelancer {
min-height: 0px;
}
.spec {
font-size: 15px;
color: #474747;
text-align: center;
font-weight: 300;
margin-bottom: 13px;
}
.variable {
color: #1FBEE7;
font-weight: 400;
}
form.signup {
margin-top: 35px
}
.clear-promo {
padding-top: 30px
}
#main-content h1:first-of-type {
margin: 0 0 50px;
font-size: 60px;
font-weight: 200;
text-align: center
}
#main-content {
padding-top: 10px; line-height: 23px
}
#main-content li {
line-height: 23px
}
</style>
# Funding
If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan.
**We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.**
Signing up for a paid plan will:
* Directly contribute to faster releases, more features, and higher quality software.
* Allow more time to be invested in documentation, issue triage, and community support.
* Safeguard the future development of REST framework.
REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development.
---
## What funding has enabled so far
* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/).
* Tom Christie, the creator of Django REST framework, working on the project full-time.
* Around 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time.
* A community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship.
* Contracting development time for the work on the JavaScript client library and API documentation tooling.
---
## What 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.
* 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.
Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.
---
## What our sponsors and users say
> As a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem.
>
> &mdash; José Padilla, Django REST framework contributor
&nbsp;
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
>
> &mdash; Filipe Ximenes, Vinta Software
&nbsp;
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.
>
> &mdash; Andrew Conti, Django REST framework user
---
## Individual plan
This subscription is recommended for individuals with an interest in seeing REST framework continue to&nbsp;improve.
If you are using REST framework as a full-time employee, consider recommending that your company takes out a [corporate&nbsp;plan](#corporate-plans).
<div class="pricing">
<div class="span4">
<div class="chart first">
<div class="quantity">
<span class="dollar">{{ symbol }}</span>
<span class="price">{{ rates.personal1 }}</span>
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
</div>
<div class="plan-name">Individual</div>
<div class="specs freelancer">
<div class="spec">
Support ongoing development
</div>
<div class="spec">
Credited on the site
</div>
</div>
<form class="signup" action="/signup/{{ currency }}-{{ rates.personal1 }}/" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public }}"
data-amount="{{ stripe_amounts.personal1 }}"
data-name="Django REST framework"
data-description="Individual"
data-currency="{{ currency }}"
data-allow-remember-me=false
data-billing-address=true
data-label='Sign up'
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
</script>
</form>
</div>
</div>
</div>
<div style="clear: both; padding-top: 50px"></div>
*Billing is monthly and you can cancel at any time.*
---
## Corporate plans
These subscriptions are recommended for companies and organizations using REST framework either publicly or privately.
In exchange for funding you'll also receive advertising space on our site, allowing you to **promote your company or product to many tens of thousands of developers worldwide**.
Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.
<div class="pricing">
<div class="span4">
<div class="chart first">
<div class="quantity">
<span class="dollar">{{ symbol }}</span>
<span class="price">{{ rates.corporate1 }}</span>
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
</div>
<div class="plan-name">Basic</div>
<div class="specs startup">
<div class="spec">
Support ongoing development
</div>
<div class="spec">
<span class="variable">Funding page</span> ad placement
</div>
</div>
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate1 }}/" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public }}"
data-amount="{{ stripe_amounts.corporate1 }}"
data-name="Django REST framework"
data-description="Basic"
data-currency="{{ currency }}"
data-allow-remember-me=false
data-billing-address=true
data-label='Sign up'
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
</script>
</form>
</div>
</div>
<div class="span4">
<div class="chart">
<div class="quantity">
<span class="dollar">{{ symbol }}</span>
<span class="price">{{ rates.corporate2 }}</span>
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
</div>
<div class="plan-name">Professional</div>
<div class="specs">
<div class="spec">
Support ongoing development
</div>
<div class="spec">
<span class="variable">Sidebar</span> ad placement
</div>
<div class="spec">
<span class="variable">Priority support</span> for your engineers
</div>
</div>
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate2 }}/" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public }}"
data-amount="{{ stripe_amounts.corporate2 }}"
data-name="Django REST framework"
data-description="Professional"
data-currency="{{ currency }}"
data-allow-remember-me=false
data-billing-address=true
data-label='Sign up'
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
</script>
</form>
</div>
</div>
<div class="span4">
<div class="chart last">
<div class="quantity">
<span class="dollar">{{ symbol }}</span>
<span class="price">{{ rates.corporate3 }}</span>
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
</div>
<div class="plan-name">Premium</div>
<div class="specs">
<div class="spec">
Support ongoing development
</div>
<div class="spec">
<span class="variable">Homepage</span> ad placement
</div>
<div class="spec">
<span class="variable">Sidebar</span> ad placement
</div>
<div class="spec">
<span class="variable">Priority support</span> for your engineers
</div>
</div>
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate3 }}/" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public }}"
data-amount="{{ stripe_amounts.corporate3 }}"
data-name="Django REST framework"
data-description="Premium"
data-currency="{{ currency }}"
data-allow-remember-me=false
data-billing-address=true
data-label='Sign up'
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
</script>
</form>
</div>
</div>
</div>
<div style="clear: both; padding-top: 50px"></div>
*Billing is monthly and you can cancel at any time.*
Once you've signed up, we will contact you via email and arrange your ad placements on the site.
For further enquires please contact <a href=mailto:funding@django-rest-framework.org>funding@django-rest-framework.org</a>.
---
## Accountability
In an effort to keep the project as transparent as possible, we are releasing [monthly progress reports](https://www.encode.io/reports/march-2018/) and regularly include financial reports and cost breakdowns.
<!-- Begin MailChimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
<style type="text/css">
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="//encode.us13.list-manage.com/subscribe/post?u=b6b66bb5e4c7cb484a85c8dd7&amp;id=e382ef68ef" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<div id="mc_embed_signup_scroll">
<h2>Stay up to date, with our monthly progress reports...</h2>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address </label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_b6b66bb5e4c7cb484a85c8dd7_e382ef68ef" tabindex="-1" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</div>
</form>
</div>
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!--End mc_embed_signup-->
---
## Frequently asked questions
**Q: Can you issue monthly invoices?**
A: Yes, we are happy to issue monthly invoices. Please just <a href=mailto:funding@django-rest-framework.org>email us</a> and let us know who to issue the invoice to (name and address) and which email address to send it to each month.
**Q: Does sponsorship include VAT?**
A: Sponsorship is VAT exempt.
**Q: Do I have to sign up for a certain time period?**
A: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime.
**Q: Can I pay yearly? Can I pay upfront fox X amount of months at a time?**
A: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution.
**Q: Are you only looking for corporate sponsors?**
A: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support.
---
## Our sponsors
<div id="fundingInclude"></div>
<script src="https://fund.django-rest-framework.org/funding_include.js"></script>
<script>
// Imperfect, but easier to fit in with the existing docs build.
// Hyperlinks should point directly to the "fund." subdomain, but this'll
// handle the nav bar links without requiring any docs build changes for the moment.
if (window.location.hostname == "www.django-rest-framework.org") {
window.location.replace("https://fund.django-rest-framework.org/topics/funding/");
}
</script>
<style>
.promo li a {
float: left;
width: 130px;
height: 20px;
text-align: center;
margin: 10px 30px;
padding: 150px 0 0 0;
background-position: 0 50%;
background-size: 130px auto;
background-repeat: no-repeat;
font-size: 120%;
color: black;
}
.promo li {
list-style: none;
}
.chart {
background-color: #e3e3e3;
background: -webkit-linear-gradient(top, #fff 0, #e3e3e3 100%);
border: 1px solid #E6E6E6;
border-radius: 5px;
box-shadow: 0px 0px 2px 0px rgba(181, 181, 181, 0.3);
padding: 40px 0px 5px;
position: relative;
text-align: center;
width: 97%;
min-height: 255px;
position: relative;
top: 37px;
margin-bottom: 20px
}
.quantity {
text-align: center
}
.dollar {
font-size: 19px;
position: relative;
top: -18px;
}
.price {
font-size: 49px;
}
.period {
font-size: 17px;
position: relative;
top: -8px;
margin-left: 4px;
}
.plan-name {
text-align: center;
font-size: 20px;
font-weight: 400;
color: #777;
border-bottom: 1px solid #d5d5d5;
padding-bottom: 15px;
width: 90%;
margin: 0 auto;
margin-top: 8px;
}
.specs {
margin-top: 20px;
min-height: 130px;
}
.specs.freelancer {
min-height: 0px;
}
.spec {
font-size: 15px;
color: #474747;
text-align: center;
font-weight: 300;
margin-bottom: 13px;
}
.variable {
color: #1FBEE7;
font-weight: 400;
}
form.signup {
margin-top: 35px
}
.clear-promo {
padding-top: 30px
}
#main-content h1:first-of-type {
margin: 0 0 50px;
font-size: 60px;
font-weight: 200;
text-align: center
}
#main-content {
padding-top: 10px; line-height: 23px
}
#main-content li {
line-height: 23px
}
</style>
# Funding
If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan.
**We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.**
Signing up for a paid plan will:
* Directly contribute to faster releases, more features, and higher quality software.
* Allow more time to be invested in documentation, issue triage, and community support.
* Safeguard the future development of REST framework.
REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development.
---
## What funding has enabled so far
* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/).
* Tom Christie, the creator of Django REST framework, working on the project full-time.
* Around 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time.
* A community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship.
* Contracting development time for the work on the JavaScript client library and API documentation tooling.
---
## What 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.
* 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.
Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.
---
## What our sponsors and users say
> As a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem.
>
> &mdash; José Padilla, Django REST framework contributor
&nbsp;
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
>
> &mdash; Filipe Ximenes, Vinta Software
&nbsp;
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.
>
> &mdash; Andrew Conti, Django REST framework user
---
## Individual plan
This subscription is recommended for individuals with an interest in seeing REST framework continue to&nbsp;improve.
If you are using REST framework as a full-time employee, consider recommending that your company takes out a [corporate&nbsp;plan](#corporate-plans).
<div class="pricing">
<div class="span4">
<div class="chart first">
<div class="quantity">
<span class="dollar">{{ symbol }}</span>
<span class="price">{{ rates.personal1 }}</span>
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
</div>
<div class="plan-name">Individual</div>
<div class="specs freelancer">
<div class="spec">
Support ongoing development
</div>
<div class="spec">
Credited on the site
</div>
</div>
<form class="signup" action="/signup/{{ currency }}-{{ rates.personal1 }}/" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public }}"
data-amount="{{ stripe_amounts.personal1 }}"
data-name="Django REST framework"
data-description="Individual"
data-currency="{{ currency }}"
data-allow-remember-me=false
data-billing-address=true
data-label='Sign up'
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
</script>
</form>
</div>
</div>
</div>
<div style="clear: both; padding-top: 50px"></div>
*Billing is monthly and you can cancel at any time.*
---
## Corporate plans
These subscriptions are recommended for companies and organizations using REST framework either publicly or privately.
In exchange for funding you'll also receive advertising space on our site, allowing you to **promote your company or product to many tens of thousands of developers worldwide**.
Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.
<div class="pricing">
<div class="span4">
<div class="chart first">
<div class="quantity">
<span class="dollar">{{ symbol }}</span>
<span class="price">{{ rates.corporate1 }}</span>
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
</div>
<div class="plan-name">Basic</div>
<div class="specs startup">
<div class="spec">
Support ongoing development
</div>
<div class="spec">
<span class="variable">Funding page</span> ad placement
</div>
</div>
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate1 }}/" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public }}"
data-amount="{{ stripe_amounts.corporate1 }}"
data-name="Django REST framework"
data-description="Basic"
data-currency="{{ currency }}"
data-allow-remember-me=false
data-billing-address=true
data-label='Sign up'
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
</script>
</form>
</div>
</div>
<div class="span4">
<div class="chart">
<div class="quantity">
<span class="dollar">{{ symbol }}</span>
<span class="price">{{ rates.corporate2 }}</span>
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
</div>
<div class="plan-name">Professional</div>
<div class="specs">
<div class="spec">
Support ongoing development
</div>
<div class="spec">
<span class="variable">Sidebar</span> ad placement
</div>
<div class="spec">
<span class="variable">Priority support</span> for your engineers
</div>
</div>
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate2 }}/" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public }}"
data-amount="{{ stripe_amounts.corporate2 }}"
data-name="Django REST framework"
data-description="Professional"
data-currency="{{ currency }}"
data-allow-remember-me=false
data-billing-address=true
data-label='Sign up'
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
</script>
</form>
</div>
</div>
<div class="span4">
<div class="chart last">
<div class="quantity">
<span class="dollar">{{ symbol }}</span>
<span class="price">{{ rates.corporate3 }}</span>
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
</div>
<div class="plan-name">Premium</div>
<div class="specs">
<div class="spec">
Support ongoing development
</div>
<div class="spec">
<span class="variable">Homepage</span> ad placement
</div>
<div class="spec">
<span class="variable">Sidebar</span> ad placement
</div>
<div class="spec">
<span class="variable">Priority support</span> for your engineers
</div>
</div>
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate3 }}/" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public }}"
data-amount="{{ stripe_amounts.corporate3 }}"
data-name="Django REST framework"
data-description="Premium"
data-currency="{{ currency }}"
data-allow-remember-me=false
data-billing-address=true
data-label='Sign up'
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
</script>
</form>
</div>
</div>
</div>
<div style="clear: both; padding-top: 50px"></div>
*Billing is monthly and you can cancel at any time.*
Once you've signed up, we will contact you via email and arrange your ad placements on the site.
For further enquires please contact <a href=mailto:funding@django-rest-framework.org>funding@django-rest-framework.org</a>.
---
## Accountability
In an effort to keep the project as transparent as possible, we are releasing [monthly progress reports](https://www.encode.io/reports/march-2018/) and regularly include financial reports and cost breakdowns.
<!-- Begin MailChimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
<style type="text/css">
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="//encode.us13.list-manage.com/subscribe/post?u=b6b66bb5e4c7cb484a85c8dd7&amp;id=e382ef68ef" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<div id="mc_embed_signup_scroll">
<h2>Stay up to date, with our monthly progress reports...</h2>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address </label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_b6b66bb5e4c7cb484a85c8dd7_e382ef68ef" tabindex="-1" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</div>
</form>
</div>
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!--End mc_embed_signup-->
---
## Frequently asked questions
**Q: Can you issue monthly invoices?**
A: Yes, we are happy to issue monthly invoices. Please just <a href=mailto:funding@django-rest-framework.org>email us</a> and let us know who to issue the invoice to (name and address) and which email address to send it to each month.
**Q: Does sponsorship include VAT?**
A: Sponsorship is VAT exempt.
**Q: Do I have to sign up for a certain time period?**
A: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime.
**Q: Can I pay yearly? Can I pay upfront fox X amount of months at a time?**
A: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution.
**Q: Are you only looking for corporate sponsors?**
A: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support.
---
## Our sponsors
<div id="fundingInclude"></div>
<script src="https://fund.django-rest-framework.org/funding_include.js"></script>

View File

@ -7,15 +7,17 @@ Looking for a new Django REST Framework related role? On this site we provide a
* [https://www.djangoproject.com/community/jobs/][djangoproject-website]
* [https://www.python.org/jobs/][python-org-jobs]
* [https://django.on-remote.com][django-on-remote]
* [https://djangogigs.com][django-gigs-com]
* [https://djangojobs.net/jobs/][django-jobs-net]
* [https://findwork.dev/django-rest-framework-jobs][findwork-dev]
* [https://www.indeed.com/q-Django-jobs.html][indeed-com]
* [https://stackoverflow.com/jobs/developer-jobs-using-django][stackoverflow-com]
* [https://stackoverflow.com/jobs/companies?tl=django][stackoverflow-com]
* [https://www.upwork.com/o/jobs/browse/skill/django-framework/][upwork-com]
* [https://www.technojobs.co.uk/django-jobs][technobjobs-co-uk]
* [https://remoteok.io/remote-django-jobs][remoteok-io]
* [https://remoteok.com/remote-django-jobs][remoteok-com]
* [https://www.remotepython.com/jobs/][remotepython-com]
* [https://www.pyjobs.com/][pyjobs-com]
Know of any other great resources for Django REST Framework jobs that are missing in our list? Please [submit a pull request][submit-pr] or [email us][anna-email].
@ -25,15 +27,17 @@ Wonder how else you can help? One of the best ways you can help Django REST Fram
[djangoproject-website]: https://www.djangoproject.com/community/jobs/
[python-org-jobs]: https://www.python.org/jobs/
[django-on-remote]: https://django.on-remote.com/
[django-gigs-com]: https://djangogigs.com
[django-jobs-net]: https://djangojobs.net/jobs/
[findwork-dev]: https://findwork.dev/django-rest-framework-jobs
[indeed-com]: https://www.indeed.com/q-Django-jobs.html
[stackoverflow-com]: https://stackoverflow.com/jobs/developer-jobs-using-django
[stackoverflow-com]: https://stackoverflow.com/jobs/companies?tl=django
[upwork-com]: https://www.upwork.com/o/jobs/browse/skill/django-framework/
[technobjobs-co-uk]: https://www.technojobs.co.uk/django-jobs
[remoteok-io]: https://remoteok.io/remote-django-jobs
[remoteok-com]: https://remoteok.com/remote-django-jobs
[remotepython-com]: https://www.remotepython.com/jobs/
[pyjobs-com]: https://www.pyjobs.com/
[drf-funding]: https://fund.django-rest-framework.org/topics/funding/
[submit-pr]: https://github.com/encode/django-rest-framework
[anna-email]: mailto:anna@django-rest-framework.org

View File

@ -13,55 +13,13 @@ The aim is to ensure that the project has a high
## Maintenance team
We have a quarterly maintenance cycle where new members may join the maintenance team. We currently cap the size of the team at 5 members, and may encourage folks to step out of the team for a cycle to allow new members to participate.
[Participating actively in the REST framework project](contributing.md) **does not require being part of the maintenance team**. Almost every important part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.
#### Current team
#### Composition
The [maintenance team for Q4 2015](https://github.com/encode/django-rest-framework/issues/2190):
The composition of the maintenance team is handled by [@tomchristie](https://github.com/encode/). Team members will be added as collaborators to the repository.
* [@tomchristie](https://github.com/encode/)
* [@xordoquy](https://github.com/xordoquy/) (Release manager.)
* [@carltongibson](https://github.com/carltongibson/)
* [@kevin-brown](https://github.com/kevin-brown/)
* [@jpadilla](https://github.com/jpadilla/)
#### Maintenance cycles
Each maintenance cycle is initiated by an issue being opened with the `Process` label.
* To be considered for a maintainer role simply comment against the issue.
* Existing members must explicitly opt-in to the next cycle by check-marking their name.
* The final decision on the incoming team will be made by `@tomchristie`.
Members of the maintenance team will be added as collaborators to the repository.
The following template should be used for the description of the issue, and serves as the formal process for selecting the team.
This issue is for determining the maintenance team for the *** period.
Please see the [Project management](https://www.django-rest-framework.org/topics/project-management/) section of our documentation for more details.
---
#### Renewing existing members.
The following people are the current maintenance team. Please checkmark your name if you wish to continue to have write permission on the repository for the *** period.
- [ ] @***
- [ ] @***
- [ ] @***
- [ ] @***
- [ ] @***
---
#### New members.
If you wish to be considered for this or a future date, please comment against this or subsequent issues.
To modify this process for future maintenance cycles make a pull request to the [project management](https://www.django-rest-framework.org/topics/project-management/) documentation.
#### Responsibilities of team members
#### Responsibilities
Team members have the following responsibilities.
@ -76,18 +34,13 @@ Further notes for maintainers:
* Code changes should come in the form of a pull request - do not push directly to master.
* Maintainers should typically not merge their own pull requests.
* Each issue/pull request should have exactly one label once triaged.
* Search for un-triaged issues with [is:open no:label][un-triaged].
It should be noted that participating actively in the REST framework project clearly **does not require being part of the maintenance team**. Almost every import part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.
---
## Release process
The release manager is selected on every quarterly maintenance cycle.
* The manager should be selected by `@tomchristie`.
* The manager will then have the maintainer role added to PyPI package.
* The release manager is selected by `@tomchristie`.
* The release manager will then have the maintainer role added to PyPI package.
* The previous manager will then have the maintainer role removed from the PyPI package.
Our PyPI releases will be handled by either the current release manager, or by `@tomchristie`. Every release should have an open issue tagged with the `Release` label and marked against the appropriate milestone.
@ -112,6 +65,9 @@ The following template should be used for the description of the issue, and serv
- [ ] `docs` Python & Django versions
- [ ] Update the translations from [transifex](https://www.django-rest-framework.org/topics/project-management/#translations).
- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/__init__.py).
- [ ] Ensure documentation validates
- Build and serve docs `mkdocs serve`
- Validate links `pylinkvalidate.py -P http://127.0.0.1:8000`
- [ ] Confirm with @tomchristie that release is finalized and ready to go.
- [ ] Ensure that release date is included in pull request.
- [ ] Merge the release pull request.
@ -195,15 +151,12 @@ If `@tomchristie` ceases to participate in the project then `@j4mie` has respons
The following issues still need to be addressed:
* Ensure `@jamie` has back-up access to the `django-rest-framework.org` domain setup and admin.
* Document ownership of the [live example][sandbox] API.
* Ensure `@j4mie` has back-up access to the `django-rest-framework.org` domain setup and admin.
* Document ownership of the [mailing list][mailing-list] and IRC channel.
* Document ownership and management of the security mailing list.
[bus-factor]: https://en.wikipedia.org/wiki/Bus_factor
[un-triaged]: https://github.com/encode/django-rest-framework/issues?q=is%3Aopen+no%3Alabel
[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/
[transifex-client]: https://pypi.org/project/transifex-client/
[translation-memory]: http://docs.transifex.com/guides/tm#let-tm-automatically-populate-translations
[sandbox]: https://restframework.herokuapp.com/
[mailing-list]: https://groups.google.com/forum/#!forum/django-rest-framework

View File

@ -2,11 +2,13 @@
## Versioning
Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.
- **Minor** version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.
Medium version numbers (0.x.0) may include API changes, in line with the [deprecation policy][deprecation-policy]. You should read the release notes carefully before upgrading between medium point releases.
- **Medium** version numbers (0.x.0) may include API changes, in line with the [deprecation policy][deprecation-policy]. You should read the release notes carefully before upgrading between medium point releases.
Major version numbers (x.0.0) are reserved for substantial project milestones.
- **Major** version numbers (x.0.0) are reserved for substantial project milestones.
As REST Framework is considered feature-complete, most releases are expected to be minor releases.
## Deprecation policy
@ -34,6 +36,232 @@ You can determine your currently installed version using `pip show`:
---
## 3.16.x series
### 3.16.0
**Date**: 28th March 2025
This release is considered a significant release to improve upstream support with Django and Python. Some of these may change the behaviour of existing features and pre-existing behaviour. Specifically, some fixes were added to around the support of `UniqueConstraint` with nullable fields which will improve built-in serializer validation.
## Features
* Add official support for Django 5.1 and its new `LoginRequiredMiddleware` in [#9514](https://github.com/encode/django-rest-framework/pull/9514) and [#9657](https://github.com/encode/django-rest-framework/pull/9657)
* Add official Django 5.2a1 support in [#9634](https://github.com/encode/django-rest-framework/pull/9634)
* Add support for Python 3.13 in [#9527](https://github.com/encode/django-rest-framework/pull/9527) and [#9556](https://github.com/encode/django-rest-framework/pull/9556)
* Support Django 2.1+ test client JSON data automatically serialized in [#6511](https://github.com/encode/django-rest-framework/pull/6511) and fix a regression in [#9615](https://github.com/encode/django-rest-framework/pull/9615)
## Bug fixes
* Fix unique together validator to respect condition's fields from `UniqueConstraint` in [#9360](https://github.com/encode/django-rest-framework/pull/9360)
* Fix raising on nullable fields part of `UniqueConstraint` in [#9531](https://github.com/encode/django-rest-framework/pull/9531)
* Fix `unique_together` validation with source in [#9482](https://github.com/encode/django-rest-framework/pull/9482)
* Added protections to `AttributeError` raised within properties in [#9455](https://github.com/encode/django-rest-framework/pull/9455)
* Fix `get_template_context` to handle also lists in [#9467](https://github.com/encode/django-rest-framework/pull/9467)
* Fix "Converter is already registered" deprecation warning. in [#9512](https://github.com/encode/django-rest-framework/pull/9512)
* Fix noisy warning and accept integers as min/max values of `DecimalField` in [#9515](https://github.com/encode/django-rest-framework/pull/9515)
* Fix usages of `open()` in `setup.py` in [#9661](https://github.com/encode/django-rest-framework/pull/9661)
## Translations
* Add some missing Chinese translations in [#9505](https://github.com/encode/django-rest-framework/pull/9505)
* Fix spelling mistakes in Farsi language were corrected in [#9521](https://github.com/encode/django-rest-framework/pull/9521)
* Fixing and adding missing Brazilian Portuguese translations in [#9535](https://github.com/encode/django-rest-framework/pull/9535)
## Removals
* Remove support for Python 3.8 in [#9670](https://github.com/encode/django-rest-framework/pull/9670)
* Remove long deprecated code from request wrapper in [#9441](https://github.com/encode/django-rest-framework/pull/9441)
* Remove deprecated `AutoSchema._get_reference` method in [#9525](https://github.com/encode/django-rest-framework/pull/9525)
## Documentation and internal changes
* Provide tests for hashing of `OperandHolder` in [#9437](https://github.com/encode/django-rest-framework/pull/9437)
* Update documentation: Add `adrf` third party package in [#9198](https://github.com/encode/django-rest-framework/pull/9198)
* Update tutorials links in Community contributions docs in [#9476](https://github.com/encode/django-rest-framework/pull/9476)
* Fix usage of deprecated Django function in example from docs in [#9509](https://github.com/encode/django-rest-framework/pull/9509)
* Move path converter docs into a separate section in [#9524](https://github.com/encode/django-rest-framework/pull/9524)
* Add test covering update view without `queryset` attribute in [#9528](https://github.com/encode/django-rest-framework/pull/9528)
* Fix Transifex link in [#9541](https://github.com/encode/django-rest-framework/pull/9541)
* Fix example `httpie` call in docs in [#9543](https://github.com/encode/django-rest-framework/pull/9543)
* Fix example for serializer field with choices in docs in [#9563](https://github.com/encode/django-rest-framework/pull/9563)
* Remove extra `<>` in validators example in [#9590](https://github.com/encode/django-rest-framework/pull/9590)
* Update `strftime` link in the docs in [#9624](https://github.com/encode/django-rest-framework/pull/9624)
* Switch to codecov GHA in [#9618](https://github.com/encode/django-rest-framework/pull/9618)
* Add note regarding availability of the `action` attribute in 'Introspecting ViewSet actions' docs section in [#9633](https://github.com/encode/django-rest-framework/pull/9633)
* Improved description of allowed throttling rates in documentation in [#9640](https://github.com/encode/django-rest-framework/pull/9640)
* Add `rest-framework-gm2m-relations` package to the list of 3rd party libraries in [#9063](https://github.com/encode/django-rest-framework/pull/9063)
* Fix a number of typos in the test suite in the docs in [#9662](https://github.com/encode/django-rest-framework/pull/9662)
* Add `django-pyoidc` as a third party authentication library in [#9667](https://github.com/encode/django-rest-framework/pull/9667)
## New Contributors
* [`@maerteijn`](https://github.com/maerteijn) made their first contribution in [#9198](https://github.com/encode/django-rest-framework/pull/9198)
* [`@FraCata00`](https://github.com/FraCata00) made their first contribution in [#9444](https://github.com/encode/django-rest-framework/pull/9444)
* [`@AlvaroVega`](https://github.com/AlvaroVega) made their first contribution in [#9451](https://github.com/encode/django-rest-framework/pull/9451)
* [`@james`](https://github.com/james)-mchugh made their first contribution in [#9455](https://github.com/encode/django-rest-framework/pull/9455)
* [`@ifeanyidavid`](https://github.com/ifeanyidavid) made their first contribution in [#9479](https://github.com/encode/django-rest-framework/pull/9479)
* [`@p`](https://github.com/p)-schlickmann made their first contribution in [#9480](https://github.com/encode/django-rest-framework/pull/9480)
* [`@akkuman`](https://github.com/akkuman) made their first contribution in [#9505](https://github.com/encode/django-rest-framework/pull/9505)
* [`@rafaelgramoschi`](https://github.com/rafaelgramoschi) made their first contribution in [#9509](https://github.com/encode/django-rest-framework/pull/9509)
* [`@Sinaatkd`](https://github.com/Sinaatkd) made their first contribution in [#9521](https://github.com/encode/django-rest-framework/pull/9521)
* [`@gtkacz`](https://github.com/gtkacz) made their first contribution in [#9535](https://github.com/encode/django-rest-framework/pull/9535)
* [`@sliverc`](https://github.com/sliverc) made their first contribution in [#9556](https://github.com/encode/django-rest-framework/pull/9556)
* [`@gabrielromagnoli1987`](https://github.com/gabrielromagnoli1987) made their first contribution in [#9543](https://github.com/encode/django-rest-framework/pull/9543)
* [`@cheehong1030`](https://github.com/cheehong1030) made their first contribution in [#9563](https://github.com/encode/django-rest-framework/pull/9563)
* [`@amansharma612`](https://github.com/amansharma612) made their first contribution in [#9590](https://github.com/encode/django-rest-framework/pull/9590)
* [`@Gluroda`](https://github.com/Gluroda) made their first contribution in [#9616](https://github.com/encode/django-rest-framework/pull/9616)
* [`@deepakangadi`](https://github.com/deepakangadi) made their first contribution in [#9624](https://github.com/encode/django-rest-framework/pull/9624)
* [`@EXG1O`](https://github.com/EXG1O) made their first contribution in [#9633](https://github.com/encode/django-rest-framework/pull/9633)
* [`@decadenza`](https://github.com/decadenza) made their first contribution in [#9640](https://github.com/encode/django-rest-framework/pull/9640)
* [`@mojtabaakbari221b`](https://github.com/mojtabaakbari221b) made their first contribution in [#9063](https://github.com/encode/django-rest-framework/pull/9063)
* [`@mikemanger`](https://github.com/mikemanger) made their first contribution in [#9661](https://github.com/encode/django-rest-framework/pull/9661)
* [`@gbip`](https://github.com/gbip) made their first contribution in [#9667](https://github.com/encode/django-rest-framework/pull/9667)
**Full Changelog**: https://github.com/encode/django-rest-framework/compare/3.15.2...3.16.0
## 3.15.x series
### 3.15.2
**Date**: 14th June 2024
* Fix potential XSS vulnerability in browsable API. [#9435](https://github.com/encode/django-rest-framework/pull/9435)
* Revert "Ensure CursorPagination respects nulls in the ordering field". [#9381](https://github.com/encode/django-rest-framework/pull/9381)
* Use warnings rather than logging a warning for DecimalField. [#9367](https://github.com/encode/django-rest-framework/pull/9367)
* Remove unused code. [#9393](https://github.com/encode/django-rest-framework/pull/9393)
* Django < 4.2 and Python < 3.8 no longer supported. [#9393](https://github.com/encode/django-rest-framework/pull/9393)
### 3.15.1
Date: 22nd March 2024
* Fix `SearchFilter` handling of quoted and comma separated strings, when `.get_search_terms` is being called into by a custom class. See [[#9338](https://github.com/encode/django-rest-framework/issues/9338)]
* Revert number of 3.15.0 issues which included unintended side-effects. See [[#9331](https://github.com/encode/django-rest-framework/issues/9331)]
### 3.15.0
Date: 15th March 2024
* Django 5.0 and Python 3.12 support [[#9157](https://github.com/encode/django-rest-framework/pull/9157)]
* Use POST method instead of GET to perform logout in browsable API [[9208](https://github.com/encode/django-rest-framework/pull/9208)]
* Added jQuery 3.7.1 support & dropped previous version [[#9094](https://github.com/encode/django-rest-framework/pull/9094)]
* Use str as default path converter [[#9066](https://github.com/encode/django-rest-framework/pull/9066)]
* Document support for http.HTTPMethod in the @action decorator added in Python 3.11 [[#9067](https://github.com/encode/django-rest-framework/pull/9067)]
* Update exceptions.md [[#9071](https://github.com/encode/django-rest-framework/pull/9071)]
* Partial serializer should not have required fields [[#7563](https://github.com/encode/django-rest-framework/pull/7563)]
* Propagate 'default' from model field to serializer field. [[#9030](https://github.com/encode/django-rest-framework/pull/9030)]
* Allow to override child.run_validation call in ListSerializer [[#8035](https://github.com/encode/django-rest-framework/pull/8035)]
* Align SearchFilter behaviour to django.contrib.admin search [[#9017](https://github.com/encode/django-rest-framework/pull/9017)]
* Class name added to unknown field error [[#9019](https://github.com/encode/django-rest-framework/pull/9019)]
* Fix: Pagination response schemas. [[#9049](https://github.com/encode/django-rest-framework/pull/9049)]
* Fix choices in ChoiceField to support IntEnum [[#8955](https://github.com/encode/django-rest-framework/pull/8955)]
* Fix `SearchFilter` rendering search field with invalid value [[#9023](https://github.com/encode/django-rest-framework/pull/9023)]
* Fix OpenAPI Schema yaml rendering for `timedelta` [[#9007](https://github.com/encode/django-rest-framework/pull/9007)]
* Fix `NamespaceVersioning` ignoring `DEFAULT_VERSION` on non-None namespaces [[#7278](https://github.com/encode/django-rest-framework/pull/7278)]
* Added Deprecation Warnings for CoreAPI [[#7519](https://github.com/encode/django-rest-framework/pull/7519)]
* Removed usage of `field.choices` that triggered full table load [[#8950](https://github.com/encode/django-rest-framework/pull/8950)]
* Permit mixed casing of string values for `BooleanField` validation [[#8970](https://github.com/encode/django-rest-framework/pull/8970)]
* Fixes `BrowsableAPIRenderer` for usage with `ListSerializer`. [[#7530](https://github.com/encode/django-rest-framework/pull/7530)]
* Change semantic of `OR` of two permission classes [[#7522](https://github.com/encode/django-rest-framework/pull/7522)]
* Remove dependency on `pytz` [[#8984](https://github.com/encode/django-rest-framework/pull/8984)]
* Make set_value a method within `Serializer` [[#8001](https://github.com/encode/django-rest-framework/pull/8001)]
* Fix URLPathVersioning reverse fallback [[#7247](https://github.com/encode/django-rest-framework/pull/7247)]
* Warn about Decimal type in min_value and max_value arguments of DecimalField [[#8972](https://github.com/encode/django-rest-framework/pull/8972)]
* Fix mapping for choice values [[#8968](https://github.com/encode/django-rest-framework/pull/8968)]
* Refactor read function to use context manager for file handling [[#8967](https://github.com/encode/django-rest-framework/pull/8967)]
* Fix: fallback on CursorPagination ordering if unset on the view [[#8954](https://github.com/encode/django-rest-framework/pull/8954)]
* Replaced `OrderedDict` with `dict` [[#8964](https://github.com/encode/django-rest-framework/pull/8964)]
* Refactor get_field_info method to include max_digits and decimal_places attributes in SimpleMetadata class [[#8943](https://github.com/encode/django-rest-framework/pull/8943)]
* Implement `__eq__` for validators [[#8925](https://github.com/encode/django-rest-framework/pull/8925)]
* Ensure CursorPagination respects nulls in the ordering field [[#8912](https://github.com/encode/django-rest-framework/pull/8912)]
* Use ZoneInfo as primary source of timezone data [[#8924](https://github.com/encode/django-rest-framework/pull/8924)]
* Add username search field for TokenAdmin (#8927) [[#8934](https://github.com/encode/django-rest-framework/pull/8934)]
* Handle Nested Relation in SlugRelatedField when many=False [[#8922](https://github.com/encode/django-rest-framework/pull/8922)]
* Bump version of jQuery to 3.6.4 & updated ref links [[#8909](https://github.com/encode/django-rest-framework/pull/8909)]
* Support UniqueConstraint [[#7438](https://github.com/encode/django-rest-framework/pull/7438)]
* Allow Request, Response, Field, and GenericAPIView to be subscriptable. This allows the classes to be made generic for type checking. [[#8825](https://github.com/encode/django-rest-framework/pull/8825)]
* Feat: Add some changes to ValidationError to support django style validation errors [[#8863](https://github.com/encode/django-rest-framework/pull/8863)]
* Fix Respect `can_read_model` permission in DjangoModelPermissions [[#8009](https://github.com/encode/django-rest-framework/pull/8009)]
* Add SimplePathRouter [[#6789](https://github.com/encode/django-rest-framework/pull/6789)]
* Re-prefetch related objects after updating [[#8043](https://github.com/encode/django-rest-framework/pull/8043)]
* Fix FilePathField required argument [[#8805](https://github.com/encode/django-rest-framework/pull/8805)]
* Raise ImproperlyConfigured exception if `basename` is not unique [[#8438](https://github.com/encode/django-rest-framework/pull/8438)]
* Use PrimaryKeyRelatedField pkfield in openapi [[#8315](https://github.com/encode/django-rest-framework/pull/8315)]
* replace partition with split in BasicAuthentication [[#8790](https://github.com/encode/django-rest-framework/pull/8790)]
* Fix BooleanField's allow_null behavior [[#8614](https://github.com/encode/django-rest-framework/pull/8614)]
* Handle Django's ValidationErrors in ListField [[#6423](https://github.com/encode/django-rest-framework/pull/6423)]
* Remove a bit of inline CSS. Add CSP nonce where it might be required and is available [[#8783](https://github.com/encode/django-rest-framework/pull/8783)]
* Use autocomplete widget for user selection in Token admin [[#8534](https://github.com/encode/django-rest-framework/pull/8534)]
* Make browsable API compatible with strong CSP [[#8784](https://github.com/encode/django-rest-framework/pull/8784)]
* Avoid inline script execution for injecting CSRF token [[#7016](https://github.com/encode/django-rest-framework/pull/7016)]
* Mitigate global dependency on inflection [[#8017](https://github.com/encode/django-rest-framework/pull/8017)] [[#8781](https://github.com/encode/django-rest-framework/pull/8781)]
* Register Django urls [[#8778](https://github.com/encode/django-rest-framework/pull/8778)]
* Implemented Verbose Name Translation for TokenProxy [[#8713](https://github.com/encode/django-rest-framework/pull/8713)]
* Properly handle OverflowError in DurationField deserialization [[#8042](https://github.com/encode/django-rest-framework/pull/8042)]
* Fix OpenAPI operation name plural appropriately [[#8017](https://github.com/encode/django-rest-framework/pull/8017)]
* Represent SafeString as plain string on schema rendering [[#8429](https://github.com/encode/django-rest-framework/pull/8429)]
* Fix #8771 - Checking for authentication even if `_ignore_model_permissions = True` [[#8772](https://github.com/encode/django-rest-framework/pull/8772)]
* Fix 404 when page query parameter is empty string [[#8578](https://github.com/encode/django-rest-framework/pull/8578)]
* Fixes instance check in ListSerializer.to_representation [[#8726](https://github.com/encode/django-rest-framework/pull/8726)] [[#8727](https://github.com/encode/django-rest-framework/pull/8727)]
* FloatField will crash if the input is a number that is too big [[#8725](https://github.com/encode/django-rest-framework/pull/8725)]
* Add missing DurationField to SimpleMetadata label_lookup [[#8702](https://github.com/encode/django-rest-framework/pull/8702)]
* Add support for Python 3.11 [[#8752](https://github.com/encode/django-rest-framework/pull/8752)]
* Make request consistently available in pagination classes [[#8764](https://github.com/encode/django-rest-framework/pull/9764)]
* Possibility to remove trailing zeros on DecimalFields representation [[#6514](https://github.com/encode/django-rest-framework/pull/6514)]
* Add a method for getting serializer field name (OpenAPI) [[#7493](https://github.com/encode/django-rest-framework/pull/7493)]
* Add `__eq__` method for `OperandHolder` class [[#8710](https://github.com/encode/django-rest-framework/pull/8710)]
* Avoid importing `django.test` package when not testing [[#8699](https://github.com/encode/django-rest-framework/pull/8699)]
* Preserve exception messages for wrapped Django exceptions [[#8051](https://github.com/encode/django-rest-framework/pull/8051)]
* Include `examples` and `format` to OpenAPI schema of CursorPagination [[#8687](https://github.com/encode/django-rest-framework/pull/8687)] [[#8686](https://github.com/encode/django-rest-framework/pull/8686)]
* Fix infinite recursion with deepcopy on Request [[#8684](https://github.com/encode/django-rest-framework/pull/8684)]
* Refactor: Replace try/except with contextlib.suppress() [[#8676](https://github.com/encode/django-rest-framework/pull/8676)]
* Minor fix to SerializeMethodField docstring [[#8629](https://github.com/encode/django-rest-framework/pull/8629)]
* Minor refactor: Unnecessary use of list() function [[#8672](https://github.com/encode/django-rest-framework/pull/8672)]
* Unnecessary list comprehension [[#8670](https://github.com/encode/django-rest-framework/pull/8670)]
* Use correct class to indicate present deprecation [[#8665](https://github.com/encode/django-rest-framework/pull/8665)]
## 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 Browsable 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 compatibility. [#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
@ -116,6 +344,7 @@ Date: 28th September 2020
* 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]
* Deprecate `serializers.NullBooleanField` in favour of `serializers.BooleanField` with `allow_null=True` [#7122]
---
@ -264,7 +493,11 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
class NullableCharField(serializers.CharField):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.validators = [v for v in self.validators if not isinstance(v, ProhibitNullCharactersValidator)]
self.validators = [
v
for v in self.validators
if not isinstance(v, ProhibitNullCharactersValidator)
]
```
* Add `OpenAPIRenderer` and `generate_schema` management command. [#6229][gh6229]
* Add OpenAPIRenderer by default, and add schema docs. [#6233][gh6233]
@ -279,7 +512,7 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
* Allow hashing of ErrorDetail. [#5932][gh5932]
* Correct schema parsing for JSONField [#5878][gh5878]
* Render descriptions (from help_text) using safe [#5869][gh5869]
* Removed input value from deault_error_message [#5881][gh5881]
* Removed input value from default_error_message [#5881][gh5881]
* Added min_value/max_value support in DurationField [#5643][gh5643]
* Fixed instance being overwritten in pk-only optimization try/except block [#5747][gh5747]
* Fixed AttributeError from items filter when value is None [#5981][gh5981]
@ -900,7 +1133,7 @@ See the [release announcement][3.6-release].
* description.py codes and tests removal. ([#4153][gh4153])
* Wrap guardian.VERSION in tuple. ([#4149][gh4149])
* Refine validator for fields with <source=> kwargs. ([#4146][gh4146])
* Fix None values representation in childs of ListField, DictField. ([#4118][gh4118])
* Fix None values representation in children of ListField, DictField. ([#4118][gh4118])
* Resolve TimeField representation for midnight value. ([#4107][gh4107])
* Set proper status code in AdminRenderer for the redirection after POST/DELETE requests. ([#4106][gh4106])
* TimeField render returns None instead of 00:00:00. ([#4105][gh4105])
@ -908,7 +1141,7 @@ See the [release announcement][3.6-release].
* Prevent raising exception when limit is 0. ([#4098][gh4098])
* TokenAuthentication: Allow custom keyword in the header. ([#4097][gh4097])
* Handle incorrectly padded HTTP basic auth header. ([#4090][gh4090])
* LimitOffset pagination crashes Browseable API when limit=0. ([#4079][gh4079])
* LimitOffset pagination crashes Browsable API when limit=0. ([#4079][gh4079])
* Fixed DecimalField arbitrary precision support. ([#4075][gh4075])
* Added support for custom CSRF cookie names. ([#4049][gh4049])
* Fix regression introduced by #4035. ([#4041][gh4041])

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.
@ -165,7 +32,7 @@ We suggest adding your package to the [REST Framework][rest-framework-grid] grid
#### Adding to the Django REST framework docs
Create a [Pull Request][drf-create-pr] or [Issue][drf-create-issue] on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under **Third party packages** of the API Guide section that best applies, like [Authentication][authentication] or [Permissions][permissions]. You can also link your package under the [Third Party Packages][third-party-packages] section.
Create a [Pull Request][drf-create-pr] on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under **Third party packages** of the API Guide section that best applies, like [Authentication][authentication] or [Permissions][permissions]. You can also link your package under the [Third Party Packages][third-party-packages] section.
#### Announce on the discussion group.
@ -177,7 +44,11 @@ Django REST Framework has a growing community of developers, packages, and resou
Check out a grid detailing all the packages and ecosystem around Django REST Framework at [Django Packages][rest-framework-grid].
To submit new content, [open an issue][drf-create-issue] or [create a pull request][drf-create-pr].
To submit new content, [create a pull request][drf-create-pr].
## Async Support
* [adrf](https://github.com/em1208/adrf) - Async support, provides async Views, ViewSets, and Serializers.
### Authentication
@ -187,10 +58,11 @@ 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.
* [dango-pyoidc][django-pyoidc] adds support for OpenID Connect (OIDC) authentication.
### Permissions
@ -239,6 +111,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [djangorestframework-msgpack][djangorestframework-msgpack] - Provides MessagePack renderer and parser support.
* [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
* [djangorestframework-camel-case][djangorestframework-camel-case] - Provides camel case JSON renderers and parsers.
* [nested-multipart-parser][nested-multipart-parser] - Provides nested parser for http multipart request
### Renderers
@ -253,10 +126,11 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [djangorestframework-chain][djangorestframework-chain] - Allows arbitrary chaining of both relations and lookup filters.
* [django-url-filter][django-url-filter] - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.
* [drf-url-filter][drf-url-filter] is a simple Django app to apply filters on drf `ModelViewSet`'s `Queryset` in a clean, simple and configurable way. It also supports validations on incoming query params and their values.
* [django-rest-framework-guardian][django-rest-framework-guardian] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF.
* [django-rest-framework-guardian2][django-rest-framework-guardian2] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF.
### Misc
* [drf-sendables][drf-sendables] - User messages for Django REST Framework
* [cookiecutter-django-rest][cookiecutter-django-rest] - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome.
* [djangorestrelationalhyperlink][djangorestrelationalhyperlink] - A hyperlinked serializer that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.
* [django-rest-framework-proxy][django-rest-framework-proxy] - Proxy to redirect incoming request to another API server.
@ -280,20 +154,27 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
* [django-elasticsearch-dsl-drf][django-elasticsearch-dsl-drf] - Integrate Elasticsearch DSL with Django REST framework. Package provides views, serializers, filter backends, pagination and other handy add-ons.
* [django-api-client][django-api-client] - DRF client that groups the Endpoint response, for use in CBVs and FBV as if you were working with Django's Native Models..
* [fast-drf] - A model based library for making API development faster and easier.
* [django-requestlogs] - Providing middleware and other helpers for audit logging for REST framework.
* [drf-standardized-errors][drf-standardized-errors] - DRF exception handler to standardize error responses for all API endpoints.
* [drf-api-action][drf-api-action] - uses the power of DRF also as a library functions
### Customization
* [drf-restwind][drf-restwind] - a modern re-imagining of the Django REST Framework utilizes TailwindCSS and DaisyUI to provide flexible and customizable UI solutions with minimal coding effort.
* [drf-redesign][drf-redesign] - A project that gives a fresh look to the browse-able API using Bootstrap 5.
* [drf-material][drf-material] - A project that gives a sleek and elegant look to the browsable API using Material Design.
[drf-sendables]: https://github.com/amikrop/drf-sendables
[cite]: http://www.software-ecosystems.com/Software_Ecosystems/Ecosystems.html
[cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework
[new-repo]: https://github.com/new
[create-a-repo]: https://help.github.com/articles/create-a-repo/
[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/
[drf-compat]: https://github.com/encode/django-rest-framework/blob/master/rest_framework/compat.py
[rest-framework-grid]: https://www.djangopackages.com/grids/g/django-rest-framework/
[drf-create-pr]: https://github.com/encode/django-rest-framework/compare
[drf-create-issue]: https://github.com/encode/django-rest-framework/issues/new
[authentication]: ../api-guide/authentication.md
[permissions]: ../api-guide/permissions.md
[third-party-packages]: ../topics/third-party-packages/#existing-third-party-packages
@ -318,6 +199,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
[wq.db.rest]: https://wq.io/docs/about-rest
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
[nested-multipart-parser]: https://github.com/remigermain/nested-multipart-parser
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
[drf_ujson2]: https://github.com/Amertz08/drf_ujson2
[rest-pandas]: https://github.com/wq/django-rest-pandas
@ -328,7 +210,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
@ -336,7 +218,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
[django-url-filter]: https://github.com/miki725/django-url-filter
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
[drf-haystack]: https://drf-haystack.readthedocs.io/en/latest/
[django-rest-framework-version-transforms]: https://github.com/mrhwick/django-rest-framework-version-transforms
[djangorestframework-jsonapi]: https://github.com/django-json-api/django-rest-framework-json-api
@ -360,7 +242,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
[djangorestframework-dataclasses]: https://github.com/oxan/djangorestframework-dataclasses
[django-restql]: https://github.com/yezyilomo/django-restql
[djangorestframework-mvt]: https://github.com/corteva/djangorestframework-mvt
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
[django-rest-framework-guardian2]: https://github.com/johnthagen/django-rest-framework-guardian2
[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
@ -370,3 +252,10 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
[graphwrap]: https://github.com/PaulGilmartin/graph_wrap
[rest-framework-actions]: https://github.com/AlexisMunera98/rest-framework-actions
[fast-drf]: https://github.com/iashraful/fast-drf
[django-requestlogs]: https://github.com/Raekkeri/django-requestlogs
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors
[drf-api-action]: https://github.com/Ori-Roza/drf-api-action
[drf-restwind]: https://github.com/youzarsiph/drf-restwind
[drf-redesign]: https://github.com/youzarsiph/drf-redesign
[drf-material]: https://github.com/youzarsiph/drf-material
[django-pyoidc]: https://github.com/makinacorpus/django_pyoidc

View File

@ -12,19 +12,22 @@ There are a wide range of resources available for learning and using Django REST
<img src="../../img/books/tsd-cover.png"/>
</a>
<a class="book-cover" href="https://djangoforapis.com">
<img src="../../img/books/dfa-cover.jpg"/>
<img src="../../img/books/dfa-40-cover.jpg"/>
</a>
<a class="book-cover" href="https://books.agiliq.com/projects/django-api-polls-tutorial/en/latest/">
<img src="../../img/books/bda-cover.png"/>
</a>
</div>
## Courses
* [Developing RESTful APIs with Django REST Framework][developing-restful-apis-with-django-rest-framework]
## Tutorials
* [Beginner's Guide to the Django REST Framework][beginners-guide-to-the-django-rest-framework]
* [Django REST Framework - An Introduction][drf-an-intro]
* [Django REST Framework Tutorial][drf-tutorial]
* [Django REST Framework Course][django-rest-framework-course]
* [Building a RESTful API with Django REST Framework][building-a-restful-api-with-drf]
* [Getting Started with Django REST Framework and AngularJS][getting-started-with-django-rest-framework-and-angularjs]
* [End to End Web App with Django REST Framework & AngularJS][end-to-end-web-app-with-django-rest-framework-angularjs]
@ -35,8 +38,10 @@ There are a wide range of resources available for learning and using Django REST
* [Check Credentials Using Django REST Framework][check-credentials-using-django-rest-framework]
* [Creating a Production Ready API with Python and Django REST Framework Part 1][creating-a-production-ready-api-with-python-and-drf-part1]
* [Creating a Production Ready API with Python and Django REST Framework Part 2][creating-a-production-ready-api-with-python-and-drf-part2]
* [Django REST Framework Tutorial - Build a Blog API][django-rest-framework-tutorial-build-a-blog]
* [Django REST Framework & React Tutorial - Build a Todo List API][django-rest-framework-react-tutorial-build-a-todo-list]
* [Creating a Production Ready API with Python and Django REST Framework Part 3][creating-a-production-ready-api-with-python-and-drf-part3]
* [Creating a Production Ready API with Python and Django REST Framework Part 4][creating-a-production-ready-api-with-python-and-drf-part4]
* [Django Polls Tutorial API][django-polls-api]
* [Django REST Framework Tutorial: Todo API][django-rest-framework-todo-api]
* [Tutorial: Django REST with React (Django 2.0)][django-rest-react-valentinog]
@ -45,11 +50,11 @@ There are a wide range of resources available for learning and using Django REST
### Talks
* [Level Up! Rethinking the Web API Framework][pycon-us-2017]
* [How to Make a Full Fledged REST API with Django OAuth Toolkit][full-fledged-rest-api-with-django-oauth-tookit]
* [How to Make a Full Fledged REST API with Django OAuth Toolkit][full-fledged-rest-api-with-django-oauth-toolkit]
* [Django REST API - So Easy You Can Learn It in 25 Minutes][django-rest-api-so-easy]
* [Tom Christie about Django Rest Framework at Django: Under The Hood][django-under-hood-2014]
* [Django REST Framework: Schemas, Hypermedia & Client Libraries][pycon-uk-2016]
* [Finally Understand Authentication in Django REST Framework][django-con-2018]
### Tutorials
@ -76,6 +81,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,10 +101,9 @@ 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://web.archive.org/web/20180104205117/http://machinalis.com/blog/pandas-django-rest-framework-bokeh/
@ -110,12 +115,14 @@ Want your Django REST Framework talk/tutorial/article to be added to our website
[chatbot-using-drf-part1]: https://chatbotslife.com/chatbot-using-django-rest-framework-api-ai-slack-part-1-3-69c7e38b7b1e#.g2aceuncf
[new-django-admin-with-drf-and-emberjs]: https://blog.levit.be/new-django-admin-with-emberjs-what-are-the-news/
[drf-schema]: https://drf-schema-adapter.readthedocs.io/en/latest/
[creating-a-production-ready-api-with-python-and-drf-part1]: https://www.andreagrandi.it/2016/09/28/creating-production-ready-api-python-django-rest-framework-part-1/
[creating-a-production-ready-api-with-python-and-drf-part2]: https://www.andreagrandi.it/2016/10/01/creating-a-production-ready-api-with-python-and-django-rest-framework-part-2/
[django-rest-framework-tutorial-build-a-blog]: https://wsvincent.com/django-rest-framework-tutorial/
[django-rest-framework-react-tutorial-build-a-todo-list]: https://wsvincent.com/django-rest-framework-react-tutorial/
[creating-a-production-ready-api-with-python-and-drf-part1]: https://www.andreagrandi.it/posts/creating-production-ready-api-python-django-rest-framework-part-1/
[creating-a-production-ready-api-with-python-and-drf-part2]: https://www.andreagrandi.it/posts/creating-a-production-ready-api-with-python-and-django-rest-framework-part-2/
[creating-a-production-ready-api-with-python-and-drf-part3]: https://www.andreagrandi.it/posts/creating-a-production-ready-api-with-python-and-django-rest-framework-part-3/
[creating-a-production-ready-api-with-python-and-drf-part4]: https://www.andreagrandi.it/posts/creating-a-production-ready-api-with-python-and-django-rest-framework-part-4/
[django-polls-api]: https://learndjango.com/tutorials/django-polls-tutorial-api
[django-rest-framework-todo-api]: https://learndjango.com/tutorials/django-rest-framework-tutorial-todo-api
[django-rest-api-so-easy]: https://www.youtube.com/watch?v=cqP758k1BaQ
[full-fledged-rest-api-with-django-oauth-tookit]: https://www.youtube.com/watch?v=M6Ud3qC2tTk
[full-fledged-rest-api-with-django-oauth-toolkit]: https://www.youtube.com/watch?v=M6Ud3qC2tTk
[drf-in-your-pjs]: https://www.youtube.com/watch?v=xMtHsWa72Ww
[building-a-rest-api-using-django-and-drf]: https://www.youtube.com/watch?v=PwssEec3IRw
[drf-tutorials]: https://www.youtube.com/watch?v=axRCBgbOJp8&list=PLJtp8Jm8EDzjgVg9vVyIUMoGyqtegj7FH
@ -128,3 +135,6 @@ 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/
[developing-restful-apis-with-django-rest-framework]: https://testdriven.io/courses/django-rest-framework/
[django-con-2018]: https://youtu.be/pY-oje5b5Qk?si=AOU6tLi0IL1_pVzq

View File

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

View File

@ -1,171 +0,0 @@
## Built-in API documentation
The built-in API documentation includes:
* Documentation of API endpoints.
* Automatically generated code samples for each of the available API client libraries.
* Support for API interaction.
### Installation
The `coreapi` library is required as a dependency for the API docs. Make sure
to install the latest version. The `Pygments` and `Markdown` libraries
are optional but recommended.
To install the API documentation, you'll need to include it in your project's URLconf:
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
path('docs/', include_docs_urls(title='My API title'))
]
This will include two different views:
* `/docs/` - The documentation page itself.
* `/docs/schema.js` - A JavaScript resource that exposes the API schema.
---
**Note**: By default `include_docs_urls` configures the underlying `SchemaView` to generate _public_ schemas.
This means that views will not be instantiated with a `request` instance. i.e. Inside the view `self.request` will be `None`.
To be compatible with this behaviour, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
# Generate schema with valid `request` instance:
path('docs/', include_docs_urls(title='My API title', public=False))
]
---
### Documenting your views
You can document your views by including docstrings that describe each of the available actions.
For example:
class UserList(generics.ListAPIView):
"""
Return a list of all the existing users.
"""
If a view supports multiple methods, you should split your documentation using `method:` style delimiters.
class UserList(generics.ListCreateAPIView):
"""
get:
Return a list of all the existing users.
post:
Create a new user instance.
"""
When using viewsets, you should use the relevant action names as delimiters.
class UserViewSet(viewsets.ModelViewSet):
"""
retrieve:
Return the given user.
list:
Return a list of all the existing users.
create:
Create a new user instance.
"""
Custom actions on viewsets can also be documented in a similar way using the method names
as delimiters or by attaching the documentation to action mapping methods.
class UserViewSet(viewsets.ModelViewset):
...
@action(detail=False, methods=['get', 'post'])
def some_action(self, request, *args, **kwargs):
"""
get:
A description of the get method on the custom action.
post:
A description of the post method on the custom action.
"""
@some_action.mapping.put
def put_some_action():
"""
A description of the put method on the custom action.
"""
### `documentation` API Reference
The `rest_framework.documentation` module provides three helper functions to help configure the interactive API documentation, `include_docs_urls` (usage shown above), `get_docs_view` and `get_schemajs_view`.
`include_docs_urls` employs `get_docs_view` and `get_schemajs_view` to generate the url patterns for the documentation page and JavaScript resource that exposes the API schema respectively. They expose the following options for customisation. (`get_docs_view` and `get_schemajs_view` ultimately call `rest_frameworks.schemas.get_schema_view()`, see the Schemas docs for more options there.)
#### `include_docs_urls`
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
* `description`: Default `None`. May be used to provide a description for the schema definition.
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
* `public`: Default `True`. Should the schema be considered _public_? If `True` schema is generated without a `request` instance being passed to views.
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`.
* `renderer_classes`: Default `None`. May be used to pass custom renderer classes to the `SchemaView`.
#### `get_docs_view`
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
* `description`: Default `None`. May be used to provide a description for the schema definition.
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views.
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES`. May be used to pass custom permission classes to the `SchemaView`.
* `renderer_classes`: Default `None`. May be used to pass custom renderer classes to the `SchemaView`. If `None` the `SchemaView` will be configured with `DocumentationRenderer` and `CoreJSONRenderer` renderers, corresponding to the (default) `html` and `corejson` formats.
#### `get_schemajs_view`
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
* `description`: Default `None`. May be used to provide a description for the schema definition.
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views.
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`.
### Customising code samples
The built-in API documentation includes automatically generated code samples for
each of the available API client libraries.
You may customise these samples by subclassing `DocumentationRenderer`, setting
`languages` to the list of languages you wish to support:
from rest_framework.renderers import DocumentationRenderer
class CustomRenderer(DocumentationRenderer):
languages = ['ruby', 'go']
For each language you need to provide an `intro` template, detailing installation instructions and such,
plus a generic template for making API requests, that can be filled with individual request details.
See the [templates for the bundled languages][client-library-templates] for examples.
---
[client-library-templates]: https://github.com/encode/django-rest-framework/tree/master/rest_framework/templates/rest_framework/docs/langs

View File

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

View File

@ -1,846 +0,0 @@
source: schemas.py
# Schemas
> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.
>
> &mdash; Heroku, [JSON Schema for the Heroku Platform API][cite]
API schemas are a useful tool that allow for a range of use cases, including
generating reference documentation, or driving dynamic client libraries that
can interact with your API.
## Install Core API & PyYAML
You'll need to install the `coreapi` package in order to add schema support
for REST framework. You probably also want to install `pyyaml`, so that you
can render the schema into the commonly used YAML-based OpenAPI format.
pip install coreapi pyyaml
## Quickstart
There are two different ways you can serve a schema description for your API.
### Generating a schema with the `generateschema` management command
To generate a static API schema, use the `generateschema` management command.
```shell
$ python manage.py generateschema > schema.yml
```
Once you've generated a schema in this way you can annotate it with any
additional information that cannot be automatically inferred by the schema
generator.
You might want to check your API schema into version control and update it
with each new release, or serve the API schema from your site's static media.
### Adding a view with `get_schema_view`
To add a dynamically generated schema view to your API, use `get_schema_view`.
```python
from rest_framework.schemas import get_schema_view
from django.urls import path
schema_view = get_schema_view(title="Example API")
urlpatterns = [
path('schema', schema_view),
...
]
```
See below [for more details](#the-get_schema_view-shortcut) on customizing a
dynamically generated schema view.
## Internal schema representation
REST framework uses [Core API][coreapi] in order to model schema information in
a format-independent representation. This information can then be rendered
into various different schema formats, or used to generate API documentation.
When using Core API, a schema is represented as a `Document` which is the
top-level container object for information about the API. Available API
interactions are represented using `Link` objects. Each link includes a URL,
HTTP method, and may include a list of `Field` instances, which describe any
parameters that may be accepted by the API endpoint. The `Link` and `Field`
instances may also include descriptions, that allow an API schema to be
rendered into user documentation.
Here's an example of an API description that includes a single `search`
endpoint:
coreapi.Document(
title='Flight Search API',
url='https://api.example.org/',
content={
'search': coreapi.Link(
url='/search/',
action='get',
fields=[
coreapi.Field(
name='from',
required=True,
location='query',
description='City name or airport code.'
),
coreapi.Field(
name='to',
required=True,
location='query',
description='City name or airport code.'
),
coreapi.Field(
name='date',
required=True,
location='query',
description='Flight date in "YYYY-MM-DD" format.'
)
],
description='Return flight availability and prices.'
)
}
)
## Schema output formats
In order to be presented in an HTTP response, the internal representation
has to be rendered into the actual bytes that are used in the response.
REST framework includes a few different renderers that you can use for
encoding the API schema.
* `renderers.OpenAPIRenderer` - Renders into YAML-based [OpenAPI][open-api], the most widely used API schema format.
* `renderers.JSONOpenAPIRenderer` - Renders into JSON-based [OpenAPI][open-api].
* `renderers.CoreJSONRenderer` - Renders into [Core JSON][corejson], a format designed for
use with the `coreapi` client library.
[Core JSON][corejson] is designed as a canonical format for use with Core API.
REST framework includes a renderer class for handling this media type, which
is available as `renderers.CoreJSONRenderer`.
## Schemas vs Hypermedia
It's worth pointing out here that Core API can also be used to model hypermedia
responses, which present an alternative interaction style to API schemas.
With an API schema, the entire available interface is presented up-front
as a single endpoint. Responses to individual API endpoints are then typically
presented as plain data, without any further interactions contained in each
response.
With Hypermedia, the client is instead presented with a document containing
both data and available interactions. Each interaction results in a new
document, detailing both the current state and the available interactions.
Further information and support on building Hypermedia APIs with REST framework
is planned for a future version.
---
# Creating a schema
REST framework includes functionality for auto-generating a schema,
or allows you to specify one explicitly.
## Manual Schema Specification
To manually specify a schema you create a Core API `Document`, similar to the
example above.
schema = coreapi.Document(
title='Flight Search API',
content={
...
}
)
## Automatic Schema Generation
Automatic schema generation is provided by the `SchemaGenerator` class.
`SchemaGenerator` processes a list of routed URL patterns and compiles the
appropriately structured Core API Document.
Basic usage is just to provide the title for your schema and call
`get_schema()`:
generator = schemas.SchemaGenerator(title='Flight Search API')
schema = generator.get_schema()
## Per-View Schema Customisation
By default, view introspection is performed by an `AutoSchema` instance
accessible via the `schema` attribute on `APIView`. This provides the
appropriate Core API `Link` object for the view, request method and path:
auto_schema = view.schema
coreapi_link = auto_schema.get_link(...)
(In compiling the schema, `SchemaGenerator` calls `view.schema.get_link()` for
each view, allowed method and path.)
---
**Note**: For basic `APIView` subclasses, default introspection is essentially
limited to the URL kwarg path parameters. For `GenericAPIView`
subclasses, which includes all the provided class based views, `AutoSchema` will
attempt to introspect serializer, pagination and filter fields, as well as
provide richer path field descriptions. (The key hooks here are the relevant
`GenericAPIView` attributes and methods: `get_serializer`, `pagination_class`,
`filter_backends` and so on.)
---
To customise the `Link` generation you may:
* Instantiate `AutoSchema` on your view with the `manual_fields` kwarg:
from rest_framework.views import APIView
from rest_framework.schemas import AutoSchema
class CustomView(APIView):
...
schema = AutoSchema(
manual_fields=[
coreapi.Field("extra_field", ...),
]
)
This allows extension for the most common case without subclassing.
* Provide an `AutoSchema` subclass with more complex customisation:
from rest_framework.views import APIView
from rest_framework.schemas import AutoSchema
class CustomSchema(AutoSchema):
def get_link(...):
# Implement custom introspection here (or in other sub-methods)
class CustomView(APIView):
...
schema = CustomSchema()
This provides complete control over view introspection.
* Instantiate `ManualSchema` on your view, providing the Core API `Fields` for
the view explicitly:
from rest_framework.views import APIView
from rest_framework.schemas import ManualSchema
class CustomView(APIView):
...
schema = ManualSchema(fields=[
coreapi.Field(
"first_field",
required=True,
location="path",
schema=coreschema.String()
),
coreapi.Field(
"second_field",
required=True,
location="path",
schema=coreschema.String()
),
])
This allows manually specifying the schema for some views whilst maintaining
automatic generation elsewhere.
You may disable schema generation for a view by setting `schema` to `None`:
class CustomView(APIView):
...
schema = None # Will not appear in schema
This also applies to extra actions for `ViewSet`s:
class CustomViewSet(viewsets.ModelViewSet):
@action(detail=True, schema=None)
def extra_action(self, request, pk=None):
...
---
**Note**: For full details on `SchemaGenerator` plus the `AutoSchema` and
`ManualSchema` descriptors see the [API Reference below](#api-reference).
---
# Adding a schema view
There are a few different ways to add a schema view to your API, depending on
exactly what you need.
## The get_schema_view shortcut
The simplest way to include a schema in your project is to use the
`get_schema_view()` function.
from rest_framework.schemas import get_schema_view
schema_view = get_schema_view(title="Server Monitoring API")
urlpatterns = [
path('', schema_view),
...
]
Once the view has been added, you'll be able to make API requests to retrieve
the auto-generated schema definition.
$ http http://127.0.0.1:8000/ Accept:application/coreapi+json
HTTP/1.0 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/vnd.coreapi+json
{
"_meta": {
"title": "Server Monitoring API"
},
"_type": "document",
...
}
The arguments to `get_schema_view()` are:
#### `title`
May be used to provide a descriptive title for the schema definition.
#### `url`
May be used to pass a canonical URL for the schema.
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/'
)
#### `urlconf`
A string representing the import path to the URL conf that you want
to generate an API schema for. This defaults to the value of Django's
ROOT_URLCONF setting.
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/',
urlconf='myproject.urls'
)
#### `renderer_classes`
May be used to pass the set of renderer classes that can be used to render the API root endpoint.
from rest_framework.schemas import get_schema_view
from rest_framework.renderers import JSONOpenAPIRenderer
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/',
renderer_classes=[JSONOpenAPIRenderer]
)
#### `patterns`
List of url patterns to limit the schema introspection to. If you only want the `myproject.api` urls
to be exposed in the schema:
schema_url_patterns = [
path('api/', include('myproject.api.urls')),
]
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/',
patterns=schema_url_patterns,
)
#### `generator_class`
May be used to specify a `SchemaGenerator` subclass to be passed to the
`SchemaView`.
#### `authentication_classes`
May be used to specify the list of authentication classes that will apply to the schema endpoint.
Defaults to `settings.DEFAULT_AUTHENTICATION_CLASSES`
#### `permission_classes`
May be used to specify the list of permission classes that will apply to the schema endpoint.
Defaults to `settings.DEFAULT_PERMISSION_CLASSES`
## Using an explicit schema view
If you need a little more control than the `get_schema_view()` shortcut gives you,
then you can use the `SchemaGenerator` class directly to auto-generate the
`Document` instance, and to return that from a view.
This option gives you the flexibility of setting up the schema endpoint
with whatever behaviour you want. For example, you can apply different
permission, throttling, or authentication policies to the schema endpoint.
Here's an example of using `SchemaGenerator` together with a view to
return the schema.
**views.py:**
from rest_framework.decorators import api_view, renderer_classes
from rest_framework import renderers, response, schemas
generator = schemas.SchemaGenerator(title='Bookings API')
@api_view()
@renderer_classes([renderers.OpenAPIRenderer])
def schema_view(request):
schema = generator.get_schema(request)
return response.Response(schema)
**urls.py:**
urlpatterns = [
path('', schema_view),
...
]
You can also serve different schemas to different users, depending on the
permissions they have available. This approach can be used to ensure that
unauthenticated requests are presented with a different schema to
authenticated requests, or to ensure that different parts of the API are
made visible to different users depending on their role.
In order to present a schema with endpoints filtered by user permissions,
you need to pass the `request` argument to the `get_schema()` method, like so:
@api_view()
@renderer_classes([renderers.OpenAPIRenderer])
def schema_view(request):
generator = schemas.SchemaGenerator(title='Bookings API')
return response.Response(generator.get_schema(request=request))
## Explicit schema definition
An alternative to the auto-generated approach is to specify the API schema
explicitly, by declaring a `Document` object in your codebase. Doing so is a
little more work, but ensures that you have full control over the schema
representation.
import coreapi
from rest_framework.decorators import api_view, renderer_classes
from rest_framework import renderers, response
schema = coreapi.Document(
title='Bookings API',
content={
...
}
)
@api_view()
@renderer_classes([renderers.OpenAPIRenderer])
def schema_view(request):
return response.Response(schema)
---
# Schemas as documentation
One common usage of API schemas is to use them to build documentation pages.
The schema generation in REST framework uses docstrings to automatically
populate descriptions in the schema document.
These descriptions will be based on:
* The corresponding method docstring if one exists.
* A named section within the class docstring, which can be either single line or multi-line.
* The class docstring.
## Examples
An `APIView`, with an explicit method docstring.
class ListUsernames(APIView):
def get(self, request):
"""
Return a list of all user names in the system.
"""
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
A `ViewSet`, with an explicit action docstring.
class ListUsernames(ViewSet):
def list(self, request):
"""
Return a list of all user names in the system.
"""
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
A generic view with sections in the class docstring, using single-line style.
class UserList(generics.ListCreateAPIView):
"""
get: List all the users.
post: Create a new user.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [IsAdminUser]
A generic viewset with sections in the class docstring, using multi-line style.
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
retrieve:
Return a user instance.
list:
Return all users, ordered by most recently joined.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
---
# API Reference
## SchemaGenerator
A class that walks a list of routed URL patterns, requests the schema for each view,
and collates the resulting CoreAPI Document.
Typically you'll instantiate `SchemaGenerator` with a single argument, like so:
generator = SchemaGenerator(title='Stock Prices API')
Arguments:
* `title` **required** - The name of the API.
* `url` - The root URL of the API schema. This option is not required unless the schema is included under path prefix.
* `patterns` - A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.
* `urlconf` - A URL conf module name to use when generating the schema. Defaults to `settings.ROOT_URLCONF`.
### get_schema(self, request)
Returns a `coreapi.Document` instance that represents the API schema.
@api_view
@renderer_classes([renderers.OpenAPIRenderer])
def schema_view(request):
generator = schemas.SchemaGenerator(title='Bookings API')
return Response(generator.get_schema())
The `request` argument is optional, and may be used if you want to apply per-user
permissions to the resulting schema generation.
### get_links(self, request)
Return a nested dictionary containing all the links that should be included in the API schema.
This is a good point to override if you want to modify the resulting structure of the generated schema,
as you can build a new dictionary with a different layout.
## AutoSchema
A class that deals with introspection of individual views for schema generation.
`AutoSchema` is attached to `APIView` via the `schema` attribute.
The `AutoSchema` constructor takes a single keyword argument `manual_fields`.
**`manual_fields`**: a `list` of `coreapi.Field` instances that will be added to
the generated fields. Generated fields with a matching `name` will be overwritten.
class CustomView(APIView):
schema = AutoSchema(manual_fields=[
coreapi.Field(
"my_extra_field",
required=True,
location="path",
schema=coreschema.String()
),
])
For more advanced customisation subclass `AutoSchema` to customise schema generation.
class CustomViewSchema(AutoSchema):
"""
Overrides `get_link()` to provide Custom Behavior X
"""
def get_link(self, path, method, base_url):
link = super().get_link(path, method, base_url)
# Do something to customize link here...
return link
class MyView(APIView):
schema = CustomViewSchema()
The following methods are available to override.
### get_link(self, path, method, base_url)
Returns a `coreapi.Link` instance corresponding to the given view.
This is the main entry point.
You can override this if you need to provide custom behaviors for particular views.
### get_description(self, path, method)
Returns a string to use as the link description. By default this is based on the
view docstring as described in the "Schemas as Documentation" section above.
### get_encoding(self, path, method)
Returns a string to indicate the encoding for any request body, when interacting
with the given view. Eg. `'application/json'`. May return a blank string for views
that do not expect a request body.
### get_path_fields(self, path, method):
Return a list of `coreapi.Field()` instances. One for each path parameter in the URL.
### get_serializer_fields(self, path, method)
Return a list of `coreapi.Field()` instances. One for each field in the serializer class used by the view.
### get_pagination_fields(self, path, method)
Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method on any pagination class used by the view.
### get_filter_fields(self, path, method)
Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method of any filter classes used by the view.
### get_manual_fields(self, path, method)
Return a list of `coreapi.Field()` instances to be added to or replace generated fields. Defaults to (optional) `manual_fields` passed to `AutoSchema` constructor.
May be overridden to customise manual fields by `path` or `method`. For example, a per-method adjustment may look like this:
```python
def get_manual_fields(self, path, method):
"""Example adding per-method fields."""
extra_fields = []
if method=='GET':
extra_fields = # ... list of extra fields for GET ...
if method=='POST':
extra_fields = # ... list of extra fields for POST ...
manual_fields = super().get_manual_fields(path, method)
return manual_fields + extra_fields
```
### update_fields(fields, update_with)
Utility `staticmethod`. Encapsulates logic to add or replace fields from a list
by `Field.name`. May be overridden to adjust replacement criteria.
## ManualSchema
Allows manually providing a list of `coreapi.Field` instances for the schema,
plus an optional description.
class MyView(APIView):
schema = ManualSchema(fields=[
coreapi.Field(
"first_field",
required=True,
location="path",
schema=coreschema.String()
),
coreapi.Field(
"second_field",
required=True,
location="path",
schema=coreschema.String()
),
]
)
The `ManualSchema` constructor takes two arguments:
**`fields`**: A list of `coreapi.Field` instances. Required.
**`description`**: A string description. Optional.
**`encoding`**: Default `None`. A string encoding, e.g `application/json`. Optional.
---
## Core API
This documentation gives a brief overview of the components within the `coreapi`
package that are used to represent an API schema.
Note that these classes are imported from the `coreapi` package, rather than
from the `rest_framework` package.
### Document
Represents a container for the API schema.
#### `title`
A name for the API.
#### `url`
A canonical URL for the API.
#### `content`
A dictionary, containing the `Link` objects that the schema contains.
In order to provide more structure to the schema, the `content` dictionary
may be nested, typically to a second level. For example:
content={
"bookings": {
"list": Link(...),
"create": Link(...),
...
},
"venues": {
"list": Link(...),
...
},
...
}
### Link
Represents an individual API endpoint.
#### `url`
The URL of the endpoint. May be a URI template, such as `/users/{username}/`.
#### `action`
The HTTP method associated with the endpoint. Note that URLs that support
more than one HTTP method, should correspond to a single `Link` for each.
#### `fields`
A list of `Field` instances, describing the available parameters on the input.
#### `description`
A short description of the meaning and intended usage of the endpoint.
### Field
Represents a single input parameter on a given API endpoint.
#### `name`
A descriptive name for the input.
#### `required`
A boolean, indicated if the client is required to included a value, or if
the parameter can be omitted.
#### `location`
Determines how the information is encoded into the request. Should be one of
the following strings:
**"path"**
Included in a templated URI. For example a `url` value of `/products/{product_code}/` could be used together with a `"path"` field, to handle API inputs in a URL path such as `/products/slim-fit-jeans/`.
These fields will normally correspond with [named arguments in the project URL conf][named-arguments].
**"query"**
Included as a URL query parameter. For example `?search=sale`. Typically for `GET` requests.
These fields will normally correspond with pagination and filtering controls on a view.
**"form"**
Included in the request body, as a single item of a JSON object or HTML form. For example `{"colour": "blue", ...}`. Typically for `POST`, `PUT` and `PATCH` requests. Multiple `"form"` fields may be included on a single link.
These fields will normally correspond with serializer fields on a view.
**"body"**
Included as the complete request body. Typically for `POST`, `PUT` and `PATCH` requests. No more than one `"body"` field may exist on a link. May not be used together with `"form"` fields.
These fields will normally correspond with views that use `ListSerializer` to validate the request input, or with file upload views.
#### `encoding`
**"application/json"**
JSON encoded request content. Corresponds to views using `JSONParser`.
Valid only if either one or more `location="form"` fields, or a single
`location="body"` field is included on the `Link`.
**"multipart/form-data"**
Multipart encoded request content. Corresponds to views using `MultiPartParser`.
Valid only if one or more `location="form"` fields is included on the `Link`.
**"application/x-www-form-urlencoded"**
URL encoded request content. Corresponds to views using `FormParser`. Valid
only if one or more `location="form"` fields is included on the `Link`.
**"application/octet-stream"**
Binary upload request content. Corresponds to views using `FileUploadParser`.
Valid only if a `location="body"` field is included on the `Link`.
#### `description`
A short description of the meaning and intended usage of the input field.
---
# Third party packages
## drf-yasg - Yet Another Swagger Generator
[drf-yasg][drf-yasg] generates [OpenAPI][open-api] documents suitable for code generation - nested schemas,
named models, response bodies, enum/pattern/min/max validators, form parameters, etc.
## drf-spectacular - Sane and flexible OpenAPI 3.0 schema generation for Django REST framework
[drf-spectacular][drf-spectacular] is a [OpenAPI 3][open-api] schema generation tool with explicit focus on extensibility,
customizability and client generation. It's usage patterns are very similar to [drf-yasg][drf-yasg].
[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api
[coreapi]: https://www.coreapi.org/
[corejson]: https://www.coreapi.org/specification/encoding/#core-json-encoding
[drf-yasg]: https://github.com/axnsan12/drf-yasg/
[drf-spectacular]: https://github.com/tfranzel/drf-spectacular/
[open-api]: https://openapis.org/
[json-hyperschema]: https://json-schema.org/latest/json-schema-hypermedia.html
[api-blueprint]: https://apiblueprint.org/
[static-files]: https://docs.djangoproject.com/en/stable/howto/static-files/
[named-arguments]: https://docs.djangoproject.com/en/stable/topics/http/urls/#named-groups

Binary file not shown.

After

Width:  |  Height:  |  Size: 755 KiB

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
docs/img/drf-m-api-root.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

BIN
docs/img/drf-r-api-root.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 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.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 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/">
@ -48,7 +48,7 @@ Django REST framework is a powerful and flexible toolkit for building Web APIs.
Some reasons you might want to use REST framework:
* The [Web browsable API][sandbox] is a huge usability win for your developers.
* The Web browsable API is a huge usability win for your developers.
* [Authentication policies][authentication] including packages for [OAuth1a][oauth1-section] and [OAuth2][oauth2-section].
* [Serialization][serializers] that supports both [ORM][modelserializer-section] and [non-ORM][serializer-section] data sources.
* Customizable all the way down - just use [regular function-based views][functionview-section] if you don't need the [more][generic-views] [powerful][viewsets] [features][routers].
@ -67,15 +67,19 @@ 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>
<li><a href="https://www.svix.com/?utm_source=django-REST&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/svix.png)">Svix</a></li>
<li><a href="https://zuplo.link/django-web" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/zuplo.png)">Zuplo</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), [FEZTO](https://www.fezto.xyz/?utm_source=DjangoRESTFramework), [Svix](https://www.svix.com/?utm_source=django-REST&utm_medium=sponsorship), , and [Zuplo](https://zuplo.link/django-web).*
---
@ -83,8 +87,8 @@ continued development by **[signing up for a paid plan][funding]**.
REST framework requires the following:
* Python (3.5, 3.6, 3.7, 3.8, 3.9)
* Django (2.2, 3.0, 3.1)
* Django (4.2, 5.0, 5.1, 5.2)
* Python (3.9, 3.10, 3.11, 3.12, 3.13)
We **highly recommend** and only officially support the latest patch release of
each Python and Django series.
@ -92,8 +96,8 @@ each Python and Django series.
The following packages are optional:
* [PyYAML][pyyaml], [uritemplate][uriteemplate] (5.1+, 3.0.0+) - Schema generation support.
* [Markdown][markdown] (3.0.0+) - Markdown support for the browsable API.
* [Pygments][pygments] (2.4.0+) - Add syntax highlighting to Markdown processing.
* [Markdown][markdown] (3.3.0+) - Markdown support for the browsable API.
* [Pygments][pygments] (2.7.0+) - Add syntax highlighting to Markdown processing.
* [django-filter][django-filter] (1.0.1+) - Filtering support.
* [django-guardian][django-guardian] (1.1.1+) - Object level permissions support.
@ -181,20 +185,20 @@ Can't wait to get started? The [quickstart guide][quickstart] is the fastest way
## Development
See the [Contribution guidelines][contributing] for information on how to clone
the repository, run the test suite and contribute changes back to REST
the repository, run the test suite and help maintain the code base of REST
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/).
## 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**.
**Please report security issues by emailing security@encode.io**.
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.
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
## License
@ -242,7 +246,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[serializer-section]: api-guide/serializers#serializers
[modelserializer-section]: api-guide/serializers#modelserializer
[functionview-section]: api-guide/views#function-based-views
[sandbox]: https://restframework.herokuapp.com/
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[quickstart]: tutorial/quickstart.md
@ -257,7 +260,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

@ -2,7 +2,7 @@
> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability &mdash; very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
>
> &mdash; [Jeff Atwood][cite]
> &mdash; [Jeff Atwood][cite]
## Javascript clients
@ -31,11 +31,11 @@ In order to make AJAX requests, you need to include CSRF token in the HTTP heade
The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.
[Otto Yiu][ottoyiu] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
[Adam Johnson][adamchainz] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
[cite]: https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/
[csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax
[csrf-ajax]: https://docs.djangoproject.com/en/stable/howto/csrf/#using-csrf-protection-with-ajax
[cors]: https://www.w3.org/TR/cors/
[ottoyiu]: https://github.com/ottoyiu/
[django-cors-headers]: https://github.com/ottoyiu/django-cors-headers/
[adamchainz]: https://github.com/adamchainz
[django-cors-headers]: https://github.com/adamchainz/django-cors-headers

View File

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

View File

@ -15,9 +15,23 @@ If you include fully-qualified URLs in your resource output, they will be 'urliz
By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview].
## Authentication
To quickly add authentication to the browesable api, add a routes named `"login"` and `"logout"` under the namespace `"rest_framework"`. DRF provides default routes for this which you can add to your urlconf:
```python
from django.urls import include, path
urlpatterns = [
# ...
path("api-auth/", include("rest_framework.urls", namespace="rest_framework"))
]
```
## 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 +49,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 +58,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 %}
@ -65,6 +79,48 @@ For more specific CSS tweaks than simply overriding the default bootstrap theme
---
### Third party packages for customization
You can use a third party package for customization, rather than doing it by yourself. Here is 3 packages for customizing the API:
* [drf-restwind][drf-restwind] - a modern re-imagining of the Django REST Framework utilizes TailwindCSS and DaisyUI to provide flexible and customizable UI solutions with minimal coding effort.
* [drf-redesign][drf-redesign] - A package for customizing the API using Bootstrap 5. Modern and sleek design, it comes with the support for dark mode.
* [drf-material][drf-material] - Material design for Django REST Framework.
---
![API Root][drf-rw-api-root]
![List View][drf-rw-list-view]
![Detail View][drf-rw-detail-view]
*Screenshots of the drf-restwind*
---
---
![API Root][drf-r-api-root]
![List View][drf-r-list-view]
![Detail View][drf-r-detail-view]
*Screenshot of the drf-redesign*
---
![API Root][drf-m-api-root]
![List View][drf-m-api-root]
![Detail View][drf-m-api-root]
*Screenshot of the drf-material*
---
### Blocks
All of the blocks available in the browsable API base template that can be used in your `api.html`.
@ -162,3 +218,15 @@ There are [a variety of packages for autocomplete widgets][autocomplete-packages
[bcomponentsnav]: https://getbootstrap.com/2.3.2/components.html#navbar
[autocomplete-packages]: https://www.djangopackages.com/grids/g/auto-complete/
[django-autocomplete-light]: https://github.com/yourlabs/django-autocomplete-light
[drf-restwind]: https://github.com/youzarsiph/drf-restwind
[drf-rw-api-root]: ../img/drf-rw-api-root.png
[drf-rw-list-view]: ../img/drf-rw-list-view.png
[drf-rw-detail-view]: ../img/drf-rw-detail-view.png
[drf-redesign]: https://github.com/youzarsiph/drf-redesign
[drf-r-api-root]: ../img/drf-r-api-root.png
[drf-r-list-view]: ../img/drf-r-list-view.png
[drf-r-detail-view]: ../img/drf-r-detail-view.png
[drf-material]: https://github.com/youzarsiph/drf-material
[drf-m-api-root]: ../img/drf-m-api-root.png
[drf-m-list-view]: ../img/drf-m-list-view.png
[drf-m-detail-view]: ../img/drf-m-detail-view.png

View File

@ -4,12 +4,42 @@
>
> &mdash; Roy Fielding, [REST APIs must be hypertext driven][cite]
REST framework provides built-in support for generating OpenAPI schemas, which
can be used with tools that allow you to build API documentation.
REST framework provides a range of different choices for documenting your API. The following
is a non-exhaustive list of the most popular ones.
There are also a number of great third-party documentation packages available.
## Third party packages for OpenAPI support
## Generating documentation from OpenAPI schemas
### drf-spectacular
[drf-spectacular][drf-spectacular] is an [OpenAPI 3][open-api] schema generation library with explicit
focus on extensibility, customizability and client generation. It is the recommended way for
generating and presenting OpenAPI schemas.
The library aims to extract as much schema information as possible, while providing decorators and extensions for easy
customization. There is explicit support for [swagger-codegen][swagger], [SwaggerUI][swagger-ui] and [Redoc][redoc],
i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters,
documentation and more. Several popular plugins for DRF are supported out-of-the-box as well.
### drf-yasg
[drf-yasg][drf-yasg] is a [Swagger / OpenAPI 2][swagger] generation tool implemented without using the schema generation provided
by Django Rest Framework.
It aims to implement as much of the [OpenAPI 2][open-api] specification as possible - nested schemas, named models,
response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code
generation tools like `swagger-codegen`.
This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`:
![Screenshot - drf-yasg][image-drf-yasg]
---
## Built-in OpenAPI schema generation (deprecated)
**Deprecation notice: REST framework's built-in support for generating OpenAPI schemas is
deprecated in favor of 3rd party packages that can provide this functionality instead.
As replacement, we recommend using the [drf-spectacular](#drf-spectacular) package.**
There are a number of packages available that allow you to generate HTML
documentation pages from OpenAPI schemas.
@ -66,10 +96,14 @@ urlpatterns = [
# ...
# Route TemplateView to serve Swagger UI template.
# * Provide `extra_context` with view name of `SchemaView`.
path('swagger-ui/', TemplateView.as_view(
template_name='swagger-ui.html',
extra_context={'schema_url':'openapi-schema'}
), name='swagger-ui'),
path(
"swagger-ui/",
TemplateView.as_view(
template_name="swagger-ui.html",
extra_context={"schema_url": "openapi-schema"},
),
name="swagger-ui",
),
]
```
@ -115,44 +149,18 @@ urlpatterns = [
# ...
# Route TemplateView to serve the ReDoc template.
# * Provide `extra_context` with view name of `SchemaView`.
path('redoc/', TemplateView.as_view(
template_name='redoc.html',
extra_context={'schema_url':'openapi-schema'}
), name='redoc'),
path(
"redoc/",
TemplateView.as_view(
template_name="redoc.html", extra_context={"schema_url": "openapi-schema"}
),
name="redoc",
),
]
```
See the [ReDoc documentation][redoc] for advanced usage.
## Third party packages
There are a number of mature third-party packages for providing API documentation.
#### drf-yasg - Yet Another Swagger Generator
[drf-yasg][drf-yasg] is a [Swagger][swagger] generation tool implemented without using the schema generation provided
by Django Rest Framework.
It aims to implement as much of the [OpenAPI][open-api] specification as possible - nested schemas, named models,
response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code
generation tools like `swagger-codegen`.
This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`:
![Screenshot - drf-yasg][image-drf-yasg]
#### drf-spectacular - Sane and flexible OpenAPI 3.0 schema generation for Django REST framework
[drf-spectacular][drf-spectacular] is a [OpenAPI 3][open-api] schema generation tool with explicit focus on extensibility,
customizability and client generation. Usage patterns are very similar to [drf-yasg][drf-yasg].
It aims to extract as much schema information as possible, while providing decorators and extensions for easy
customization. There is explicit support for [swagger-codegen][swagger], [SwaggerUI][swagger-ui] and [Redoc][redoc],
i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters,
documentation and more. Several popular plugins for DRF are supported out-of-the-box as well.
---
## Self describing APIs

View File

@ -1,220 +1,220 @@
# HTML & Forms
REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can be used as HTML forms and rendered in templates.
## Rendering HTML
In order to return HTML responses you'll need to use either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`.
The `TemplateHTMLRenderer` class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.
The `StaticHTMLRender` class expects the response to contain a string of the pre-rendered HTML content.
Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.
Here's an example of a view that returns a list of "Profile" instances, rendered in an HTML template:
**views.py**:
from my_project.example.models import Profile
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
class ProfileList(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'profile_list.html'
def get(self, request):
queryset = Profile.objects.all()
return Response({'profiles': queryset})
**profile_list.html**:
<html><body>
<h1>Profiles</h1>
<ul>
{% for profile in profiles %}
<li>{{ profile.name }}</li>
{% endfor %}
</ul>
</body></html>
## Rendering Forms
Serializers may be rendered as forms by using the `render_form` template tag, and including the serializer instance as context to the template.
The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:
**views.py**:
from django.shortcuts import get_object_or_404
from my_project.example.models import Profile
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.views import APIView
class ProfileDetail(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'profile_detail.html'
def get(self, request, pk):
profile = get_object_or_404(Profile, pk=pk)
serializer = ProfileSerializer(profile)
return Response({'serializer': serializer, 'profile': profile})
def post(self, request, pk):
profile = get_object_or_404(Profile, pk=pk)
serializer = ProfileSerializer(profile, data=request.data)
if not serializer.is_valid():
return Response({'serializer': serializer, 'profile': profile})
serializer.save()
return redirect('profile-list')
**profile_detail.html**:
{% load rest_framework %}
<html><body>
<h1>Profile - {{ profile.name }}</h1>
<form action="{% url 'profile-detail' pk=profile.pk %}" method="POST">
{% csrf_token %}
{% render_form serializer %}
<input type="submit" value="Save">
</form>
</body></html>
### Using template packs
The `render_form` tag takes an optional `template_pack` argument, that specifies which template directory should be used for rendering the form and form fields.
REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default style is `horizontal`. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.
The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.
Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a "Login" form.
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField(
max_length=100,
style={'placeholder': 'Email', 'autofocus': True}
)
password = serializers.CharField(
max_length=100,
style={'input_type': 'password', 'placeholder': 'Password'}
)
remember_me = serializers.BooleanField()
---
#### `rest_framework/vertical`
Presents form labels above their corresponding control inputs, using the standard Bootstrap layout.
*This is the default template pack.*
{% load rest_framework %}
...
<form action="{% url 'login' %}" method="post" novalidate>
{% csrf_token %}
{% render_form serializer template_pack='rest_framework/vertical' %}
<button type="submit" class="btn btn-default">Sign in</button>
</form>
![Vertical form example](../img/vertical.png)
---
#### `rest_framework/horizontal`
Presents labels and controls alongside each other, using a 2/10 column split.
*This is the form style used in the browsable API and admin renderers.*
{% load rest_framework %}
...
<form class="form-horizontal" action="{% url 'login' %}" method="post" novalidate>
{% csrf_token %}
{% render_form serializer %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
</form>
![Horizontal form example](../img/horizontal.png)
---
#### `rest_framework/inline`
A compact form style that presents all the controls inline.
{% load rest_framework %}
...
<form class="form-inline" action="{% url 'login' %}" method="post" novalidate>
{% csrf_token %}
{% render_form serializer template_pack='rest_framework/inline' %}
<button type="submit" class="btn btn-default">Sign in</button>
</form>
![Inline form example](../img/inline.png)
## Field styles
Serializer fields can have their rendering style customized by using the `style` keyword argument. This argument is a dictionary of options that control the template and layout used.
The most common way to customize the field style is to use the `base_template` style keyword argument to select which template in the template pack should be use.
For example, to render a `CharField` as an HTML textarea rather than the default HTML input, you would use something like this:
details = serializers.CharField(
max_length=1000,
style={'base_template': 'textarea.html'}
)
If you instead want a field to be rendered using a custom template that is *not part of an included template pack*, you can instead use the `template` style option, to fully specify a template name:
details = serializers.CharField(
max_length=1000,
style={'template': 'my-field-templates/custom-input.html'}
)
Field templates can also use additional style properties, depending on their type. For example, the `textarea.html` template also accepts a `rows` property that can be used to affect the sizing of the control.
details = serializers.CharField(
max_length=1000,
style={'base_template': 'textarea.html', 'rows': 10}
)
The complete list of `base_template` options and their associated style options is listed below.
base_template | Valid field types | Additional style options
----|----|----
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
textarea.html | `CharField` | rows, placeholder, hide_label
select.html | `ChoiceField` or relational field types | hide_label
radio.html | `ChoiceField` or relational field types | inline, hide_label
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
checkbox.html | `BooleanField` | hide_label
fieldset.html | Nested serializer | hide_label
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label
# HTML & Forms
REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can be used as HTML forms and rendered in templates.
## Rendering HTML
In order to return HTML responses you'll need to use either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`.
The `TemplateHTMLRenderer` class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.
The `StaticHTMLRender` class expects the response to contain a string of the pre-rendered HTML content.
Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.
Here's an example of a view that returns a list of "Profile" instances, rendered in an HTML template:
**views.py**:
from my_project.example.models import Profile
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
class ProfileList(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'profile_list.html'
def get(self, request):
queryset = Profile.objects.all()
return Response({'profiles': queryset})
**profile_list.html**:
<html><body>
<h1>Profiles</h1>
<ul>
{% for profile in profiles %}
<li>{{ profile.name }}</li>
{% endfor %}
</ul>
</body></html>
## Rendering Forms
Serializers may be rendered as forms by using the `render_form` template tag, and including the serializer instance as context to the template.
The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:
**views.py**:
from django.shortcuts import get_object_or_404
from my_project.example.models import Profile
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.views import APIView
class ProfileDetail(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'profile_detail.html'
def get(self, request, pk):
profile = get_object_or_404(Profile, pk=pk)
serializer = ProfileSerializer(profile)
return Response({'serializer': serializer, 'profile': profile})
def post(self, request, pk):
profile = get_object_or_404(Profile, pk=pk)
serializer = ProfileSerializer(profile, data=request.data)
if not serializer.is_valid():
return Response({'serializer': serializer, 'profile': profile})
serializer.save()
return redirect('profile-list')
**profile_detail.html**:
{% load rest_framework %}
<html><body>
<h1>Profile - {{ profile.name }}</h1>
<form action="{% url 'profile-detail' pk=profile.pk %}" method="POST">
{% csrf_token %}
{% render_form serializer %}
<input type="submit" value="Save">
</form>
</body></html>
### Using template packs
The `render_form` tag takes an optional `template_pack` argument, that specifies which template directory should be used for rendering the form and form fields.
REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default style is `horizontal`. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.
The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.
Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a "Login" form.
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField(
max_length=100,
style={'placeholder': 'Email', 'autofocus': True}
)
password = serializers.CharField(
max_length=100,
style={'input_type': 'password', 'placeholder': 'Password'}
)
remember_me = serializers.BooleanField()
---
#### `rest_framework/vertical`
Presents form labels above their corresponding control inputs, using the standard Bootstrap layout.
*This is the default template pack.*
{% load rest_framework %}
...
<form action="{% url 'login' %}" method="post" novalidate>
{% csrf_token %}
{% render_form serializer template_pack='rest_framework/vertical' %}
<button type="submit" class="btn btn-default">Sign in</button>
</form>
![Vertical form example](../img/vertical.png)
---
#### `rest_framework/horizontal`
Presents labels and controls alongside each other, using a 2/10 column split.
*This is the form style used in the browsable API and admin renderers.*
{% load rest_framework %}
...
<form class="form-horizontal" action="{% url 'login' %}" method="post" novalidate>
{% csrf_token %}
{% render_form serializer %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
</form>
![Horizontal form example](../img/horizontal.png)
---
#### `rest_framework/inline`
A compact form style that presents all the controls inline.
{% load rest_framework %}
...
<form class="form-inline" action="{% url 'login' %}" method="post" novalidate>
{% csrf_token %}
{% render_form serializer template_pack='rest_framework/inline' %}
<button type="submit" class="btn btn-default">Sign in</button>
</form>
![Inline form example](../img/inline.png)
## Field styles
Serializer fields can have their rendering style customized by using the `style` keyword argument. This argument is a dictionary of options that control the template and layout used.
The most common way to customize the field style is to use the `base_template` style keyword argument to select which template in the template pack should be use.
For example, to render a `CharField` as an HTML textarea rather than the default HTML input, you would use something like this:
details = serializers.CharField(
max_length=1000,
style={'base_template': 'textarea.html'}
)
If you instead want a field to be rendered using a custom template that is *not part of an included template pack*, you can instead use the `template` style option, to fully specify a template name:
details = serializers.CharField(
max_length=1000,
style={'template': 'my-field-templates/custom-input.html'}
)
Field templates can also use additional style properties, depending on their type. For example, the `textarea.html` template also accepts a `rows` property that can be used to affect the sizing of the control.
details = serializers.CharField(
max_length=1000,
style={'base_template': 'textarea.html', 'rows': 10}
)
The complete list of `base_template` options and their associated style options is listed below.
base_template | Valid field types | Additional style options
-----------------------|-------------------------------------------------------------|-----------------------------------------------
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
textarea.html | `CharField` | rows, placeholder, hide_label
select.html | `ChoiceField` or relational field types | hide_label
radio.html | `ChoiceField` or relational field types | inline, hide_label
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
checkbox.html | `BooleanField` | hide_label
fieldset.html | Nested serializer | hide_label
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label

View File

@ -17,9 +17,9 @@ You can change the default language by using the standard Django `LANGUAGE_CODE`
LANGUAGE_CODE = "es-es"
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE_CLASSES` setting:
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE` setting:
MIDDLEWARE_CLASSES = [
MIDDLEWARE = [
...
'django.middleware.locale.LocaleMiddleware'
]
@ -90,7 +90,7 @@ If you're only translating custom error messages that exist inside your project
## How the language is determined
If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE_CLASSES` setting.
If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE` setting.
You can find more information on how the language preference is determined in the [Django documentation][django-language-preference]. For reference, the method is:
@ -105,7 +105,7 @@ For API clients the most appropriate of these will typically be to use the `Acce
[cite]: https://youtu.be/Wa0VfS2q94Y
[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/
[transifex-project]: https://explore.transifex.com/django-rest-framework-1/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/stable/topics/i18n/translation/#how-django-discovers-language-preference
[django-locale-paths]: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-LOCALE_PATHS

View File

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

View File

@ -8,7 +8,7 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o
---
**Note**: The code for this tutorial is available in the [encode/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox].
**Note**: The code for this tutorial is available in the [encode/rest-framework-tutorial][repo] repository on GitHub. Feel free to clone the repository and see the code in action.
---
@ -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
@ -150,7 +150,7 @@ At this point we've translated the model instance into Python native datatypes.
content = JSONRenderer().render(serializer.data)
content
# b'{"id": 2, "title": "", "code": "print(\\"hello, world\\")\\n", "linenos": false, "language": "python", "style": "friendly"}'
# b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}'
Deserialization is similar. First we parse a stream into Python native datatypes...
@ -165,7 +165,7 @@ Deserialization is similar. First we parse a stream into Python native datatype
serializer.is_valid()
# True
serializer.validated_data
# OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
# {'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}
serializer.save()
# <Snippet: Snippet object>
@ -175,11 +175,11 @@ We can also serialize querysets instead of model instances. To do so we simply
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
# [OrderedDict([('id', 1), ('title', ''), ('code', 'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', ''), ('code', 'print("hello, world")'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]
# [{'id': 1, 'title': '', 'code': 'foo = "bar"\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 3, 'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}]
## Using ModelSerializers
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes.
@ -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 5.0, using settings 'tutorial.settings'
Starting Development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
In another terminal window, we can test the server.
@ -321,42 +321,50 @@ You can install httpie using pip:
Finally, we can get a list of all of the snippets:
http http://127.0.0.1:8000/snippets/
http GET http://127.0.0.1:8000/snippets/ --unsorted
HTTP/1.1 200 OK
...
[
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 2,
"title": "",
"code": "print(\"hello, world\")\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 3,
"title": "",
"code": "print(\"hello, world\")",
"linenos": false,
"language": "python",
"style": "friendly"
}
]
Or we can get a particular snippet by referencing its id:
http GET http://127.0.0.1:8000/snippets/2/ --unsorted
HTTP/1.1 200 OK
...
{
"id": 2,
"title": "",
"code": "print(\"hello, world\")\n",
"linenos": false,
"language": "python",
"style": "friendly"
}
]
Or we can get a particular snippet by referencing its id:
http http://127.0.0.1:8000/snippets/2/
HTTP/1.1 200 OK
...
{
"id": 2,
"title": "",
"code": "print(\"hello, world\")\n",
"linenos": false,
"language": "python",
"style": "friendly"
}
Similarly, you can have the same json displayed by visiting these URLs in a web browser.
@ -371,8 +379,7 @@ We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].
[quickstart]: quickstart.md
[repo]: https://github.com/encode/rest-framework-tutorial
[sandbox]: https://restframework.herokuapp.com/
[venv]: https://docs.python.org/3/library/venv.html
[tut-2]: 2-requests-and-responses.md
[httpie]: https://github.com/jakubroztocil/httpie#installation
[httpie]: https://github.com/httpie/httpie#installation
[curl]: https://curl.haxx.se/

View File

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

View File

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

View File

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

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