Compare commits

...

3387 Commits

Author SHA1 Message Date
Carlton Gibson
07d3e1ec8f
Updated funding page to represent current scope. (#9686) 2025-04-10 12:05:06 +02:00
Ü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
Tom Christie
0323d6f895
Linting fixes (#7874)
* Fixed code quality issues

- Added '.deepsource.toml' file for continuous analysis on bug risk

- Remove `return` from `__init__()` method

- Remove duplicate dictionary key(s)

- Use `max` built-in to get the maximum of two values

- Remove redundant `None` default

- Remove unnecessary comprehension

Signed-off-by: ankitdobhal <dobhal.ankit@protonmail.com>

* Delete .deepsource.toml

* Delete test_fields.py

* Reintroduce file from accidental deletion

Co-authored-by: ankitdobhal <dobhal.ankit@protonmail.com>
2021-03-26 12:27:10 +00:00
Tom Christie
f83620dcc9
Version 3.12.4 (#7873)
* Version 3.12.4

* Tweak release notes
2021-03-26 09:27:01 +00:00
Tom Christie
72c155d8f4
Revert "pick deque instead of list (#7849)" (#7872)
This reverts commit ebcb8d5310.
2021-03-26 09:17:47 +00:00
Tom Christie
dffa612134
Fix release notes typo 2021-03-25 12:30:45 +00:00
Tom Christie
83ad265e13
Version 3.12.3 (#7866) 2021-03-25 12:23:23 +00:00
Jack
ebcb8d5310
pick deque instead of list (#7849)
Co-authored-by: Jack Zhang <jack.zhang@aspiraconnect.com>
2021-03-25 10:47:44 +00:00
Joe Michelini
71e6c30034
update SerializerMethodField example in docs (#7858)
* update SerializerMethodField example

* fix formatting
2021-03-22 12:08:19 +00:00
Mohammad Ashraful Islam
7e3dd9cd1b
Added fast-drf as a thirdparty package for making API development faster. (#7857) 2021-03-22 12:07:48 +00:00
Hasan Talha Yazıcı
0cddf097ca
Fix typo in docs (#7853) 2021-03-21 09:53:09 +00:00
Anton Zaslavskiy
b25ac6c5e3
Don't hit db to access user_id in TokenProxy (#7852) 2021-03-19 11:46:09 +00:00
Aristotelis Mikropoulos
67ebdd32cd
Reject PrimaryKeyRelatedField bool lookup values (#7597)
* Reject PrimaryKeyRelatedField bool lookup values

* Test PrimaryKeyRelatedField bool lookup rejection

* Fix indentation in test
2021-03-17 13:28:38 +00:00
Tom Christie
7b53960c3b
Revert "made Browsable API base template cachable: omit CSRF token when unnecessary (#7717)" (#7847)
This reverts commit 9c9ffb18f4.
2021-03-17 13:24:55 +00:00
Tom Christie
3e274146fc
Fix WSGI signature for DjangoTestAdapter (#7846)
Closes https://github.com/encode/django-rest-framework/issues/7132
2021-03-17 13:24:38 +00:00
Yuekui
a40bce50cd
No need to explictitly set None as default (#7373) 2021-03-16 13:29:13 +00:00
Jesse London
9c9ffb18f4
made Browsable API base template cachable: omit CSRF token when unnecessary (#7717)
HTML responses generated by the Browsable API otherwise generate
inconsistent ETAGs -- due to the presence of CSRF tokens in the response
-- even when the API is read-only, (and as such when the response
contains no resource-modifying forms, i.e. neither POST nor PUT forms,
which might require the CSRF token).

While the template was appropriately including CSRF tokens only within
POST and PUT forms, its AJAX overlay included the CSRF token in *every*
response, regardless of whether it would be needed.

This change brings the logic of the `script` block into line with that
of the rest of the template -- and such that read-only APIs (and really
the Browsable API pages of *any* read-only resources) will not
needlessly include the CSRF token, and will now be safely cachable -- by
both back-end systems and by the user agent.
2021-03-16 13:25:21 +00:00
Jeff Baumes
b0ca248d88
Correct the use of "to" (#7696) 2021-03-16 12:57:04 +00:00
Ömer Faruk Abacı
ce1568322a
Ordering filter bug with model property serializer field (#7609)
* Add failing tests for ordering filter with model property

* Fix get_default_valid_fields of OrderingFilter

* Filter model properties in get_default_valid_fields of OrderingFilter
2021-03-16 12:53:39 +00:00
Alex Hedlund
b256c46cb1
Render JSON fields with proper indentation in browsable API forms. (#6243)
* Fix JSONBoundField usage on nested serializers (#6211)

* Unify JSONBoundField as_form_field output between py2 and py3

When using json.dumps with indenting, in python2 the default formatting
prints whitespace after commas (,) and python3 does not. This can be
unified with the separators keyword argument.
2021-03-15 10:44:03 +00:00
Henryk Plötz
ff625ecff5
Document object level permissions gotchas (#7446)
* Document the limitation that object level permissions do not apply to object creation. See for example #6409.

* Add overview of three different ways to restrict access
2021-03-15 10:28:45 +00:00
Ömer Faruk Abacı
883f6fe814
Rename django-extra-fields to drf-extra-fields (#7833) 2021-03-11 11:39:06 +00:00
Carlton Gibson
f070619061
Updated tox/travis to point to Django main branch. (#7827) 2021-03-11 10:26:11 +00:00
Tom Christie
39a98c80a6 Fix 'get_page_number' implementation 2021-03-11 09:21:22 +00:00
Tom Christie
c05cbe2da2
Update pagination.py
Include `last_page_strings` logic *inside* the `get_page_number method.
2021-03-10 12:50:59 +00:00
Max Morlocke
ffe11d41bd
upgrade pytest+pytest-django to eliminate dependencies on six (#7672)
* upgrade to latest version of pytest+pytest-django to eliminate dependency on six

* rollback pytest to 6.1 as py35 is dropped in 6.2

Co-authored-by: Tom Christie <tom@tomchristie.com>
2021-03-10 12:45:47 +00:00
Feanil Patel
c78f992176
Make the doc on overriding the default permission classes more clear. (#7661) 2021-03-10 12:44:17 +00:00
Eshaan Bansal
4f3cd8c7b0
add django-rest-durin to 3rd party auth libs [docs] (#7615)
Co-authored-by: Tom Christie <tom@tomchristie.com>
2021-03-10 12:40:45 +00:00
John Alexis Munera
cef74d1726
Add rest-framework-actions to Third Party Packages (#7688)
This pull request adds rest-framework-actions to Third Party Packages, under Views

rest-framework-actions can be found on PyPi here: https://pypi.org/project/rest-framework-actions/

Co-authored-by: Tom Christie <tom@tomchristie.com>
2021-03-10 12:37:06 +00:00
sarath ak
6f6d402d04
Allow 'get_page' method for overriding #7626 (#7652) 2021-03-10 12:32:10 +00:00
Pierre Chiquet
c603b98403
Fix OpenAPISchema rendering for timedelta (#7641)
* Add failing test when rendering to json a schema with timedelta

* Fix JSONOpenAPIRenderer for fields with default=timedelta()

* fix isort

* fix test for python 3.5

Co-authored-by: Pierre Chiquet <pierre.chiquet@ubikey.fr>
2021-03-10 12:03:15 +00:00
PaulGilmartin
c69e2e4eaa
Add graphwrap to third-party-packages.md (#7819)
* Add graphwrap to third-party-packages documentation

* Fix typo in third party packages docs

* Remove additional newline

Co-authored-by: Paul Gilmartin <paulgilmartin@Pauls-MacBook-Pro.local>
Co-authored-by: Tom Christie <tom@tomchristie.com>
2021-03-10 09:02:38 +00:00
Dmitry Mugtasimov
a3ae8ea77e
Do not do SELECT count(*) FROM ... if pagination is not requested (#6098)
* Do not do `SELECT count(*) FROM ...` if pagination is not requested

* Update pagination.py

Co-authored-by: Tom Christie <tom@tomchristie.com>
2021-03-09 12:06:12 +00:00
Romain Rigaux
750bad0a58
Actually use the loginUser arguments in the example (#7714) 2021-03-09 12:00:51 +00:00
Vitor Hugo
4e0d6c4118
Update default.css (#7643)
When I apply a theme to the bootstrap used in the project, boolean inputs are out of line with the rest of the form. With this small payment, this no longer occurs.
2021-03-09 11:54:58 +00:00
Celia Oakley
747fef6134
Add django-rest-authemail to Third Party Packages (#7679)
* Add django-rest-authemail to Authentication

* Add django-rest-authemail to Third Party Packages
2021-03-09 11:51:52 +00:00
Chris Guo
82b8a64a02
docs: add example for caching (#7118) 2021-03-09 11:49:19 +00:00
Berkant
95ae92ef23
Fix #7706 (#7724)
Handle non-dict values for NestedSerializer during BrowsableAPI
rendering.
2021-03-09 11:34:18 +00:00
David Kerkeslager
05512160ab
Respect allow_null=True on DecimalFields (#7718)
* Handle None in to_representation()
* Return None as '' in to_representation() when coerce_to_string=True
* Handle '' as None in to_internal_value(), for symmetry with
  to_representation(), and because the empty concept doesn't make sense
  for Decimal.
2021-03-09 10:49:03 +00:00
Nathan Glover
a89a6427d3
#7703 adding deprecations to release notes (#7716)
* #7703 adding deprecations to release notes

* #7703 - update link for gh6687
2021-03-09 10:22:37 +00:00
Cas Ebbers
393f867995
Overlooked translation in search.html (#7551) 2021-03-09 10:21:11 +00:00
kuter
e9a54e38e1
add support for Yes/No literals with BooleanField (#7701) 2021-03-09 10:17:30 +00:00
Igor Polyakov
b463878132
Commas added in README (#7730)
To make it more comfortable for users to copy and paste snippets
2021-03-09 10:16:19 +00:00
Alex Cotsarelis
e32ebc4199
Docs: DjangoModelPermissions works on views with get_queryset() method. (#7693)
Sentinel querysets not needed after v3.1.2
2021-03-08 12:09:17 +00:00
Jean-Pierre Merx
234527959d
Have options example in documenting-your-api.md to return a Response (#7639)
It was returning data which is not correct. Closes #7638.

Co-authored-by: Jean-Pierre Merx <jean-pierre.merx@aictivate.com>
2021-03-08 12:08:26 +00:00
arcanemachine
ef112f5017
Provide example for dict in ValidationError detail (#7788)
Added a sentence describing the use of a dictionary as the `detail` argument of a ValidationError, and how it can be used to add field-level errors during object-level validation.
2021-03-08 11:46:35 +00:00
Tom Christie
ec29ff8a80
Delete ISSUE_TEMPLATE.md 2021-03-03 15:45:40 +00:00
Tom Christie
ee51145574
Update config.yml 2021-03-03 15:43:57 +00:00
Tom Christie
37b8d2018d
Create 1-issue.md 2021-03-03 15:42:38 +00:00
Tom Christie
db0bb5ef42
Update config.yml 2021-03-03 15:39:22 +00:00
Tom Christie
c9a00bdb2c
Update config.yml 2021-03-03 15:33:14 +00:00
Tom Christie
344235ab37
Create config.yml 2021-03-03 15:32:19 +00:00
Tom Christie
1deb8ae370
Update FUNDING.yml 2021-03-03 15:06:42 +00:00
Jonathan Mortensen
de7468d0b4
support multi db atomic_requests (#7739) 2021-03-03 11:15:39 +00:00
Usoof Mansoor
8f6d2d2f9c
Update docs link to Django OAuth Toolkit. (#7737) 2021-03-02 08:26:31 +01:00
Asif Saif Uddin
1ec0f86b58
Dj32 (#7713)
adds django 3.2 line to the build matrix
2021-02-16 13:17:29 +01:00
Tonye Jack
3e956df6eb Fixed test 2021-02-16 11:28:38 +01:00
Sebastian Jordan
19655edbf7
Handle tuples same as lists in ValidationError detail context (#7647) 2021-01-06 13:13:34 +00:00
Adrian Coveney
3db8877889 Clarify documentation for TemplateHTMLRenderer
Clarify that the response from a view may need to be modified to provide TemplateHTMLRenderer with a dict for it to use.
2020-12-30 09:11:38 +01:00
Tom Christie
8351747d98
Update index.md 2020-12-21 16:41:12 +00:00
Erwin Junge
bb133522ef Small documentation fix 2020-11-22 12:21:30 +01:00
babaroga
3ab8d4706e changed unicode to str 2020-11-21 18:25:55 +01:00
Karol Onyśko
96993d817a
Changed url to django docs so it points to the stable version (#7628)
Co-authored-by: Karol Onyśko <karol.onysko@cic.com>
2020-11-12 18:42:42 +01:00
Xavier Ordoquy
2b266897c9
Merge pull request #7634 from ge0rg/parser-docs
docs: outline the difference between JSON and form parsers. Fix #7633
2020-11-12 11:52:21 +01:00
Georg Lukas
6da94e5700 docs: outline the difference between JSON and form parsers. Fix #7633 2020-11-12 09:48:18 +01:00
Xavier Ordoquy
3578683a69
Merge pull request #7593 from encode/version-3.12.2
Version 3.12.2
2020-11-05 23:15:45 +01:00
bhealy-indeed
80444a0afb
nit: Typo fix (#7629) 2020-11-05 22:21:30 +01:00
Megan Gross
606df83885
Update throttling.md (#7606)
There were recent updates to the `@action` decorator calling a little more attention to the kwargs it accepts. 
I thought it would be useful to also provide an example in the throttling section of how those kwargs can be used to define/override throttle_classes through the action decorator as well.
2020-11-05 09:43:45 +01:00
James S Blachly, MD
56e4508123
Fix #7612 (#7622) 2020-11-02 09:45:43 +01:00
Jon Dufresne
9c29f5013f Use Python 3.9 release in Travis configuration 2020-11-01 20:36:08 +01:00
Xavier Ordoquy
47cfbdac97 Translations updated from transifex and compiled 2020-10-13 22:05:24 +02:00
Xavier Ordoquy
a0115e66d4 restore the transifex configuration
This reverts commit 6957aaae85.
2020-10-13 21:30:05 +02:00
David Smith
04e0c2b9ab
Bumped Markdown version to 3.3 (#7590) 2020-10-13 17:27:08 +01:00
Tom Christie
3799633cde Version 3.12.2 2020-10-13 14:17:53 +01:00
Pawel
95f0b0867a
Documentation: improve the action decorator documentation (#7316) (#7380)
* Documentation: improve the action decorator documentation (#7316)
2020-10-13 08:32:38 +02:00
Aarni Koskela
0bdd537cc4
Ignore derivations of BrowsableAPIRenderer in OpenAPI schema (#7497)
* Ignore derivations of BrowsableAPIRenderer in OpenAPI schema
* Improve test_renderer_mapping test

Co-authored-by: Carlton Gibson <carlton.gibson@noumenal.es>
2020-10-12 16:40:26 +02:00
Thomas Leese
eff97efa28
Don't catch exceptions in get_queryset (#7480)
In the `to_internal_value` method of the primary key and slug related fields, `TypeError`s and `ValueError`s are caught from `self.get_queryset().get(...)` and presented to the user. This works fine for most cases, but can cause problems if the exception is coming from `self.get_queryset()` rather than from the `.get(...)`.

It means errors in the `get_queryset` method can be hidden and presented back to the user as though, for example, the input provided to the `to_internal_value` was the wrong type, whereas in reality there's a bug in the `get_queryset` method and therefore it should bubble up and be exposed as a server error.

I've decided to fix this because twice now I've had to debug why I'm seeing `invalid_type` errors from my serializer (errors like `wrong pk type - int` when the `pk` type on my model is `int`) when the real problem was a bug in my custom `get_queryset` method.
2020-10-10 18:02:21 +01:00
Adam Johnson
fd5e1a745a
Fixed some documentation headings to use a space (#7364) 2020-10-10 17:42:59 +01:00
zach valenta
ffde169102
Add docs link to to_internal_value() (#7476) 2020-10-10 17:36:15 +01:00
Thomas Riccardi
1ef192811c
Add missing quoting for data keyword argument in serializer doc (#7587) 2020-10-10 17:34:39 +01:00
Adam Johnson
563b043768
Error on deprecation and pending deprecation warnings (#7586)
Erroring on deprecation or pending deprecation warnings means they are caught early. This will avoid the cycle of releasing with 'support for Django X', then chasing all the deprecation warnings one-by-one. Instead, when a new Django version is added to the test matrix, it will fail until all the relevant warnings are fixed. This avoids passing these warnings on to users, some of whom don't upgrade until they are all fixed.
2020-10-10 17:34:00 +01:00
David Smith
79c37d0dc3
Return NotImplemented sooner for ErrorDetail equality test (#7531)
The test suite raises warnings when tested against Python 3.9
`DeprecationWarning: NotImplemented should not be used in a boolean context`

Where `r` returns `NotImplemented` then this change returns `NotImplemented` first to avoid the comparison test.
2020-10-09 12:21:22 +01:00
Kryštof Pilnáček
79daf315c4
Fix: authtoken.TokenProxy cannot be proxy when not installed (#7571)
closes https://github.com/encode/django-rest-framework/issues/7442
2020-10-09 12:16:15 +01:00
Adam Johnson
931b34e7de
Remove tox-venv from Travis setup (#7585)
This was added in #6139. However it seems [tox-venv is no longer maintained](https://github.com/tox-dev/tox-venv), the related [virtualenv issue has been closed](https://github.com/pypa/virtualenv/issues/355), and I suspect with the virtualenv rewrite fixed the problem with site.py and the warnings referred to for the DRF tests.
2020-10-09 11:09:34 +01:00
Adam Johnson
7921e9af43
Fix RemovedInDjango40Warning for middleware get_resopnse() (#7513)
Fixes #7417.

Fixes all these issues seen with `tox -e py38-django31`:

```
  /Users/chainz/Documents/Projects/django-rest-framework/tests/test_request.py:208: RemovedInDjango40Warning: Passing None for the middleware get_response argument is deprecated.
    SessionMiddleware().process_request(self.wrapped_request)

tests/test_requests_client.py: 1 test with warning
tests/test_testing.py: 4 tests with warnings
tests/test_throttling.py: 1 test with warning
tests/authentication/test_authentication.py: 4 tests with warnings
tests/browsable_api/test_browsable_api.py: 4 tests with warnings
  /Users/chainz/Documents/Projects/django-rest-framework/rest_framework/authentication.py:139: RemovedInDjango40Warning: Passing None for the middleware get_response argument is deprecated.
    check = CSRFCheck()
```
2020-10-09 10:48:03 +01:00
Mopsan
5e23b559f8
Fix example override of SchemaGenerator.get_schema() 2020-10-09 09:38:11 +01:00
Xavier Ordoquy
2e721cdbc8
Merge pull request #7436 from markstory/patch-1
Fix broken links in documenting API section
2020-10-06 22:26:22 +02:00
Xavier Ordoquy
ebc1ebf0c4
Merge pull request #7481 from smithdc1/app-config
default_app_config application variable is deprecated in Django 3.2
2020-10-06 22:16:29 +02:00
Xavier Ordoquy
fdf277a782
Merge pull request #6843 from max-wittig/patch-1
docs(tutorial): add missing permission import in viewsets
2020-10-06 21:42:30 +02:00
स्पर्श
6a45a6a36f
Fix broken machinalis links (#7580)
#7572 #7423 #7573  all are related to this
2020-10-06 13:14:11 +01:00
Xavier Ordoquy
d635bc9c71
Merge pull request #7539 from verhovsky/patch-2
Correct indentation
2020-10-06 13:04:08 +02:00
Xavier Ordoquy
9dc10d2af7
Merge pull request #7577 from Exifers/patch-1
Documentation: use retrieve instead of read for Viewset
2020-10-05 21:54:33 +02:00
Xavier Ordoquy
a849627f88 Fixes #7538 - use retrieve action name instead of detail 2020-10-05 21:48:07 +02:00
Emmanuel Meric de Bellefon
86ec3da2da
Update 6-viewsets-and-routers.md 2020-10-05 20:56:42 +02:00
Adam Johnson
91916a4db1
Fix NullBooleanField warning (#7565)
The argument to Field is 'allow_null'.
2020-09-30 13:47:06 +01:00
Tom Christie
be87eb43b3 Update release notes with 3.11.1, 3.11.2 2020-09-30 09:44:31 +01:00
Tom Christie
a03c85225f
Update test_templatetags.py 2020-09-30 09:10:36 +01:00
Xavier Ordoquy
c7ba30825a
Merge pull request #7559 from AliMirlou/patch-1
Fix typo in release notes
2020-09-29 10:48:51 +02:00
Ali Mirlou
9edd5dfe5d
Fix typo in release notes 2020-09-28 23:15:30 +03:30
Tom Christie
05b3865838 Version 3.12.1 2020-09-28 16:18:23 +01:00
Hugo Rodger-Brown
995188f8c5
Add missing TokenProxy migration (#7557)
Fixes #7554
2020-09-28 16:16:18 +01:00
Tom Christie
68b23075a2
Add date to 3.12 release. 2020-09-28 10:54:52 +01:00
Tom Christie
6f7aad8ffa
Placeholder for 3.12 release (#7379)
* Placeholder for 3.12 release

* Updating release notes

* Updating release notes

* Updating release notes

* Update release notes

* Fix typo

* Basic structure for release announcement

* 3.12 release notes

* Version 3.12.0
2020-09-28 10:47:50 +01:00
Esieboma Jeremiah
9ee67bbff7
corrects typographical error in line 118 (#7553) 2020-09-28 08:52:17 +01:00
Tom Christie
ae649336b1
Drop urlize_quoted_links (#7548) 2020-09-23 15:39:06 +01:00
T. Franzel
c6e24521da
Add third-party schema library drf-spectacular to docs (#7540)
Co-authored-by: T. Franzel <13507857+tfranzel@users.noreply.github.com>
2020-09-21 11:39:35 +01:00
Борис Верховский
98761e4ebb
Correct indentation 2020-09-16 09:43:27 -04:00
johnthagen
e17779c47b
Make it more clear to add django_filters to INSTALLED_APPS in docs. (#7535) 2020-09-14 19:46:51 +02:00
Mohammad Amin Haghpanah
04f39c42ee
Add drf-psq package to docs (#7451)
* Add drf-psq to third party packages

* Add drf-psq to permissions.md

this package is an extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.

Co-authored-by: Salar Nasiri <salarnasiri@users.noreply.github.com>
2020-09-09 08:54:05 +01:00
Rafael Henter
327cbef299
Add Django API Client to the third party packages (#7440) 2020-09-08 15:44:03 +01:00
Francisco Couzo
6b632c15b1
Remove unnecessary type conversions (#7526) 2020-09-08 15:42:01 +01:00
Michael K
ddcd8b539b
Run tests against Python 3.9 (#7517)
3.9.0 final is expected on Monday, 2020-10-05
See https://www.python.org/dev/peps/pep-0596/#schedule

Also mention Django 3.1 compat where missing.
2020-09-08 15:40:21 +01:00
Adam Johnson
410575dace
Replace all url() calls with path() or re_path() (#7512)
* url() is deprecated in Django 3.1

* update given feedbacks on url() is deprecated in Django 3.1

* Fix test_urlpatterns.py to continue testing mixed re_path() and path()

* Fix one missed reference

Co-authored-by: sanjusci <sanju.sci9@gmail.com>
2020-09-08 15:32:27 +01:00
David Smith
9990b59281
Dropped test compatibility shims for Django <2.2. (#7523) 2020-09-07 20:00:17 +02:00
David Smith
d5461e93fe
Bump flake8 to 3.8.3 (#7521) 2020-09-05 10:02:27 +02:00
David Smith
b8ab30683a default_app_config application variable is deprecated in Django 3.2 2020-09-03 21:57:41 +01:00
Charles
35c0abf24e
Change Token.generate_key to a Classmethod (#7502)
* adds classmethod decorator to generate_key and test to confirm change is acceptable

* self -> cls
2020-09-03 11:51:03 +01:00
Ryan P Kilby
f323049ecc
Fix pk-only optimization for properties (#7142)
* Add callable/prop tests for pk-only optimization

* Fix related field pk-only optimization for props
2020-09-03 11:49:15 +01:00
Bob Thomas
b3e02592d0
Add support for Django 3.1 JSONField (#7467)
Django 3.1 adds a new generic JSONField to replace the PostgreSQL-specific one. This adds support for the new field type, which should behave the same as the existing PostgreSQL field.

Django's new JSONField also includes support for a custom "decoder", so add support for that in the serializer field.
2020-09-03 11:47:11 +01:00
johnthagen
7f3a3557a0
Add drf_ujson2 reference (#7494) 2020-08-25 15:15:17 -07:00
Vlad
e215db206a
Updated url()'s with path() and re_path() (#7492) 2020-08-25 13:50:02 +02:00
Justin Duke
48c327c681
Fix schema typo (#7491) 2020-08-24 03:44:34 -07:00
Борис Верховский
374c0d4142
Punctuation fix (#7488)
* Punctuation fix

* more punctuation
2020-08-20 13:23:59 +01:00
David Smith
355afcf64b
isort v5 (#7484) 2020-08-17 13:26:56 -07:00
Vibhu Agarwal
3d708ac700
Fix broken docs link (#7473) 2020-08-11 16:36:23 -07:00
Ryan P Kilby
1e383f103a
Check extra action func.__name__ (#7098) 2020-08-05 21:29:47 -07:00
Michael K
0d2bbd3177
Fix Request docstring kwarg names (#7443) 2020-08-05 16:51:06 -07:00
Masked Man
17f2b39bdb
Fix docs issue (#7418) 2020-08-05 15:33:30 -07:00
Tom Christie
7d5155e0eb
Resize sponsor images for new GitHub layout (#7465) 2020-08-05 14:13:01 +01:00
Paul Watts
559088463b
Update an example to not use oppressive language (#7439)
* Update an example to use less oppressive language

For reference: https://tools.ietf.org/id/draft-knodel-terminology-00.html

* Code review update

Blocklisted -> blocked.
2020-07-29 20:21:13 +01:00
Mark Story
30ca04df83
Fix broken links in documenting API section
The changed links were not working on the documentation site. I'm not 100% sure that these changes are correct but they generate working links in the GitHub previews.
2020-07-29 09:58:53 -04:00
Tom Christie
c252c3dfa5
Update sponsors (#7434)
* Adjusted token admin to map to user ID.

Closes #6131.

* Adds a proxy model for Token that uses the user.pk, rather than it's own.
* Adjusts Admin to map back from User ID to token instance.

* Update sponsors

Co-authored-by: Carlton Gibson <carlton.gibson@noumenal.es>
2020-07-29 14:55:10 +01:00
John Vandenberg
599e2b183d
urlpatterns: Remove unnecessary branching (#7405)
Functions path and register_converter are constants.
2020-07-23 19:26:35 +02:00
Anirudh Bagri
1e164c5eeb
Just smalling cleaning up, causing confusion (#7426) 2020-07-23 17:34:34 +02:00
Mariusz Felisiak
4b06e0a5a1
Fix tests crash on SQLite without JSON1 extension. (#7409) 2020-07-12 11:08:40 +02:00
Anton Agestam
76232437d4
Allow type checkers to make serializers generic (#7385) 2020-07-07 10:05:36 +01:00
Minjae Kim
d46d5cbaaa
Not include charset when charset is None (#7400) 2020-07-07 09:58:32 +01:00
Oğuzhan Çelikarslan
36bd1b30d8
drf-encrypt-content added into third party list in documentation's serializer page (#7398) 2020-07-06 11:56:46 +01:00
Xavier Ordoquy
28983cb28b
Merge pull request #7290 from encode/xordoquy/fix_action_namespace
Fix viewsets action urls with namespaces (#7287)
2020-07-03 20:18:18 +02:00
Dhaval Mehta
5ce237e004
Corrected regex serialization for OpenAPI. (#7389)
* replace \Z by \z in regex

* fix test cases for Django >= 3.0

* fix isort

* Added comment for why `\z`.

Co-authored-by: Carlton Gibson <carlton@noumenal.es>
2020-06-28 14:28:59 +02:00
Ngô Thanh Lợi (Leonn)
19915d1917
Fix docs typo (#7387) 2020-06-22 14:24:50 -07:00
w
7a04269209
Fixed docs typo (#7382) 2020-06-19 10:29:41 -07:00
Carlton Gibson
e18e40d6ae
Updated Schema docs. (#7268) 2020-06-16 13:33:48 +02:00
Carlton Gibson
e2bd3b6a57
Adjusted token admin to map to user ID. (#7341)
Closes #6131.

* Adds a proxy model for Token that uses the user.pk, rather than it's own.
* Adjusts Admin to map back from User ID to token instance.
2020-06-15 11:43:09 +01:00
Rignon Noël
b677b7b15d
Update link to dry-rest-permissions (#7374)
dry-rest-permissions was no maintain since 2018, so FJNR-inc just got a new PyPi version on their fork
2020-06-11 18:33:04 +01:00
Nikhil Kumar
9dc7021770
Fixed h4 rendering 2020-06-01 14:03:10 -04:00
Nikhil Kumar
505a69cf43
Fixed heading markdown 2020-06-01 13:49:43 -04:00
Asif Saif Uddin
acbd9d8222
django 3.1 alpha on matrix (#7334)
* django 3.1 alpha on matrix

* django 3.1 alpha on matrix
2020-05-15 08:40:47 +01:00
Jair Henrique
bb795674f8
Drop all compat support to Django < 2 urls (#7337) 2020-05-14 20:31:38 +02:00
Jair Henrique
65add6679d
Remove unnecessary test skips (#7336) 2020-05-14 14:49:04 +01:00
Jair Henrique
b83e9121f3
Remove compat urls for Django < 2.0 (#7335) 2020-05-14 14:48:14 +01:00
Jair Henrique
aed74961ba
Remove compat for ProhibitNullCharactersValidator (#7333) 2020-05-14 08:24:09 +01:00
johnthagen
fccfdd21c0
Remove object inheritance in docs (#7332) 2020-05-13 17:54:46 -07:00
Carlton Gibson
8bb9a37f4b
Removed duplicated class RemovedInDRF314Warning.
Added accidently in e888fc11c7

Co-authored-by: Jair Henrique <jair.henrique@gmail.com>
2020-05-13 20:41:53 +02:00
Kevin Brown
e888fc11c7
Merge NullBooleanField with BooleanField(allow_null=True) (#7122)
* Make `NullBooleanField` subclass `BooleanField`

This removes a lot of the redundancy that was in place becuase we
were not doing this. This maintains the `None` initial value that
was previously present, as well as disallowing `allow_null` to be
passed in.

* Remove special case for mapping `NullBooleanField`

In newer versions of Django, the `NullBooleanField` is handled the
same way as a `BooleanField(null=True)`. Given that we also support
that combination, and that our own `NullBooleanField` behaves in the
same manner, it makes sense to remove the special casing that exists
for it.

* Add test for BooleanField(null=True, choices)

* Remove special case for NullBooleanField

* Adjust mapping tests for NullBooleanField

* Fixed linting error

* Raise deprecation warning when NullBooleanField is used

* Fix linting issue in imports
2020-05-13 14:59:04 +01:00
Ryan P Kilby
089162e6e3
Fix ModelSerializer unique_together handling for field sources (#7143)
* Fix ModelSerializer unique_together field sources

Updates ModelSerializer to check for serializer fields that map to the
model field sources in the unique_together lists.

* Ensure field name ordering consistency
2020-05-13 11:11:26 +01:00
Derek
00e6079e94
Nginx basic auth tutorial moved (#7324) 2020-05-11 16:29:31 +01:00
Asif Saif Uddin
1260ed424a
jquery 3.5.1 (#7313)
* jquery 3.5.1
2020-05-11 13:08:40 +01:00
Kamil Sampolski
f07f48a5da
Updating documentation / switching from url to path (#7237)
* Update README.md

We should use path instead of url in urlpatterns,

* Update index.md

We should use path instead of url in urlpatterns

* Update README.md

We should use path instead of url in urlpatterns
2020-05-11 11:01:00 +01:00
Ryan P Kilby
8a38991d6a
Fix SearchFilter.must_call_distinict for annotation+m2m (#7146)
* Test SearchFilter annotation+m2m distinct

* Fix SearchFilter annotation+m2m distinct
2020-05-11 10:55:39 +01:00
Daniil Okhlopkov
4ac0fae75b
use @admin decorator (#7022) 2020-05-11 09:04:37 +01:00
Asif Saif Uddin
56ff382b17
updated required versions of dependencies (#7312) 2020-05-05 14:05:29 +01:00
Sardorbek Imomaliev
46be2ffd34
Fix schema endpoint example (#7178)
* Fix schema endpoint example

Endpoint `schema` collides with `schema` class variable `schema` which is use for specification generation

* Update metadata.md

Co-authored-by: Tom Christie <tom@tomchristie.com>
2020-05-05 14:04:35 +01:00
Xavier Ordoquy
5b388e8f83
Merge pull request #7307 from santos22/docs
Update index.md
2020-05-02 12:23:42 +02:00
Santos Solorzano
256f076df2
Update index.md
- Dropped Django 1.11, 2.0, 2.1 support
2020-05-01 14:16:18 -07:00
Mathieu Pillard
d7777ea10f
Pass custom code to PermissionDenied if permission class had one set (#7306) 2020-05-01 10:22:36 +01:00
ADimeo
4349ce1a54
Fix broken documentation link (#7305) 2020-04-30 13:14:27 +01:00
Ryan P Kilby
900773ad06
Minor test improvements (#7297)
* Pass data via response instead of renderer_context

Instead of relying on internal implementation details to get a reference
to the response or view, attach these directly to the returned response.

* Remove unused method
2020-04-29 11:21:42 +01:00
Rick van Hattem
5828d8f7ca
Changed hardcoded /tmp/ directory to autodetect from system (#7292) 2020-04-29 11:20:02 +01:00
Ryan P Kilby
e275b9036a
Allow context to be provided to get_serializer (#7298)
* Test generics serializer behavior

* Allow context to be provided to get_serializer
2020-04-29 11:19:44 +01:00
Robert Singer
05a59095ce
Adds drf-typed-views to 3rd party packages (#7293) 2020-04-27 12:12:13 -07:00
Xavier Ordoquy
bda84372d4 Fix viewsets action urls with namespaces (#7287)
Use the current request's namespace to resolve action urls.
2020-04-25 19:50:59 +02:00
Victor Mireyev
3eef5f47f3
Fix typo in links (#7289)
Reference-style link should be enclosed in square brackets. Otherwise it is treated as an inline-style link.
2020-04-24 22:38:01 -04:00
Victor Mireyev
26cd52a461
Fix markdown lists formatting. (#7288) 2020-04-24 15:17:35 +01:00
Dhaval Mehta
e1336387d1
Added example for pagination in schemas. (#7275) 2020-04-24 16:13:13 +02:00
Matthaus Woolard
812f254bbd
SearchFilter to support JSONField and HStoreField (#7121)
* SearchFilter to support Custom query Transforms

Since Some fields support `__` as a custom Transform for query lookups we needed to update the m2m checking code to handle search_fields that contain __ that are not relationships.

* Update documentation on SearchFilter to include references to JSON and HStore Fields.
2020-04-23 09:38:14 +01:00
spollard
13c08370e7
Remove a few submenu scroll bars on docs site (#7283)
Remove the scroll bars for the "Topics" and "Tutorial" submenus on the website. Previously, unnecessary scroll bars appeared in Firefox and Chrome. Applying this change allows "Community" and "API Guide" submenues to still have scroll bars as necessary.
2020-04-23 09:36:46 +01:00
Byron Peebles
676aa77223
Fix punctuation in system check (#7281) 2020-04-20 16:40:05 -07:00
Tasawar Hussain
8cba4f87ca
Updates Ruby on Rails reference link (#7269)
The cited sentences are from actually the action controller docs from ruby on rails
2020-04-13 03:58:51 +01:00
Carlton Gibson
b2497fc245 Convert openapi.AutoSchema methods to public API. 2020-04-09 20:05:16 +02:00
Carlton Gibson
d45e0005f3 Updated deprecation warnings for 3.12 2020-04-09 20:05:16 +02:00
Carlton Gibson
b1bfff4f1c Revert "Schemas: Improved decimal handling when mapping ChoiceField. (#7264)"
This reverts commit 1872bde462.
2020-04-09 19:35:46 +02:00
Dhaval Mehta
1872bde462
Schemas: Improved decimal handling when mapping ChoiceField. (#7264) 2020-04-09 19:18:00 +02:00
Clinton Blackburn
603aac7db1
Corrected OpenAPI schema type for DecimalField (#7254) 2020-04-09 19:16:17 +02:00
Dhaval Mehta
41f27c3b43
Schemas: Don't generate component for DELETE method. (#7229) 2020-04-09 19:10:50 +02:00
François Freitag
e6c1afbcf9
Tighten checks for invalid field name in ordering (#7259)
Django master removed the ORDER_PATTERN regex with commit
513948735b
2020-04-07 12:28:09 +02:00
tsurutan
0c8eb91737
Fixed docs' custom render example. (#7171) 2020-04-06 17:09:23 +02:00
Rotzbua
a7a362813b
Update optional dependencies list. (#7243)
Co-authored-by: Ryan P Kilby <kilbyr@gmail.com>
2020-04-06 15:54:30 +02:00
David Szotten
734c534dbb
update release note to include full message (#7251)
the truncation changes the meaning somewhat..
2020-03-31 14:53:33 +01:00
Ryan P Kilby
dd33ebb4e2
Add Request repr (#7239) 2020-03-29 12:01:14 +01:00
Rotzbua
57e7cc21e1
Remove unavailable script (#7244) 2020-03-24 11:52:17 -07:00
Artur Barseghyan
5cc6ace9c4
Update third-party-packages.md (#7175) 2020-03-20 11:28:51 -07:00
Mahmoud Adel
8b5d3437f9
Add django-rest-auth fork to docs (#7227) 2020-03-17 15:45:45 -07:00
0dysseas
be96939ec1
Fix serializer example in docs (#7233) 2020-03-17 09:49:19 -07:00
Ryan P Kilby
86aa549832
Drop Django 2.1 and below. (#7225) 2020-03-11 14:51:42 +01:00
Ryan P Kilby
908f91d8ef
Set action for HEAD requests (#7223)
* Test viewset action attr

* Add 'head' to viewset actions map
2020-03-09 09:43:02 +00:00
Tom Christie
4a98533746
Fix - run test_head_request_against_viewset method (#7219) 2020-03-05 13:18:48 +00:00
Tom Christie
73f7bf4941
Extra action detection is too permissive. Add failing test + fix (#7217)
* Add failing test

* Add failing test++

* Make get_extra_action less permissive
2020-03-05 10:18:22 +00:00
Tom Christie
ddfb9672ae
Release notes for 3.11.0 (#7214) 2020-03-04 13:31:43 +00:00
Martin Desrumaux
6a23fa0649
OpenAPI: Make operationId camelCase, matching spec examples. (#7208) 2020-03-03 17:51:51 +01:00
Martin Desrumaux
609f708a27
Fix schema generation for ObtainAuthToken view. (#7211) 2020-03-03 13:27:34 +01:00
Martin Desrumaux
8aa8be7653
Implement OpenAPI Components (#7124) 2020-03-02 19:35:27 +01:00
Martin Desrumaux
797518af6d
OpenAPI: Warn user about duplicate operationIds. (#7207) 2020-03-02 16:44:06 +01:00
Martin Desrumaux
5b16a17242
OpenAPI: Allow customizing operation name. (#7190) 2020-03-02 16:40:18 +01:00
Mateusz Legięcki
94a09149b6
OpenAPI: Use 201 status code for POST requests. (#7206) 2020-03-02 16:32:26 +01:00
Dhaval Mehta
2a5c2f3f70
Added OpenAPI tags to schemas. (#7184) 2020-02-28 12:06:03 +01:00
Samuel Dion-Girardeau
e32ffbb12b
Fix docs code example (#7201) 2020-02-24 16:33:00 -08:00
Prayash Mohapatra
764dabd29e
Update writeable nested serializer doc (#7198) 2020-02-20 10:55:13 +00:00
Ryan P Kilby
92a4a5d423
Fix docs 404 (#7197)
* Use 'site_url' instead of hardcoding DRF homepage

* Use 'url' template filter instead of 'base_url'

This fixes static file loading for the 404 page.

* Only insert funding <hr> if toc is present

* Link quickstart to valid API guide page

* Fix 404 search modal link

* Use 'base_url' instead of 'site_url' on 404 page
2020-02-20 10:23:06 +00:00
Yoo In Keun
4faa674196
Fixed docs typo. (#7188) 2020-02-19 20:16:42 +01:00
Dalei
39dd34f161
Update docs for OpenAPI (#6814) (#7191) 2020-02-19 11:56:12 +00:00
Kevin Kennell
d7b218f5eb
decode base64 credentials as utf8; adjust tests (#7193)
* decode base64 credentials as utf8; adjust tests

* basicauth: add dedicated test for utf8 credentials

* basicauth: add fallback to latin-1 encoding if utf-8 fails
2020-02-17 16:10:52 +00:00
Thorsten
f81ca78642
Add file option to generateschema (#7130) 2020-02-12 20:35:54 +01:00
Thorsten
4137ef41ef
Disable yaml aliases for schema generation. (#7131) 2020-02-03 14:41:47 +01:00
Kentalot
79d37bce4c
OpenAPI: Include type key in schema object properties dict. (#7169) 2020-01-30 12:14:17 +01:00
Dhaval Mehta
bc4d52558b
Schemas: Add mapping of type for ChoiceField. (#7161) 2020-01-29 19:15:56 +01:00
Stella
160f912a60
Schemas: Handle default=false for boolean fields (#7165) 2020-01-29 10:20:51 +01:00
William S. Vincent
d21b8eb084 update Django for APIs book to 3.0 edition (#7164) 2020-01-28 14:05:32 +00:00
Fábio Domingues
d22daf4e05 OpenAPI: Use _get_serializer() in _get_operation_id() (#7160) 2020-01-26 19:13:08 +01:00
Fábio Domingues
e4a26ad58a Corrected _get_serializer() argument order. (#7156) 2020-01-23 15:53:47 +01:00
Kevin Brown
f8f8b3a1f1 Adjust test for ListField(IntegerField)
The `maximum` is valid here within the schema but it was not
previously being included because we were not copying over the
entire schema for the generated `IntegerField` previously.
2020-01-21 20:45:07 +01:00
Kevin Brown
98c8af5291 ListField mapping should map all options for the child
Previously it was only mapping the `type` and `format`, even though
for some field types (like a `MultipleChoiceField`) we map more
than just these. And for some fields (like a `ChoiceField`) we do
not map the `type` at all.
2020-01-21 20:45:07 +01:00
Kevin Brown
b1048984a7 Add failing test for ListField schema generation
The `ListField` was generating a schema that contained `type=None`
when a `ChoiceField` was the child, since we are not currently able
to introspect the type of a `ChoiceField`.
2020-01-21 20:45:07 +01:00
Carlton Gibson
496947be3a Inline unnecessary method in OpenAPI schema generator. 2020-01-21 20:05:13 +01:00
Carlton Gibson
3b88312c33 Call get_schema(), rather than sub-method in schema tests. 2020-01-21 20:05:13 +01:00
Carlton Gibson
d0b9577605 Return valid OpenAPI schema even when empty. 2020-01-21 20:05:13 +01:00
David Runge
7bd730124c MANIFEST.in: Adding tests to sdist tarball. (#7145) 2020-01-15 20:18:25 +00:00
Jonathan Longe
62193e0378 Add permissions to quickstart tutorial (#7113) 2020-01-15 11:58:31 -08:00
Ryan P Kilby
5f3f2ef106 Add note that APISettings is an internal class (#7144) 2020-01-15 10:52:29 +00:00
Danny
442a206502 Fix full-text search docs (#7133) 2020-01-10 22:38:29 -08:00
Sebastian Pipping
373e521f36 Make CharField prohibit surrogate characters (#7026) (#7067)
* CharField: Detect and prohibit surrogate characters

* CharField: Cover handling of surrogate characters
2020-01-06 14:12:21 +00:00
Alex ⚡
165da5be0c Documentation: make codeblocks easier to read. (#6896) 2020-01-03 14:42:29 +00:00
phankiewicz
a9e55334e7 Add X-CSRFToken HTTP header in swagger-ui example (#6968) 2020-01-03 13:59:32 +00:00
Frederico Lima
25ac7ba450 Add third party lib drf-viewset-profiler (#6993) 2020-01-03 13:53:09 +00:00
Tom Christie
430a567258
Update openapi.py 2020-01-03 13:50:26 +00:00
Noam
ced37a56cb Avoid outputting callable defaults to schema. (#7105) 2020-01-03 13:49:46 +00:00
Bart
07376f128c Grammar fix (#6933) 2020-01-03 13:36:43 +00:00
Jihoon Park
f3ed69374d Add missing punctuation marks and URL name (#7108)
- trailing commas (as both Python and JavaScript allow them)
- trailing semicolons in JavaScript
- URL name `api-docs`
2020-01-03 13:28:35 +00:00
Ran Benita
62ae241894 Remove outdated comment in SerializerMethodField (#7110)
Since 91ea138406.
2020-01-02 14:52:05 +00:00
Ran Benita
d985c7cbb9 Remove a few no longer needed compat checks and references (#7092)
* serializers: removes no longer needed compat checks

UUIDField and DurationField are both supported in all supported Django
versions.

IPAddressField was removed in Django 1.9, which is no longer supported.

* serializers: move related code closer together

This way it's easier to see all of the mappings in one place.

* serializers,docs: remove some DRF 2.x references

The last release of DRF 2.x was 5 years ago, it seems fine to remove
these references now.
2019-12-16 18:59:25 +00:00
Tom Christie
de497a9bf1
Version 3.11 (#7083)
* Version 3.11

* Added notes on OpenAPI changes for 3.11.

* Minor docs tweaking

* Update package version and supported versions

* Use a lazy import for django.test.client.encode_mutlipart. Closes #7078
2019-12-12 14:31:40 +00:00
Jordan Ephron
3c1428ff79 Fix NotImplementedError for Field.to_internal_value and Field.to_representation (#6996) 2019-12-12 14:09:34 +00:00
Ryan P Kilby
b8c369c4cf Fix serializer multiple inheritance bug (#6980)
* Expand declared filtering tests

- Test declared filter ordering
- Test multiple inheritance

* Fix serializer multiple inheritance bug

* Improve field order test to check for field types
2019-12-12 14:03:55 +00:00
Adam Johnson
7c5459626d Declare Django versions in install_requires (#7063)
* Declare Django versions in install_requires

Pip's dependency resolver (used in pipenv, pip-compile, poetry, etc.) can use this to infer whether there's a verison collision in what it's being asked to install or not.

* No max
2019-12-12 13:03:34 +00:00
Ryan P Kilby
236667b717 Fix UniqueTogetherValidator with field sources (#7086)
* Add failing tests for unique_together+source

* Fix UniqueTogetherValidator source handling

* Fix read-only+default+source handling

* Update test to use functional serializer

* Test UniqueTogetherValidator error+source
2019-12-12 13:02:30 +00:00
Aarni Koskela
f744da74d2 Improve the docstring on @action (#6951) 2019-12-11 15:08:54 -08:00
Ryan P Kilby
de9f1d56c4 Followup to set_context removal (#7076)
* Raise framework-specific deprecation warnings

- Use `RemovedInDRF313Warning` instead of DeprecationWarning
- Update to follow deprecation policy

* Pass serializer instead of model to validator

The `UniqueTogetherValidator` may need to access attributes on the
serializer instead of just the model instance. For example, this is
useful for handling field sources.

* Fix framework deprecation warning in test

* Remove outdated validator attribute
2019-12-11 08:44:08 +00:00
Roy Segall
ebcd93163a Adding I'm a teapot error code (#7081) 2019-12-10 09:18:35 +00:00
Ryan P Kilby
90eaf51839
Update framework deprecation warnings (#7075)
- Bump version numbers for deprecation warnings
- Drop deprecated features
2019-12-04 16:18:38 -08:00
Ryan P Kilby
95d4843abe
Fix Django 3.0 deprecations (#7074) 2019-12-04 14:14:43 -08:00
Hasan Ramezani
4d9f9eb192 Changed default widget for TextField with choices to select (#6892) 2019-12-04 12:24:49 -08:00
Kye Russell
dff9759555 Removed Eric S. Raymond quote from the release notes (#7073) 2019-12-04 09:29:01 +00:00
Tom Christie
070cff5a03
Drop set_context() (#7062)
* Do not persist the context in validators

Fixes encode/django-rest-framework#5760

* Drop set_context() in favour of 'requires_context = True'
2019-12-03 11:16:27 +00:00
Asif Saif Uddin
9325c3f654 dj 3.0 (#7070) 2019-12-03 11:13:44 +00:00
Oskar Persson
8001087e9e Fix typo in unsupported version error message (#7060) 2019-11-21 14:59:50 +00:00
Tom Christie
7fbbfe2c60
Django 3 compat (#7058)
* First pass at Django 3.0 compat

* Drop Guardian for 1.11 tests, since we're installing an incompatible version

* Fix ROOT_URLCONF override in test case

* Fix typo

Co-Authored-By: Rémy HUBSCHER <hubscher.remy@gmail.com>

* Linting
2019-11-21 11:55:53 +00:00
Tom Christie
fe840a34ff
Escape hyperlink URLs on lookup (#7059)
* Escape hyperlink URLs on lookup

* Rename duplicate test
2019-11-21 11:38:40 +00:00
Xavier Ordoquy
39876e6607
Merge pull request #7061 from b0uh/doc-remove-old-ref
[Doc] Remove the old reference to `JSONResponse`
2019-11-20 14:29:04 +01:00
Thomas Loiret
adaf97a739 Remove the old reference to JSONResponse 2019-11-20 14:09:49 +01:00
Hendrik
a73d3c309f Elaborated on nested relationships (#7051) 2019-11-18 12:35:36 +00:00
CloudCode Hungary
6196e9c8cd add djangorestframework-features to third-party (#7052) 2019-11-18 12:31:32 +00:00
Chris Guo
cad1b08260 Fix override func style and regular usage (#7050)
* style: add space and rm redundant parentheses

* refactor: use super to replace inherit class

* Prefer explicit tuple syntax
2019-11-18 12:30:36 +00:00
James
323e1cddda Cleanup "Documenting your API" 3rd party recommendations (#7057) 2019-11-15 18:39:47 -08:00
Maxime Jacques
8988afa082 Update bootstrap to 3.4.1 (#6923) 2019-11-11 16:41:10 -05:00
brantmorton
0d6589cf45 Updated url() with re_path() in Versioning docs. (#7043) 2019-11-07 13:20:56 +01:00
Yann Savary
0d3d548aa5 OpenAPI: Fixed generation when title or version not provided. (#6912) 2019-11-06 21:54:12 +01:00
Yann Savary
7c3477dcda OpenAPI: Ported docstring operation description from CoreAPI inspector. (#6898) 2019-11-06 21:52:02 +01:00
Kentalot
becb962160 OpenAPI: Use int64 format for large integers. (#7018) 2019-11-06 21:46:19 +01:00
Dima Knivets
8b06ce72d7 OpenAPI: Map renderers/parsers for request/response media-types. (#6865) 2019-11-06 21:44:51 +01:00
Aaron Yong
14d740d088 Update DEFAULT_SCHEMA_CLASSES default value in Settings docs (#7014)
The default value was changed to point to the OpenAPI AutoSchema class.  The docs were leading users to believe that rest_framework.schemas.AutoSchema was the default.  As of this commit, the root AutoSchema is in fact imported from the coreapi module.
2019-11-06 21:37:13 +01:00
Erwan Rouchet
5e8fe6edf0 Fix link to Django docs (#7040) 2019-11-06 09:34:28 -08:00
Tom Christie
82f2569895
Update __init__.py 2019-11-05 16:43:32 +00:00
Chris Guo
5521eacb02 Update docs imports (#7030) 2019-11-01 10:56:59 -07:00
Daniel Hnyk
ab40b80fa6 Remove unmaintained django-rest-framework-bulk from docs (#7021) 2019-10-28 03:46:44 -07:00
Erwan Rouchet
39bd6cc5cb Set the proper JSON schema type for HStoreFields in OpenAPI schemas (#6914) 2019-10-27 21:13:01 -04:00
Chris Guo
5ee970c090 Fix docs typos (#7015) 2019-10-24 11:31:12 -07:00
Jeremy Lainé
c9f06bf73f Fix a spelling error in openapi AutoSchema method (#7004)
Replace "pagninator" by "paginator".
2019-10-24 10:51:16 +02:00
Aaron Yong
4d57cd31f6 Update method override example in Schemas docs (#6887) (#7013)
get_link() was a method in the old CoreAPI-based AutoSchema implementation.  The new OpenAPI one defines get_operation() instead: the example code block was overlooked.
2019-10-24 08:54:37 +02:00
Bastien Vallet
64f567a021 Bump CI to Python 3.8 (#7008) 2019-10-22 14:39:01 -07:00
Ryan P Kilby
a8c86be660
Update linter requirements (#7010) 2019-10-22 11:18:51 -07:00
nautikos1235
65ed7be754 Fix markdown code indent in schemas (#7009) 2019-10-22 11:10:15 -07:00
Sergey
43397a81ae Fixed decimal snan deserialization (#7002)
* Added test case causes exception in DecimalField deserialization

* Fixed NaN checking which throws exception with sNaN value
2019-10-22 10:06:37 +01:00
Chris Guo
a734e58d44 Fix docs typos (#7006) 2019-10-21 15:11:12 -07:00
zach valenta
f98b6f3577 proper Github repo issue already resolved (#6999)
per the ticket anyway https://github.com/encode/django-rest-framework/issues/2162
2019-10-17 13:58:12 +01:00
Braden MacDonald
3aa1089a6a Update serializer docs to use correct param name (#6995)
Avoids a pylint warning ".to_representation: Parameters differ from overridden 'to_representation' method" if people copy these examples.
2019-10-15 15:47:05 +01:00
Guilherme Munarolo
0fd72f17ee Fixed crash deleting required schema parameter key on PATCH requests. (#6944)
Closes #6941
2019-10-10 08:50:20 +02:00
David Sanders
9850441e6f Fix docs typo (#6974) 2019-10-08 16:37:58 -07:00
Law Karingithi
0e4811e9ce Fix minor grammatical errors in docs (#6979) 2019-10-08 09:38:14 -07:00
Tom Christie
f9cc190177 Crop width on premium sponsor images 2019-10-07 14:31:16 +01:00
Tom Christie
1f3505931c
Update README.md 2019-10-07 14:22:40 +01:00
Tom Christie
f36ff9b08b
Add Retool as a new premium sponsor (#6977) 2019-10-07 14:21:58 +01:00
Francisco Couzo
37dcd55370 Fix bug in escape_curly_brackets (#6909) 2019-10-04 13:50:19 -07:00
mehrab
b4db2dfacf Fixed no-cls-argument on staticmethod __new__ (#6960) 2019-10-04 12:40:09 -07:00
Konstantinos Tselepakis
30e56f62ba Fix nested write of non-relational fields (#6916) 2019-10-03 09:33:37 -07:00
Xavier Ordoquy
0dac98d215
Merge pull request #6953 from felixxm/import-FieldDoesNotExist
Fixed import of FieldDoesNotExist exception.
2019-09-29 08:53:20 +02:00
Mariusz Felisiak
75afe48b6c Fixed import of FieldDoesNotExist exception. 2019-09-28 20:52:22 +02:00
Ted Stoychev
60f9c12900 Fixed broken link in documentation (#6937) 2019-09-27 09:47:51 -07:00
Yezy Ilomo
5b990d4092 Add django-restql to 3rd party packages in docs (#6947) 2019-09-24 00:22:25 -07:00
Oxan van Leeuwen
2664e65019 Add djangorestframework-dataclasses to 3rd party package docs (#6939) 2019-09-18 11:21:32 -07:00
napsterv
7a3b7d2001 Fixed method signature in docs (#6931) 2019-09-16 10:47:29 -07:00
Tom Christie
89ac0a1c7e
Version 3.10.3 (#6908)
* Version 3.10.3

* Version 3.10.3 release notes
2019-09-04 14:28:25 +01:00
Tom Christie
4b30b32014
Default OpenAPI version to the empty string (#6907) 2019-09-04 12:53:50 +01:00
Pramod Pujara
c0cf37e35d Update tutorial links (#6890) 2019-09-03 11:21:53 -07:00
Yann Savary
e57c1505fc Replaced 'TODO' hardcoded version info by a parameter with default '0.1.0' (#6899) 2019-09-03 16:07:30 +02:00
Peter J. Farrell
b3f032fb8f Fixed #6875 -- Made OpenAPI Schema operationId casing consistent. (#6876) 2019-09-03 16:05:43 +02:00
Dima Knivets
1cc4be47b4 Fixed min/max attributes for serializers.ListField (#6866) 2019-09-03 15:43:54 +02:00
Reupen Shah
f8c16441fa Add support for pagination in OpenAPI response schemas (#6867)
Refs #6846

This provides a way for pagination classes to add pagination properties (`count`, `next`, `results` etc.) to OpenAPI response schemas.

A new method `get_paginated_response_schema()` has been added to `BasePagination`. This method is intended to mirror `get_paginated_response()` (which takes a `list` and wraps it in a `dict`). 

Hence, `get_paginated_response_schema()` takes an unpaginated response schema (of type `array`) and wraps that with a schema object of type `object` containing the relevant properties that the pagination class adds to responses.

The default implementation of `BasePagination.get_paginated_response_schema()` simply passes the schema through unmodified, for backwards compatibility.
2019-09-03 15:25:44 +02:00
Min ho Kim
ec1b14174f Fixed typos (#6872) 2019-08-14 14:39:45 -07:00
Christopher Grebs
5a8736ae45 Handle 'None' return value of wait() properly during throttling. (#6837) 2019-08-12 11:36:05 -07:00
Dima Knivets
a142467586 Fixed incorrect OpenAPI response schema generation for a DELETE method in generic views (#6860) 2019-08-09 15:02:41 +02:00
Chris Vigelius
f7dc6b5656 OpenAPI: Added required description to responses. (#6850) 2019-08-07 22:09:27 +02:00
Chris Vigelius
0ebfbfdf81 OpenAPI: only include non-empty required property. (#6851)
Closes #6834
2019-08-07 21:40:21 +02:00
Gregory N. Schmit
335054a5d3 replace force_text with force_str 2019-08-07 21:05:24 +02:00
Reupen Shah
b45ff07294 Use an array type for list view response schemas
This is the first part of #6846.

Previously, the response schema for list views was an object representing a single item. However, list views return a list of items, and hence it should be an array.

Further work will need to be done to support how pagination classes modify list responses.

There should be no change for views not determined to be list views.
2019-08-07 20:40:22 +02:00
Reupen Shah
a3f244d85e Move AutoSchema serializer instantiation to common method 2019-08-07 20:40:22 +02:00
zeroohub
7e1c4be7ce Avoided double call for remote url in FileField.to_representation. (#6841) 2019-08-06 12:31:46 +02:00
Greg Schmit
0cc09f0c0d Add drf-action-sreializer to third party packages (#6845) 2019-07-30 12:37:49 -07:00
Ryan P Kilby
bcf196d0ac
Remove outdated note about read_only+default (#6847) 2019-07-29 15:10:57 -07:00
Max Wittig
ed7f3c55f7
docs(tutorial): add missing permission import in viewsets 2019-07-29 14:20:11 +02:00
Min ho Kim
0e1c5d3132 Fix typos (#6835) 2019-07-25 10:04:01 -07:00
Chris Vigelius
ca727872c8 OpenAPI schemas: Ensure lazy field descriptions are converted to str(). (#6832) 2019-07-25 15:30:20 +02:00
Daniel Alvarez
659375ffe6 Fixed a typo on the ExampleValidatedAPIView
Cherry-picked from #6819
2019-07-24 11:13:30 +02:00
Carlton Gibson
1b66d1b819 Move serializer field introspection tests to correct test case.
From SchemaGenerator tests to Operation Introspection.
2019-07-24 11:13:30 +02:00
Carlton Gibson
de26af4295 Move determine_path_prefix() logic into CoreAPI module. 2019-07-24 11:13:30 +02:00
Carlton Gibson
e309a4f0b8 Fix OpenAPI path generation with common prefixes.
Closes #6675. Closes #6823.
2019-07-24 11:13:30 +02:00
Carlton Gibson
30a21a98dc Add test for OpenAPI SchemaGenerator url argument. 2019-07-24 11:13:30 +02:00
Carlton Gibson
178a2dc786 Correct OpenAPI test for common prefixes. 2019-07-24 11:13:30 +02:00
Daniel Alvarez
2138f558ce Added mapping of ListField.child type for OpenAPI Schemas. 2019-07-24 11:09:57 +02:00
Muammar ibn Faisal
f7c3220fdb Ability to specify urlconf in include_docs_urls added (#6824)
There is a problem in the current implementation that if one exports docs via `include_docs_urls` he will be using `ROOT_URLCONF` (https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas/generators.py#L73), which is a big problem, if one is working with subdomains and he has sets of disjoint URLs.
This simple fix allows to pass through forgotten `urlconf` parameter.
2019-07-23 12:06:03 +01:00
Bary Levi
ea2ebf61cb fix quote was outside of inline code (#6830) 2019-07-22 13:02:17 +01:00
linchiwei123
da1c6d4129 Fix indent (#6825) 2019-07-18 23:09:04 -07:00
Tom Christie
044252af1c
Version 3.10.1 (#6817)
* Ensure that requiring 'uritemplate' does not also require 'coreapi'

* Don't include autocomplete fields on TokenAuth admin

* Version 3.10.1
2019-07-17 14:17:45 +01:00
Carlton Gibson
9114034856
Update Django Filter dependency for OpenAPI schema support. (#6812) 2019-07-17 06:29:28 +02:00
Carlton Gibson
4991e4dbbe
Merge pull request #6813 from dalvtor/fix-schemas-docs
Fixes import in the schemas documentation
2019-07-16 23:03:13 +02:00
Daniel Alvarez
316526d877 Fixes import in the schemas documentation 2019-07-16 21:32:19 +01:00
Ryan P Kilby
0cb2523927
Update docs search plugin (#6810) 2019-07-16 13:00:45 -07:00
Tom Christie
a4c2d4f0d5 Fix side nav in project docs 2019-07-16 09:31:29 +01:00
Tom Christie
908516f2bd Fix pagination docs meta information 2019-07-15 20:14:59 +01:00
Ryan P Kilby
0cb6b63bde Use 'url' template filter in docs (#6805) 2019-07-15 20:11:49 +01:00
Tom Christie
6499378fc3 3.10 release notes tweaks 2019-07-15 12:38:28 +01:00
Tom Christie
9eaf49dab9
Version 3.10 (#6802)
* 3.10 release notes

* Version number -> 3.10

* Update translations

* Update 3.10 release docs

* Update release notes

* Delete symlink
2019-07-15 12:31:09 +01:00
Ryan P Kilby
b26db12813 Update default settings to use lists instead of tuples (#6799)
* Update default settings from tuples to lists

* Add missing trailing commas

* Use single quotes for consistency

* Update settings lists in docs
2019-07-15 11:54:46 +01:00
Luke Plant
f0dbf0a264 Update docs to use lists instead of tuples (#6797) 2019-07-12 18:15:36 -07:00
Aarni Koskela
5c922fb39d JSONEncoder: ensure empty listlikes remain lists, not dicts (#6794) 2019-07-09 11:41:05 +01:00
Carlton Gibson
7915485c0d Update docs for OpenAPI. (#6668)
* Update schema docs for OpenAPI

* Begin v3.10 Release Announcement.

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

Co-Authored-By: Martin Pajuste <pajusmar@users.noreply.github.com>

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

Co-Authored-By: Martin Pajuste <pajusmar@users.noreply.github.com>

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

Co-Authored-By: Martin Pajuste <pajusmar@users.noreply.github.com>

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

Co-Authored-By: Martin Pajuste <pajusmar@users.noreply.github.com>
2019-07-08 13:09:05 +01:00
Tom Quinonero
7762aaa90f Docs sidebar improvements (#5638) (#6589)
* add sans-serif fallback for Verdana in docs sidebar

Co-Authored-By: Joachim Jablon <ewjoachim@gmail.com>

* improve display for docs sidebar (#5638)

Co-Authored-By: Joachim Jablon <ewjoachim@gmail.com>
2019-07-08 13:05:13 +01:00
Tom Christie
1619d282f7
Update rollbar sponsor URL (#6791) 2019-07-08 12:27:21 +01:00
Tom Christie
cc88c8a6f3
Update serializers.md 2019-07-08 11:12:30 +01:00
Ryan P Kilby
bd6a1b3b6c Fix dotted-source field checking on serializer write (#6786)
* Add tests for raise_errors_on_nested_writes

* Fix dotted-source field checking on serializer write

The code was previously checking the validated data for the field's
attribute name, however, the data contain the first source attr.
2019-07-08 11:10:18 +01:00
linchiwei123
372f4fde20 Update pagination.md (#6787)
it seems like that
2019-07-05 22:30:01 -07:00
cyap
eebc579e9b Fix typo (#6785) 2019-07-05 15:46:51 +01:00
linchiwei123
373195996e Update fields.md (#6784)
Example ==> Example
2019-07-05 14:24:52 +01:00
linchiwei123
8fbf8c3fa3 Update serializers.md (#6783) 2019-07-05 09:11:20 +01:00
Ryan P Kilby
976739206c Don't render extra actions when unauthenticated (#6775) 2019-07-04 14:54:16 +01:00
Alex Ayon
a3eeeb20e7 Update 1-serialization.md (#6781)
Assigning a sorted list to STYLE_CHOICES by using a list comprehension.
2019-07-04 13:41:15 +01:00
johnthagen
989aeca205 Add link to django-filter on first reference (#6777) 2019-07-03 10:43:30 -07:00
Étienne Noss
f5470ab9e2 docs: update http method override middleware example (#6776) 2019-07-03 10:23:35 +01:00
Florian Bruhin
43d4736802 Fix rel=prev/next in docs (#6650) 2019-07-02 19:04:49 -07:00
Michael
1256d5363d Add project_urls to setup.py (#6625) 2019-07-02 18:56:26 -07:00
Ryan P Kilby
e4e75f1c7c
Strip null characters from search param (#6774) 2019-07-02 11:33:48 -07:00
Ryan P Kilby
280014fe37 Update docs for pagination settings (#6772) 2019-07-02 12:09:45 +01:00
Ryan P Kilby
41d5338ba6 Translate Throttled exception messages (#6771) 2019-07-02 11:21:40 +01:00
Ryan P Kilby
da06240257
Fix ModelField max_length argument (#6773) 2019-07-01 19:14:45 -07:00
Karambir Singh Nain
a7778897ad Fix ArrayField kwargs mapping for blank/allow_empty (#6758)
Postgres ArrayField blank=True should allow empty Lists in Serializer
2019-07-01 17:34:34 -07:00
Reupen Shah
3242adf058 Enforce allow_empty=False during partial validation of parent serializer (#6512)
Refs #6509

This enforces allow_empty=True when a ListSerializer is a child of another serializer and partial validation is being performed on the parent serializer.

This is because partial validation should allow fields to be omitted, but should not cause values that are invalid without partial validation to become valid.

This effectively reverts #4222. None of the tests added in that PR fail if the associated change is removed, so I‘m not sure what that PR was trying to fix.
2019-07-01 13:30:16 +01:00
Michael
79b2350b54 [fields] Format error message only if params exist (#6624)
This prevents exceptions when the error message contains `%`, but is
not intended for formatting.  Django itself does the same:
6866c91b63/django/core/exceptions.py (L168-L169)

Fixes encode/django-rest-framework#6622
2019-07-01 13:28:16 +01:00
Ryan P Kilby
7179ea9984 Raise exception when field source is a built-in (#6766) 2019-07-01 13:25:47 +01:00
Ryan P Kilby
91ea138406 Allow redundant SerializerMethodField method names (#6767) 2019-07-01 13:22:03 +01:00
Greg Curtis
42fd179d4e upgrade jQuery to latest version (#6728) 2019-07-01 13:16:21 +01:00
Ryan P Kilby
e36ba9c46e
Add twine check to publish process (#6770) 2019-07-01 00:19:12 -07:00
Ryan P Kilby
c04d6eac43
Update pytest (#6768)
* Update pytest to 5.x

* Ensure test de-monkeypatches auth on failure

* Fix pytest.raises compat issue
2019-06-30 19:08:52 -07:00
Ryan P Kilby
82c2b5c3e7
Update mkdocs (#6769) 2019-06-30 19:04:36 -07:00
Jon Besga
9a429a1c2e Fix custom authentication example (#6640) 2019-06-30 17:55:54 -07:00
Ryan P Kilby
df1d146ee7
Remove old documentation (#6765) 2019-06-28 16:03:00 -07:00
Florimond Manca
af2a2e6010 Update description and link to djangorestframework-api-key (#6764) 2019-06-28 15:40:31 -07:00
Jan Pieter Waagmeester
cfd3ea0996 TokenAdmin: add 'user' to autocomplete_fields (#6762)
TokenAdmin is unusable with a big number of user records (in this case ~150k). Django 2.0 added the [ModelAdmin.autocomplete_fields](https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields) option to use select2 to provide a better user experience.

If support for django 1.11 is dropped, this change would make the `TokenAdmin` usable again.
2019-06-28 13:44:15 +01:00
bonohubby
f76480a127 Fix typo in docs (#6757) 2019-06-25 10:08:46 +01:00
Tanner Rollefson
a1921b1adb Add djangorestframework-mvt to third party packages (#6756) 2019-06-24 15:44:22 -07:00
Robert Singer
80e89c75c7 Add DRF Access Policy to 3rd party packages (#6723) 2019-06-23 13:18:08 -07:00
Kryštof Řeháček
6a95451d72 Fixes #6751 - ModelSerializer fields does not get updated correctly when signals are connected to some fields (#6752)
* fixes #6751

* reverted condition

* save instance before setting m2m fields

* added comment why m2m fields are saved after instance

* removed blank line

* added test for the issue 6751
2019-06-22 09:14:15 +01:00
Min ho Kim
72de94a05d Fix typos in docs (#6747) 2019-06-18 12:58:01 -07:00
Xavier Ordoquy
809a6acd36 Add --urlconf to the generateschema command (#6696) 2019-06-09 15:23:52 +02:00
Alan Crosswell
4d228257ac Retain declared path ordering in OpenAPI YAML output. (#6680)
* Add pyyaml.dump(..., sort_keys=False) to not sort openapi keys alphabetically
* Retain ordering of paths as provided in urlconf in OpenAPI schemas.
2019-06-09 14:58:02 +02:00
Alan Crosswell
819c46ea80 Add --generator_class CLI option to generateschema (#6735)
* add --generator_class CLI option to generateschema
* Add test for generateschema —generator_class flag.
2019-06-09 14:43:54 +02:00
Alan Crosswell
2d65f82dd7 Generate OpenAPI schema field types from validators. (#6674) 2019-06-09 14:42:56 +02:00
Alan Crosswell
a63860fc8b Corrected openapi.SchemaGenerator path prefixes. (#6724) 2019-06-09 14:29:55 +02:00
Hasan Ramezani
60bcc93202 Remove duplicate test in tests/test_utils.py (#6736) 2019-06-07 14:45:34 +01:00
Ryan P Kilby
9ac9c1b2ea
Update status code docs (#6732) 2019-06-05 17:51:50 -07:00
Tom Christie
6a8575b042
Sponsor update (#6727)
* Sponsor updates

* Sponsor Update
2019-06-04 12:03:31 +01:00
Tom Christie
3135ae86c9
Create FUNDING.yml 2019-06-04 09:00:11 +01:00
Ryan P Kilby
3e210ae48d
Update markdown preprocessor registration (#6722) 2019-05-31 14:11:58 -07:00
Adam
6aac9d2be1 Remove references to django-crispy-forms (#6600) 2019-05-30 19:47:30 -07:00
Jon Dufresne
b37aa284eb Remove unnecessary bytes() calls (#6626) 2019-05-30 15:05:27 -07:00
Florian Wendelborn
6bd25c09a6 Add Multiple HTTP Statuses (#6706) 2019-05-30 14:32:46 -07:00
Timothy Allen
8430f3e5b6 Fix typo in github.com URL. (#6720) 2019-05-30 12:23:37 -07:00
Ran Benita
c2293e9f25 Improve performance of lazy validation message formatting (#6709) 2019-05-29 11:32:03 -07:00
Rodolfo Carvalho
62ed1f8270 Use yaml.safe_load instead of load (#6719)
Use of PyYAML's yaml.load function without specifying the Loader
parameter has been deprecated, see https://msg.pyyaml.org/load.

Earlier versions of PyYAML already had the alternative safe_load
function, which limits the loader to a subset of YAML constructs, that
is enough for what we need here.

Fixes #6677
2019-05-29 09:51:24 -07:00
Monte Hellawell
063f0de949 Move security information to the GitHub security tab (#6716)
* Create SECURITY.md

* Update security policy links in README.md
2019-05-29 09:57:07 +01:00
Dani Hodovic
10a0b42b74 Add more DRF job sites (#6691) 2019-05-24 12:50:15 +01:00
Raffaele Salmaso
514033815d Allow JSONField encoder customization. (#6713) 2019-05-24 12:47:35 +01:00
Mathieu Pillard
afb678433b Always call all throttling classes on the view when checking throttles (#6711) 2019-05-23 14:42:29 +01:00
Ryan P Kilby
19ca86d8d6
Fix lazy translation of ListField errors (#6708)
* Test init for fields w/ lazy translations
* Fix lazy translations for ListField
2019-05-22 19:41:53 -07:00
Florian Wendelborn
0d0e7c3ae0 Add HTTP 308 Permanent Redirect (#6693) 2019-05-22 11:25:12 -07:00
Ryan P Kilby
db37512a6e
Remove 3.10 deprecations (#6687)
* Remove DjangoObjectPermissionsFilter
* Remove detail_route/list_route
* Bump deprecation warning versions
2019-05-21 10:36:55 -07:00
Ran Benita
ccd9b71c0a Don't cache _readable_fields and _writable_fields (#6689)
It might be useful for a serializer with many many fields which uses
read_only and write_only on a large percentage of the fields. But the
memory usage and statefulness it adds are not worth it for the common
case.
2019-05-21 15:45:31 +01:00
Ryan P Kilby
1b8141a4aa
Fix nullable source='*' fields (#6659) 2019-05-20 14:58:02 -07:00
Rick van Hattem
2c92548963 Made the loading of the fund sidebar async (#6686) 2019-05-20 16:09:23 +01:00
Ran Benita
7232586c7c Simplify Serializer.fields with @cached_property (#6662) 2019-05-20 14:49:47 +01:00
Joachim Jablon
43a9cc1b7a Fix CursorPagination when objects get deleted between calls (#6504) (#6593)
* Added regression tests (#6504)

Co-Authored-By: Tom Quinonero <tq@3yourmind.com>

* Fix CursorPagination when objects get deleted between calls (#6504)

Co-Authored-By: Tom Quinonero <tq@3yourmind.com>
2019-05-20 14:41:31 +01:00
Asif Saif Uddin
ac0f0a1774 Updated optional requirements (#6673) 2019-05-14 10:14:11 -07:00
Ryan P Kilby
c3a13916d2
Update release notes (#6671)
* Add 3.9.4 release notes to master
* Add top-level symlink to release notes
2019-05-14 10:13:14 -07:00
Carlton Gibson
37f210a455
Added OpenAPI Schema Generation. (#6532)
Co-authored-by: Lucidiot <lucidiot@protonmail.com>
Co-authored-by: dongfangtianyu <dongfangtianyu@qq.com>
2019-05-13 16:07:03 +02:00
Asif Saif Uddin
a91e6a0e69 Updated test packges version (#6665) 2019-05-13 09:21:27 +01:00
Ran Benita
9811a29a5a Pass through memo in __deepcopy__ as required by the docs (#6660)
This is needed to avoid problems with recursive loops. See
https://docs.python.org/3.7/library/copy.html
toward the end.
2019-05-09 09:20:32 +01:00
gaetano-guerriero
a7c577cb31 Dict field allow empty (#6583)
* dict field: support allow_empty option

* document ListField allow_empty option

* document HStoreField allow_empty parameter
2019-05-09 09:18:20 +01:00
Tim Gates
564faddb0f Make Markdown 2.6 the minimum compatible version (#6576) 2019-05-08 19:34:38 -07:00
Xavier Ordoquy
2e7ab9d6c6
Merge pull request #6654 from jorrit-wehelp/patch-1
Fix test with STRICT_JSON setting
2019-05-08 18:14:27 +02:00
Jorrit
3a21b390ff
Fix test with STRICT_JSON setting
Test is not overriding the intended setting, should be nested inside settings.REST_FRAMEWORK
2019-05-08 16:48:45 +02:00
Andreu Vallbona Plazas
be5a9f78f3 Added note on serializing extra fields from Through Model (#6652)
* adding small clarification on ManyToManyFields with a Through Model

As pointed here: https://github.com/encode/django-rest-framework/pull/6585#issuecomment-490145334 I suggest to add the small clarification to work with **ManyToManyFields with a Through Model**.

* Remove blank line.
2019-05-07 20:01:24 +02:00
Serkan Hosca
680ed8aa8b Add django-rest-witchcraft to third party packages (#6587) 2019-05-06 16:19:51 -07:00
Asif Saif Uddin
50a24d6d7f Drop Python 3.4 support (#6620) 2019-05-06 11:35:58 -07:00
Aart Goossens
0f819d844d Remove recommendation for DRF Docs (#6580)
Since DRF Docs is not compatible with the latest version of DRF (or Django?; related issue: https://github.com/manosim/django-rest-framework-docs/issues/180) and the latest release is almost 3 years ago I suggest to remove the recommendation for this package.
2019-05-03 15:26:06 -07:00
Jimmy Merrild Krag
14fad0d690 Fix capitalization, markdown syntax link in docs (#6621)
The `Pygments` and `Markdown` python packages have first letter capital.
Fixed link to markdown syntax to go directly to the syntax page.
2019-05-02 18:17:33 -07:00
Jon Dufresne
1e519486e1 Fixup isort command/config (#6639) 2019-05-01 17:42:10 -07:00
Afnarel
67d2eabd6c Fix username in template for custom user models (#6612) 2019-05-01 17:23:23 -07:00
Jon Dufresne
f669395dd8 Fix BytesWarning in test_schemas.py (#6638) 2019-05-01 16:47:01 -07:00
Jon Dufresne
e16273a658 Simplify import_from_string() with Django's import_string() (#6617) 2019-05-01 15:32:28 -07:00
vu3jej
1c976f2ac8 Fix typo in docs (#6628) 2019-05-01 15:24:38 -07:00
Jon Dufresne
059947028b Update docs on django-oauth-toolkit (#6618)
Since django-oauth-toolkit 1.2.0 (2018-06-03), the package requires
Python 3.4+.

https://github.com/jazzband/django-oauth-toolkit/blob/master/CHANGELOG.md#120-2018-06-03
2019-05-01 07:52:26 +02:00
Jon Dufresne
5e1619bc9e Remove unnecessary assignments immediately before a return statement (#6619)
Cleans up the pattern:

    ...
    myvar = <expression>
    return myvar

To:

    ...
    return <expression>
2019-05-01 07:51:54 +02:00
Jon Dufresne
565794bedc Replace virtualenv references with venv in the docs (#6636)
On Python 3, creating virtual environments is available through the
stdlib module venv.

https://docs.python.org/3/library/venv.html
2019-05-01 07:51:02 +02:00
Jon Dufresne
8687f6135f Remove references to Python 2 from the docs (#6635) 2019-05-01 07:50:28 +02:00
Jon Dufresne
3f19e66d9f Replace all usage ugettext functions with the non-u versions (#6634)
On Python 3, the ugettext functions are a simple aliases of their non-u
counterparts (the 'u' represents Python 2 unicode type). Starting with
Django 3.0, the u versions will be deprecated.

https://docs.djangoproject.com/en/dev/releases/3.0/#id2

> django.utils.translation.ugettext(), ugettext_lazy(), ugettext_noop(),
> ungettext(), and ungettext_lazy() are deprecated in favor of the
> functions that they’re aliases for:
> django.utils.translation.gettext(), gettext_lazy(), gettext_noop(),
> ngettext(), and ngettext_lazy().
2019-05-01 07:49:54 +02:00
Jon Dufresne
513a49d63b Drop default 'utf-8' to .encode()/.decode() (#6633)
A Python 3 cleanup that allows for less noise in the code.

https://docs.python.org/3/library/stdtypes.html#bytes.decode
https://docs.python.org/3/library/stdtypes.html#str.encode
2019-05-01 07:49:16 +02:00
Jon Dufresne
734ca7ca8c Remove unneeded repo() test (#6632) 2019-05-01 07:46:30 +02:00
Jon Dufresne
b4e80ac721 Remove unnecessary coerce to str() in test_decorators.py (#6637)
Was added only for Python 2 compatibility.
2019-05-01 07:45:16 +02:00
Jon Dufresne
ff86f09f74 Remove unnecessary compatibility shims from rest_framework/compat.py (#6631)
For Python 3, collections.abc.Mapping and collections.abc.MutableMapping
are always available from the stdlib.
2019-05-01 07:44:33 +02:00
Carlton Gibson
0407a0df8a
Dropped Python 2 compatibility. (#6615)
Thanks to Jon Dufresne (@jdufresne) for review.

Co-authored-by: Asif Saif Uddin <auvipy@gmail.com>
Co-authored-by: Rizwan Mansuri <Rizwan@webbyfox.com>
2019-04-30 17:53:44 +02:00
Xavier Ordoquy
5c992baf32
Merge pull request #6627 from vu3jej/docs
Correct misspelled class name in validators docs
2019-04-30 14:55:27 +02:00
Jithesh Eriyakkadan Janardhanan
908236a576 Correct misspelled class name 2019-04-30 18:01:17 +05:30
Jon Dufresne
1a0a8dde00 Correct misspelled module 'typing' (#6616)
https://docs.python.org/3/library/typing.html
2019-04-30 09:44:01 +01:00
Carlton Gibson
7f16ed7727 Correct version number in release notes. 2019-04-29 16:35:17 +02:00
Carlton Gibson
83d09c7bc5
Update version and release notes for v3.9.3. 2019-04-29 16:30:44 +02:00
Carlton Gibson
bf9859de51
Adjust django-guardian check for PY2 compatible version. (#6613) 2019-04-29 16:08:39 +02:00
Xavier Ordoquy
59a5a5a868
Merge pull request #6611 from dsanders11/patch-1
Fix typo in docs
2019-04-27 22:04:07 +02:00
David Sanders
95e28b2252
Fix typo in docs 2019-04-27 12:07:49 -07:00
Dmitry Alimov
1ac0f63aa9 Fix private attributes ignore in documentation (#6601) 2019-04-21 17:27:13 +01:00
Xavier Ordoquy
db65282163
Merge pull request #6588 from rawteech/master
Add some words about `extra_kwargs` and explicitly defined fields.
2019-04-15 02:31:07 +02:00
Billy Rotich
f8c4e5079e Minor documentation fixes (#6581) 2019-04-13 15:02:19 +02:00
Asif Saif Uddin
29cbe574a3 Fix DeprecationWarning in tests (#6551) 2019-04-05 14:27:07 -07:00
jozo
cceb416098 Link DRF Condition (cache headers) third party package. (#6557) 2019-04-04 11:31:08 +02:00
Carlton Gibson
b1122a441a
Update tox to use Django 2.2 final. (#6556) 2019-04-01 16:30:26 +02:00
Matt Hegarty
f34a0a4e6a Minor documentation fixes (#6543) 2019-03-28 23:32:25 -07:00
Asif Saif Uddin
13b9b0fb98 Upgraded to Django 2.2rc1 on Tox (#6544) 2019-03-28 21:19:06 +01:00
Jabi
ac19c69539 Corrected typo in permissions docs. (#6540) 2019-03-28 11:45:13 +01:00
Turfa Auliarachman
d784e42207 Fix basename deprecation warnings in tests (#6529) 2019-03-25 10:42:27 -07:00
Patrickcai
b25d245b89 Merge multiple isinstance() calls to one (#6513)
* Merge multiple isinstance() calls to one

See https://docs.python.org/3/library/functions.html#isinstance

* Fix `)` mismatch

Fix `)` mismatch
2019-03-22 12:29:45 +00:00
Ryan Siemens
d2d1888217 Document DateTimeField default_timezone argument (#6469) 2019-03-12 21:15:12 -07:00
Matt Hegarty
6f24c21cfb Fixed typo: /Janurary/January/ (#6506) 2019-03-12 12:46:02 +01:00
Tom Christie
9bfb58746e
Update README.md 2019-03-07 11:02:43 +00:00
Tom Christie
bcdfcf7e49
Sponsor updates (#6495) 2019-03-07 11:00:50 +00:00
Kevin Brown
86c72bb226 Fix schema generation of ManyRelatedField to detect the child type (#6489)
* Introspect ManyRelatedField data type recursively

For all `ManyRelatedField` objects, we were assuming that the inner type was always a `String`. While this may be true for the default output, a `ManyRelatedField` is a wrapper for a lot of other classes which includes more than just strings. This should allow us to document lists of things other than strings.

* Added test for schemas for many-to-many fields

This adds a test that makes sure we generate the schema for a many-to-many field such that it actually has the right type. For some reason we did not previously have any tests for schema generation that included them, so hopefully this will prevent any future issues from popping up.

This should serve as a regression test for the `items` field on to-many relationships, which was previously forced to a `String` even though in most cases it is a different inner type within the array.
2019-03-07 11:26:03 +01:00
Ryan P Kilby
fd32dd7ca4 Explicitly raise exc in 'raise_uncaught_exception' (#6435) 2019-03-07 09:44:20 +00:00
Asif Saif Uddin
9e1e32f678 upgraded pytest dependencies (#6492) 2019-03-07 09:22:00 +00:00
Jon Dufresne
9d06e43d05 Replace type('') with six.text_type (#6482)
As all source files import unicode_literals, type('') is always
equivalent to six.text_type (str on Python 3 and unicode on Python 2).
Removes the need to call type(), is more explicit, and will be easier to
catch places to change for when it is time to eventually drop Python 2.
2019-03-05 12:11:46 +01:00
Luoxzhg
dfc277cce6 Corrected tutorial 1 example renderer output to bytes. (#6486) 2019-03-05 11:50:13 +01:00
SrdjanCosicPrica
ac7b20cca2 Fix get_search_fields example (#6487) 2019-03-04 14:46:14 +01:00
Carlton Gibson
0ab527a3df Updated release notes for v3.9.2 2019-03-03 20:16:16 +01:00
Carlton Gibson
ac4c78967a Update version for v3.9.2 release. 2019-03-03 20:16:16 +01:00
Jon Dufresne
7eac86688a Remove executable bit from static assets (#6484)
These files are simply static assets and do not require an executable
bit. They are never intended to be executed as standalone scripts.
2019-03-03 18:39:08 +00:00
Carlton Gibson
94593b3a50
Introduce RemovedInDRF…Warning classes to simplify deprecations. (#6480)
Closes #6290.
2019-03-03 09:20:45 +01:00
Jon Dufresne
a216d02ce0 Merge multiple isinstance() calls to one (#6481)
https://docs.python.org/3/library/functions.html#isinstance

> If classinfo is a tuple of type objects (or recursively, other such
> tuples), return true if object is an instance of any of the types.
2019-03-02 20:48:03 +00:00
Carlton Gibson
31bf597081 Updated note on BooleanField required kwarg generation.
Closes #6474.
2019-03-01 12:48:12 +01:00
Ramon de Jezus
1dc81acb4d Fixed a typo in pagination docs. (#6475) 2019-02-28 15:18:58 +01:00
Andrzej Górski
317174b163 Avoided calling distinct on annotated fields in SearchFilter. (#6240)
Fixes #6094
2019-02-25 16:59:25 +01:00
Adrien Brunet
2daf6f1341 Add negation ~ operator to permissions composition (#6361) 2019-02-25 15:33:40 +01:00
Xtreak
739b0a272a Fix DeprecationWarning in tests when accessing collections.abc classes via collections (#6473) 2019-02-25 15:22:45 +01:00
Frédéric Massart
94fbfcb6fd Added lazy evaluation to composed permissions. (#6463)
Refs #6402.
2019-02-25 13:47:02 +01:00
Carlton Gibson
8a29c53226 Allowed Q objects in limit_choices_to introspection. (#6472)
Closes #6470.
2019-02-25 10:49:29 +00:00
Charlie Hornsby
07c5c968ce Fix DeprecationWarning when accessing collections.abc classes via collections (#6268)
* Use compat version of collections.abc.Mapping

Since the Mapping class will no longer be available to import directly
from the collections module in Python 3.8, we should use the
compatibility helper introduced in #6154 in the fields module.

* Alias and use compat version of collections.abc.MutableMapping

Since the MutableMapping class will no longer be available to import
directly from the collections module in Python 3.8, we should create an
alias for it in the compat module and use that instead.
2019-02-25 09:17:04 +01:00
Ryan P Kilby
286cf57a8d
Update filtering docs (#6467) 2019-02-22 10:58:01 -08:00
Carlton Gibson
d932baa646
Corrected link to ajax-form library.
Closes #6465.
2019-02-22 11:11:52 +01:00
Allan Reyes
d110454d4c Added SearchFilter.get_search_fields() hook. (#6279) 2019-02-19 17:18:14 +01:00
Si Feng
1ece516d2d Adjusted field validators to accept iterables. (#6282)
Closes 6280.
2019-02-19 16:38:20 +01:00
Carlton Gibson
6de33effd6
Doc’d requirement to implement has_object_permission() (#6462)
…when using provided permission classes.

Closes #6402.
2019-02-19 16:18:55 +01:00
jeffrey k eliasen
eb3180173e Made templates compatible with session-based CSRF. (#6207) 2019-02-19 12:15:03 +01:00
Xavier Ordoquy
1660469ed8
Merge pull request #6460 from michael-k/docs-py3-compat
Fix Python 3 compat in documentation
2019-02-17 22:16:35 +01:00
Michael Käufl
f9401f5ff0
Fix Python 3 compat in documentation 2019-02-16 15:47:13 +01:00
Rohit Gupta
de3929fb33 Add Python 3.7 to classifiers. (#6458) 2019-02-15 10:57:02 +01:00
kuter
e8b4bb1471 Added tests for generateschema management command. (#6442) 2019-02-14 17:51:10 +01:00
Carlton Gibson
65f5c11a5b Document support for Django 2.2. 2019-02-14 15:57:20 +01:00
Carlton Gibson
1c5466eae7 Remove Django 2.2 from allowed failure. 2019-02-14 15:57:20 +01:00
Carlton Gibson
59fcbc6dd5 Add migration for generic relations Tag model. 2019-02-14 15:57:20 +01:00
Carlton Gibson
481ae69df3 Add migration for CustomToken test model.
Move authentication tests to sub-app to enable this.
2019-02-14 15:57:20 +01:00
Carlton Gibson
cb4cbb61f2 Fix search filter tests against Django 2.2.
Django 2.2 enables foreign key constraint checking on SQLite.
2019-02-14 15:57:20 +01:00
Carlton Gibson
606dd49227 Update tox to use Django 2.2b2. 2019-02-14 15:57:20 +01:00
Carlton Gibson
3b996c6dc2
Correct 3rd-party-packages link in issue template.
Closes #6457
2019-02-14 12:01:36 +01:00
Xavier Ordoquy
d23ea30d26
Merge pull request #6454 from johnthagen/patch-1
Fix typo in caching docs
2019-02-14 06:47:31 +01:00
johnthagen
9f66fc9a7c
Fix typo in caching docs 2019-02-13 19:00:16 -05:00
briwa
dc6b3bf42e Fix tutorial instruction to also add pyyaml (#6443) 2019-02-07 09:10:11 +01:00
Tanner Prestegard
abf07e672e Fix throttling documentation for specifying alternate caches (#6446) 2019-02-06 21:26:09 +01:00
carlfarrington
3c5c61f33b fix for a couple of missing words (#6444) 2019-02-06 09:35:04 +00:00
jhtimmins
7c6e34c14f Fix typo: 'what' to 'that' (#6437) 2019-02-02 14:49:58 +01:00
Daniel Roseman
7310411533 Updated example models to use __str__ in relations docs. (#6433) 2019-02-01 19:50:27 +01:00
Carlton Gibson
63e352586b
Drop testing Python 3.5 against Django master. (#6431)
Not supported in Django 3.0.
2019-01-31 17:16:43 +01:00
Asif Saif Uddin
2b62941bb4 Added testing against Django 2.2a1. (#6422)
* Added testing against Django 2.2a1.
* Allow failures for Django 2.2
2019-01-31 16:50:36 +01:00
Carlton Gibson
190f6201cb
Update Django Guardian dependency. (#6430)
* Update Django Guardian dependency.
* Skip testing Guardian on PY2. See https://github.com/django-guardian/django-guardian/issues/602
2019-01-31 15:59:19 +01:00
Carlton Gibson
bd9a799e16
Fixed SchemaView to reset renderer on exception. (#6429)
Fixes #6258.
2019-01-31 15:28:01 +01:00
Carlton Gibson
f54a220d8f
Corrected coreapi CLI code example generation. (#6428)
Remove “> “ when rendering template.
Closes #6333.
2019-01-31 11:36:40 +01:00
Andy Babic
87ade870c3 Added 'request_forms' block to base.html (#6340) 2019-01-24 16:30:46 +01:00
Carlton Gibson
9ff0092061 Added release note stub for v3.9.2. 2019-01-24 16:25:47 +01:00
Marcin Popławski
4c2af75957 Updated links to djangorestframework-api-key project. (#6414) 2019-01-24 16:10:11 +01:00
Carlton Gibson
8d20e10218
Deferred schema renderer creation to avoid requiring pyyaml. (#6416)
Closes #6366.
2019-01-24 16:01:06 +01:00
Carlton Gibson
f539c0dbd1
Removed incorrect DictField docstring. (#6417)
Closes #6363.
2019-01-24 15:18:22 +01:00
Carlton Gibson
0ac20a3d8e
Updated filtering docs to use filterset_fields. (#6415)
Closes #6411.
2019-01-21 21:00:54 +01:00
Steven Loria
271c4c5920 Remove sudo from .travis.yml (#6408)
Travis CI has migrated their infrastructure
https://blog.travis-ci.com/2018-11-19-required-linux-infrastructure-migration
2019-01-17 13:58:24 +00:00
Sébastien Diemer
822b85ac36 routers: invalidate _urls cache on register (#6407)
see https://github.com/encode/django-rest-framework/issues/5660

Trying to register new routes on a router after having accessed the
router `urls` attribute leads to surprising results.
The route is added without error to the router's `registry` but the urls
are not updated, because they are cached in `_urls`.
This commit invalidates the cache after each new registration.
2019-01-17 13:07:57 +00:00
Tom Christie
c049777dc7 Add missing item in 3.9.1 release notes 2019-01-16 13:39:36 +00:00
Tom Christie
453196e9c3
Version 3.9.1 (#6405)
* Version 3.9.1

* Upgrade bootstrap

* Release notes for 3.9.1
2019-01-16 13:27:35 +00:00
Yury V. Zaytsev
4bb9a3c484 Fix XSS caused by disabled autoescaping in the default DRF Browsable API view templates (#6330)
* Add test that verifies that HTML is correctly escaped in Browsable API views

* Fix `urlize_quoted_links` tag to avoid double escaping in autoescape mode

* Fix XSS in default DRF Browsable API template by re-enabling autoescape
2019-01-16 12:36:25 +00:00
Adrien Brunet
e3bd4b9048 Fix #1811: take limit_choices_to into account with FK (#6371)
* Fix issue1811: take limit_choices_to into account with FK

* Issue 1811: Add tests to illustrate issue

* Filter queryset only if limit_choices_to exists

* Move test_relations_with_limited_querysets file within test_relations_pk

* move limit_choices_to logic from relations.py to utils/field_mapping.py

* move limit_choices_to above other check to avoid conflicts
2019-01-08 13:49:47 +00:00
johnthagen
9c408b296b Remove reference to deprecated drf-openapi package (#6398) 2019-01-08 12:47:09 +00:00
Matt Wiens
e0ae975e5c Fix a badly formatted title in docs (#6089)
While having code blocks in a title is valid Markdown, MkDocs does not
render it as expected. This removes a code block placed in a title.
2019-01-08 12:07:00 +00:00
Stephen Finucane
c052a86c7b compat: (py2) urlparse = urllib.parse (py3) (#6262)
* compat: (py2) urlparse = urllib.parse (py3)

We were mistakenly importing the 'urlparse' function from the Python 2
'urlparse' module, as opposed to the module itself. Correct this.

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

* compat: Remove 'compat.urlparse'

We can just use Django's vendored six library, like we do everywhere
else.

Signed-off-by: Stephen Finucane <stephen@that.guru>
2019-01-08 12:03:02 +00:00
johnthagen
a49d744d5e Fix OpenAPI links (#6382) 2019-01-08 11:56:42 +00:00
johnthagen
0860ef9eee Update quickstart to Django 2.0 routing syntax (#6385)
* Update quickstart to Django 2.0 routing syntax

* Remove uneccessary raw string identifiers

* Correctly import path function

* Fix import path to use django.urls

This is what is prescribed in the Django 2.1 tutorial
2019-01-08 11:53:51 +00:00
Carlton Gibson
587058e3c2 Allow run_validators() to handle non-dict types. (#6365)
Fixes #6053.

Original test case thanks to Vincent Delaitre in #6242.
2019-01-08 11:39:30 +00:00
Yaser Khahani
0cf18c4163 Use Default Version in URLPathVersioning if 'version' Didn't Specified by Client (#6380)
* Use Default Version in URLPathVersioning if 'version' Didn't Passed

* Clean Code
2019-01-08 11:34:54 +00:00
Adrien Brunet
4863a24451 Fix links 404/302/303 in docs/community (#6387)
* Fix links 404/302/303

* Fix machinalis links in docs

* Fix kickstarter links in documentation

* Fix kickstarter links in documentation

* Fix kickstarter links in documentation - dropping links when broken
2019-01-08 11:15:53 +00:00
johnthagen
7749e4e3be Make code snippet Python 3 compatible (#6377) 2019-01-04 18:00:38 -08:00
Adrien Brunet
1e2fd25f54 Fix #3387: Documentation - Remove leading '.' before format option (#6388) 2019-01-04 14:45:08 +00:00
Xavier Ordoquy
030119c117
Merge pull request #6386 from philratcliffe/fix_missing_import_in_example_code
Fix missing import in example code
2018-12-28 17:54:41 +01:00
Phil Ratcliffe
1a9548db4f Fix missing import in example code 2018-12-28 16:10:08 +00:00
Anuvrat Parashar
97a47958c0 correct grammar, remove common noun after proper noun. (#6383)
`MultipartParser` is enough to denote that it is a parser.
2018-12-24 15:54:27 +00:00
Xavier Ordoquy
5fd12d1b16
Merge pull request #6376 from johnthagen/patch-1
Fix example to be Python 3.x and 2.7 compatible
2018-12-23 07:46:35 +01:00
johnthagen
f0712aa78a
Fix example to be Python 3.x and 2.7 compatible 2018-12-22 15:29:02 -05:00
Carlton Gibson
86aa7768a7 Update quote in relations.md (#6373)
Fixes #6372.
2018-12-21 11:39:01 +00:00
Carlton Gibson
63e6bbfd36 Note that only latest patches of Python & Django are supported. (#6370)
Fixes #6367.
2018-12-20 13:41:54 +00:00
Dario Cangialosi, Coder
fa57fb8aeb Use HTTPS URL example for git clone commands. (#6134) 2018-12-19 19:28:03 +01:00
Alf
963ce306f3 Added "allow_unicode" to generated kwargs for ModelSerializer SlugField (#6315) 2018-12-19 15:37:52 +01:00
Cyrus Ghazanfar
7ad5bdb669 Adjusted login template override example (#6265) 2018-12-19 15:25:34 +01:00
Jonathan Berger
1348bdc48a Fixed quickstart.md typos (#6348) 2018-12-19 14:50:14 +01:00
Xavier Ordoquy
a52087b1b8
Merge pull request #6362 from adrienbrunet/typo
docs: typo in permissions (double space)
2018-12-19 14:34:18 +01:00
Adrien Brunet
c4a021185f docs: typo in permissions (double space) 2018-12-18 13:03:03 +01:00
Tom Christie
2aecef3460 Update kloudless logo 2018-12-18 11:23:08 +00:00
Tom Christie
3453d65655 Update Kloudless logo 2018-12-18 11:18:40 +00:00
Michael D. Hoyle
a64980232a Add example of gender-neutral language in contributing guide. (#6358) 2018-12-17 21:10:39 +01:00
Dan Wilson
ef61288d77 Remove mention of djangorestframework-jwt (#6353)
Follow-up to https://github.com/encode/django-rest-framework/pull/6138
2018-12-13 21:01:10 +00:00
JerzySpendel
627eeb8202 Add missing comma in documentation of permission composition (#6336) 2018-12-07 16:44:57 -05:00
Josh Smith
facb433c89 Remove unmaintained digest authentication package (#6347)
https://github.com/juanriaza/django-rest-framework-digestauth has not been updated in 5 years and is currently incompatible with the latest DRF ecosystem.
2018-12-06 16:26:40 +00:00
HoangYell
b61806e3b3 add "js-tooltip" class to "POST" button (#6344)
the tool tip of "POST" button is different from other buttons, since it loses the "js-tooltip" class.
2018-12-03 12:10:05 +00:00
Benjamin Pereto
5a54f897ec FIX: openapi schema title should be a string not a tuple (#6259) 2018-11-28 12:45:26 +00:00
Xavier Ordoquy
11edf572c5
Merge pull request #6299 from encode/xordoquy/fix_composable_permissions
Fix composable permissions
2018-11-27 15:47:30 +01:00
Xavier Ordoquy
74574217a4 Fix composable permissions
In some cases we end with an operation between two `OperandHolder`.
This didn't work as it didn't knew how to deal with | or &
This fixes by adding those operations.
2018-11-27 15:29:44 +01:00
takaaki shimbo
0f5dfe8b3c Fix typo in schemas (#6332)
* Fix typo in generators.py

* Fix typo in inspectors.py

* message line too long

* Change backslash to multiline strings

* Removed trailing whitespace from assertion message
2018-11-26 10:14:59 -08:00
Ryan P Kilby
9b7db8dd69
Travis has released Xenial support (#6322) 2018-11-20 23:45:04 -08:00
Tom Christie
2084555fbe Update Lights On logo 2018-11-16 15:41:38 +00:00
Mice Pápai
d0369b27cd update docs/api-guide/serializers.md: consistency (#6320) 2018-11-15 14:44:54 +00:00
Tom Christie
2c0b2bd44e
Add 'Lights On Software' (#6319)
* Add 'Lights On Software'

* Fix link
2018-11-15 13:52:24 +00:00
Tom Christie
588c6976d4
Delete lightson.png 2018-11-15 12:06:47 +00:00
Tom Christie
bc36cf5e2b
Lights On 2018-11-15 12:06:18 +00:00
Tom Christie
f73b4896b8
Lights On Software 2018-11-15 12:04:06 +00:00
Stan Fateev
f7d2839562 Typo fix in the release announcement (#6318) 2018-11-14 07:50:28 +01:00
Xavier Ordoquy
bf9533ae37
Merge pull request #6286 from markddavidoff/patch-1
permissions must return a boolean to allow &/| operator comparison
2018-11-05 16:04:08 +00:00
Stephen Finucane
fae7e91728 docs: Remove references to drf-openapi (#6272)
This has been EOL'd in favour of drf-yasg [1].

[1] https://github.com/limdauto/drf_openapi/commit/1673c6e0

Signed-off-by: Stephen Finucane <stephen@that.guru>
2018-11-03 15:57:47 +01:00
Tom Snee
d59a130168 Fixes an import statement in chapter 5 of the tutorial. (#6267) 2018-11-02 08:48:39 -07:00
ilmucio
40da2a21ef Update authentication.md (#6291) 2018-10-29 15:43:06 -07:00
Mark Davidoff
1f13b6f6b2 use actual user instead of fake user in permission composition test 2018-10-29 10:45:40 -07:00
Zach Wernberg
67e99a29b8 Fix typo in release-notes.md (#6285) 2018-10-29 10:03:34 -07:00
Mark Davidoff
fc08e0189f
update tests to reflect that django now returns a callable for is_authenticated 2018-10-29 08:26:20 -07:00
Mark Davidoff
6f2c0dbf4d
permissions must return a boolean
`x and y` actually returns object y when both are true. the means P & IsAuthenticated will fail with TypeError: unsupported operand type(s) for &: 'instance' and 'bool' as IsAuthenticated now returns a CallableBool which does not overload __ror__
2018-10-28 14:12:39 -07:00
Tano Abeleyra
9d001cd84c Fix typo in testing.md (#6257) 2018-10-18 15:42:52 -07:00
Tom Christie
2c9c0f1b7f
Version 3.9 (#6247)
* Release notes to 5174a26ec9

* Update version for v3.9.0

* Removed exclude_from_schema per deprecation policy.

* Updated list_route() and detail_route() deprecations.

* Weakened to PendingDeprecationWarning for `base_name`

cc @rpkilby.

* Add (beginning of) 3.9 release announcement.

@tomchristie: Input on OpenAPI and What’s Next very welcome! :)

* Add announcement section for Extra Actions in Browsable API

* Update release notes and add deprecation note for Django Guardian backend.

* Add release note for #6073

* Add release notes to dd19a44583

* Adding release notes

* Update 3.9 announcement

* Add Oct 18 release date
2018-10-18 10:38:46 +01:00
Tom Christie
28040b3bda
Upgrade Auklet to premium (#6244) 2018-10-15 17:31:36 +01:00
Tom Christie
1c3f796219
Add kloudless as a new premium sponsor (#6241) 2018-10-11 14:48:05 +01:00
Tom Christie
ebc5393776 Add spacing around kloudless logo 2018-10-11 14:06:33 +01:00
Tom Christie
317d2489e4 Add Kloudless logo 2018-10-11 14:03:02 +01:00
Dennis Kliban
dd19a44583 Problem: autoescape not getting passed to urlize_quoted_links filter (#6191)
Solution: set needs_autoescape=True when registering the filter

Without this patch, the disabling autoescape in the template does not work.
2018-10-10 10:36:04 +02:00
Daniel Bate
5feb835929 Feature/action docs sections (#6060)
* added ability to add sections to custom action documentation

* added tests to cover docs sections in custom actions

* added method specific docs test for action mapping

* added docs for custom action documentation
2018-10-10 10:29:29 +02:00
Tom Christie
6522d4ae20
Add OpenAPIRenderer by default, and add schema docs. (#6233)
* Add OpenAPIRenderer as a default for get_schema_view, and start adding schema docs

* Add optional pyyaml

* Updating schema docs
2018-10-04 14:05:55 +01:00
Jufe Brown-Tsai
18ad3290ef Documentation fix for django-admin commands (#6232)
* fix django-admin commands on quickstart doc

* fix django-admin commands on tutorial/1-serialization doc

* fix django-admin command on readme

* fix django-admin command on docs/community/project-management.md
2018-10-03 16:16:52 +01:00
Xavier Ordoquy
b41a6cfa38 permissions: Allow permissions to be composed (#5753)
* permissions: Allow permissions to be composed

Implement a system to compose permissions with and / or.
This is performed by returning an `OperationHolder` instance that keeps the
permission classes and type of composition (and / or).
When called it will return a AND/OR instance that will then delegate the
permission check to the operands.

* permissions: Add documentation about composed permissions

* Fix documentation typo in permissions
2018-10-03 15:36:24 +01:00
Tom Christie
8908934928
Add OpenAPIRenderer and generate_schema management command. (#6229)
* Add OpenAPIRenderer and generate_schema command

* Add both OpenAPIRenderer and JSONOpenAPIRenderer

* Add flags to generate_schema command

* Fix syntax error

* Pull coreschema references into method, so they are only used if 'OpenAPIRenderer' is in use.

* generate_schema -> generateschema, and fix to OpenAPIRenderer

* Ensure that renderers generate bytes and generateschema outputs text

* Drop unused import
2018-10-03 15:28:04 +01:00
Tom Christie
c9d2bbcead
Update codecov.yml 2018-10-02 16:57:49 +01:00
Jerome Leclanche
0eb2dc1137 Prohibit null characters in CharField by default (#6073)
* Implement an allow_null_bytes argument to CharField (default True)
* Switch to using native ProhibitNullCharactersValidator instead
2018-10-02 16:54:15 +02:00
Ryan P Kilby
66183389f6 Deprecate DjangoObjectPermissionsFilter (#6075) 2018-10-02 16:34:25 +02:00
Ryan P Kilby
903204cd79 Fix action support for ViewSet suffixes (#6081)
* Add suffix support for actions

Removes the newly introduced `action.name` in favor of leveraging the
View's `.get_view_name()` method, which supports both name and suffix.

* Fix view description func docstrings

* Test action decorator name & suffix kwargs

* Adjust 'extra action' docs
2018-10-02 16:22:21 +02:00
Tom Christie
20a7734dce Bring docs license text up to date 2018-10-02 11:12:31 +01:00
Lewis M. Kabui
d0995fac70 Remove dot character from "pagination_class" (#6137) 2018-10-02 08:49:31 +02:00
Matheus Cansian
9ecce21044 Update JWT docs. (#6138)
* Remove mentions to djangorestframework-jwt in docs
* Remove links for blimp and djangorestframework-jwt
2018-10-02 08:43:45 +02:00
Jon Dufresne
878f9d2783 Prefer https:// for URLs when available throughout project (#6208) 2018-10-02 08:28:58 +02:00
Tom Christie
d1514d1f9c Update codecov.yml (#6224) 2018-10-01 18:12:03 +02:00
Anish Shrestha
2e8ccfd883 Fix typo in docs (#6212) 2018-09-25 12:11:13 -07:00
Anish Shrestha
d976ac56b0 Fix spelling error (#6198) 2018-09-21 08:55:32 +02:00
Melissa Lewis
b090ae9d30 Fix docs typos (#6195) 2018-09-18 15:32:32 -07:00
Ryan P Kilby
5174a26ec9 Simplify job matrix on Travis (#6174)
* Move to explicit Travis matrix

* Cleanup Python 3.6 matrix
2018-09-17 10:41:55 +02:00
Jon Dufresne
ed6340ee76 Remove unnecessary use of compat shim six.binary_type (#6189)
The type bytes is available on all supported Pythons. On Python 2.7, it
is an alias for str, same as six.binary_type. Makes the code more
forward compatible with Python 3.
2018-09-17 10:39:59 +02:00
Ryan P Kilby
fc6cbb5b26 Allow nullable BooleanField in Django 2.1 (#6183)
* Add tests for BooleanField when nullable

* Allow nullable BooleanField in Django 2.1

* Drop 'BooleanField.allow_null' check

* Remove conflicting false/null values
2018-09-13 17:25:03 +01:00
Tom Christie
5f1f2b1003 Higher res. load impact logo 2018-09-11 12:55:53 +01:00
Tom Christie
4e093b0e25 Add Load Impact to README 2018-09-11 11:53:45 +01:00
Tom Christie
9140629c45 Fix Load Impact URL 2018-09-11 11:41:49 +01:00
Tom Christie
4033f0c6b3
Add Load Impact to premium sponsors (#6176) 2018-09-11 11:40:47 +01:00
Ryan P Kilby
7f77340b33
Add Python 3.7 support (#6141) 2018-09-10 21:44:23 -07:00
Jerome Leclanche
612a7b989f Fix Python 3.8 compatibility (#6154) 2018-09-10 21:12:32 -07:00
Jon Dufresne
4d57d46bf8 Prefer io.BytesIO over six; available on all supported Pythons (#6168)
On all supported Pythons, the io.BytesIO is always a stream
implementation using an in-memory bytes buffer.

Makes code slightly more forward compatible by reducing use of the six
module and promotes more forward compatible practices in the docs.
2018-09-09 11:53:41 +01:00
Xavier Ordoquy
1d5771d980
Merge pull request #6165 from dsanders11/patch-1
Fix validate_my_field signature
2018-09-07 05:44:24 +00:00
David Sanders
69f605f30e
Fix validate_my_field signature 2018-09-06 18:16:06 -07:00
Timothy Allen
bc573d8096 Add drf-renderer-xlsx package. (#6147)
* Add drf-renderer-xlsx package.

* Gah, tabs creeped in; never leave your default editor environment. :)
2018-09-06 11:01:57 +01:00
oliver
bcc565f387 Clean up unnecessary if statement (#6163) 2018-09-06 07:25:20 +01:00
Michael
2c992f09da Mention Django 2.1 compat where missing (#6158) 2018-09-04 11:33:42 -07:00
Jon Dufresne
468cdd16ed Remove unnecessary models.py file (#6142)
Since Django 1.7, an empty models.py file is not required.

See
https://docs.djangoproject.com/en/dev/releases/1.7/#app-loading-refactor

> It is possible to omit models.py entirely if an application doesn’t
> have any models.
2018-08-28 09:51:28 +02:00
Ryan P Kilby
c4b068cfd3
Fix dist build (#6139)
* Use tox-venv to reduce warnings in output

* Remove .egg-info/ to allow wheel installation

tox now invokes pip as a python module instead of through its entry
point. "python -m" adds the current directory to the PYTHONPATH, picking
up the .egg-info/ metadata directory, tricking pip into thinking that
the package is already installed (and thus not installing the wheel).
Deleting the metadata directory fixes this.
2018-08-24 15:57:45 -07:00
Craig Johnson
90ed2c1ef7 Small grammar correction in quickstart. (#6121)
Just felt the sentence could use some improving.
2018-08-13 10:32:17 +01:00
Craig de Stigter
81fa4b4f75 Fix CSRF cookie check failure when using session auth with django 1.11.6+ (#6113)
Test included. Fixes #6088
2018-08-07 08:18:56 +01:00
Oleg
2fab7838ef Improve ModelSerializer.create() error message. (#6112) 2018-08-06 20:11:55 +02:00
Oleg
8b5e830bce Handle models without .objects manager in ModelSerializer. (#6111)
* Handle models without .objects manager in ModelSerializer.

* Improvements according to review comments.
2018-08-06 14:30:43 +02:00
Jon Dufresne
5ad24b0811 Test using Django 2.1 final release (#6109) 2018-08-06 10:06:17 +02:00
Shabda Raaj
8f9b875456 Add building with drf book (#6102)
* Added building APIs with Django and DRF book

* Added book cover
2018-08-01 16:43:09 +01:00
Michael
8493990a66 Add Django 2.1 to classifiers (#6099) 2018-07-29 11:54:10 +01:00
Daniel Hahler
f404fda29c codecov: enable status for patch/changes, comment: diff (#6080)
Ref: https://github.com/encode/django-rest-framework/pull/6077#issuecomment-403838095

This is https://github.com/encode/django-rest-framework/pull/6050
without the project status, and fixes/improves the comment added in
https://github.com/encode/django-rest-framework/pull/6077.
2018-07-10 16:32:47 +02:00
dengshilong
0484d01aae Fix typo error, Link to Field (#6078) 2018-07-10 11:03:39 +02:00
Ryan P Kilby
987d73a03d Add minimal codecov comment (#6077) 2018-07-10 10:59:08 +02:00
Ryan P Kilby
33f8910b26
Fix deprecation warnings in tests (#6076)
* Fix deprecated arguments in schema tests

* Update optional reqs, fixing markdown deprecation
2018-07-09 23:56:52 -04:00
Eze Sunday
a0277919f0 Fix grammar mistake in html-and-forms.md (#6070) 2018-07-08 16:11:05 -04:00
Ryan P Kilby
38b3d0109b Only catch TypeError/ValueError for object lookups (#6028)
* Only catch TypeError/ValueError for object lookups

* Test wrapped TypeError/ValueError handling

* Raise NotImplementedError in tests instead of pass
2018-07-06 12:18:17 +02:00
Ryan P Kilby
a628a2dbce Drop Django 1.10 support (#5657)
* Remove Django 1.10 from CI

* Remove Django 1.10 compat code
2018-07-06 12:14:31 +02:00
Ryan P Kilby
9b8af04e7f Move guardian imports out of compat (#6054) 2018-07-06 11:32:02 +02:00
Ryan P Kilby
99ca078ebb Add "Community" section to docs, minor cleanup (#5993)
* Add 'Community' tab to navigation, move articles

* Drop DRF 2.x announcements and the docs note

* Drop embedded tutorial/guide/topics links

* Conver mixture of tabs/spaces => spaces

* Fix topics/community links
2018-07-06 11:28:18 +02:00
Ryan P Kilby
7095021db7 Rename base_name => basename for consistency's sake (#5990)
* Rename base_name => basename for consistency

* Update tests to use basename
2018-07-06 11:03:12 +02:00
Ryan P Kilby
f89cc066bc Admin renderer urls (#5988)
* Make admin detail link have small width

* Disable admin detail link when no URL

* Add 'AdminRenderer.get_result_url'

Attempts to reverse the result's detail view URL.
2018-07-06 10:58:26 +02:00
Daniel Hahler
3578bd6883 get_error_detail: use error_dict/error_list (#5785) 2018-07-06 10:44:58 +02:00
Ryan P Kilby
6511b52cca Fix schemas for extra actions (#5992)
* Add failing test for extra action schemas

* Add ViewInspector setter to store instances

* Fix schema disabling for extra actions

* Add docs note about disabling schemas for actions
2018-07-06 10:35:36 +02:00
Daniel Hahler
b23cdaff4c tox/pytest: move posargs, use -ra (#6039)
- tox: move {posargs} to the end, so that it can override previous
  entries, e.g. `-ra` when `-rw` was used.
- pytest: add `-ra` to addopts: it is good to see a summary of skipped
  and failed tests at the end.
2018-07-06 10:34:11 +02:00
Ryan P Kilby
0148a9f8da Improvements to ViewSet extra actions (#5605)
* View suffix already set by initializer

* Add 'name' and 'description' attributes to ViewSet

ViewSets may now provide their `name` and `description` attributes
directly, instead of relying on view introspection to derive them.
These attributes may also be provided with the view's initkwargs.

The ViewSet `name` and `suffix` initkwargs are mutually exclusive.

The `action` decorator now provides the `name` and `description` to
the view's initkwargs. By default, these values are derived from the
method name and its docstring. The `name` may be overridden by providing
it as an argument to the decorator.

The `get_view_name` and `get_view_description` hooks now provide the
view instance to the handler, instead of the view class. The default
implementations of these handlers now respect the `name`/`description`.

* Add 'extra actions' to ViewSet & browsable APIs

* Update simple router tests

Removed old test logic around link/action decorators from `v2.3`. Also
simplified the test by making the results explicit instead of computed.

* Add method mapping to ViewSet actions

* Document extra action method mapping
2018-07-06 10:33:10 +02:00
Daniel Hahler
56967dbd90 Fix upload parser test (#6044) 2018-07-05 23:52:32 -04:00
Ryan P Kilby
0e10d32fb1
Add NotImplementedError to coverage exclusion (#6057) 2018-06-24 17:56:31 -04:00
Ryan P Kilby
c5ab65923f
tests/test_permissions.py: do not add view perm for dj21 (#6055) 2018-06-23 07:31:06 -04:00
Daniel Hahler
499533d219 Use [tool:pytest] header in setup.cfg (#6045) 2018-06-22 18:14:26 -04:00
Chris Shyi
d9f541836b Update to Django 2.0 Routing Syntax (#6049) 2018-06-22 10:28:59 +02:00
Ryan P Kilby
1a170438d2 Add "optionals not required" build (#6047) 2018-06-22 10:16:57 +02:00
Daniel Hahler
7e0ad9262e tests: update pytest/pytest-django (#6042) 2018-06-21 16:23:52 -04:00
Daniel Hahler
a44cb67988 tests: fix usage of transaction.non_atomic_requests (#6043) 2018-06-21 14:44:58 -04:00
Daniel Hahler
06526cafe5 runtests.py: clean up PYTEST_ARGS (#6040)
1. `tests` and `--tb=short` is not necessary, since it is in
`pytest.addopts` already.
2. removes `-s` (shortcut for --capture=no): it is typically a good idea
   to not display output from successful tests.
2018-06-21 14:28:25 +01:00
Çağıl
8f55cd8db5 Fix url for group_names action example (#6036) 2018-06-21 04:29:05 -04:00
Asif Saifuddin Auvi
d778c5e51e Update tox to use Django v2.1b1 (#6037) 2018-06-21 09:07:33 +02:00
William S. Vincent
feffa109a8 Add REST APIs with Django book (#6033)
Just published book dedicated to DRF.
2018-06-20 00:24:26 +01:00
Xavier Ordoquy
3fcc076d91
Merge pull request #6024 from tveastman/master
Documentation: Correct the signature for HyperlinkedRelatedField.get_object()
2018-06-13 07:43:35 +02:00
Tom Eastman
be2bcf7e3f Documentation: Correct the signature for HyperlinkedRelatedField.get_object() 2018-06-13 16:39:28 +12:00
Emeka Icha
a21484d90e (fix) link to disqus article on cursor pagination (#6020) 2018-06-12 10:34:28 +01:00
Xavier Ordoquy
8688c99602
Merge pull request #6019 from jdufresne/pypi-register
Update incorrect PyPI URL to register an account
2018-06-10 09:49:16 +02:00
Jon Dufresne
89fb0b0f99 Update incorrect PyPI URL to register an account
To register an account on PyPI, the URL is
https://pypi.org/account/register/, which changed after the move to
pypi.org.
2018-06-09 19:09:31 -07:00
Tom Christie
26b0f650d6
Update LICENSE.md 2018-06-04 09:16:18 +01:00
Tom Christie
206423009b
Update LICENSE.md 2018-06-04 09:15:05 +01:00
Steven Loria
cf925caa48 Render markdown readme on PyPI (#6004)
* Render markdown readme on PyPI

PyPI now supports GitHub-flavored Markdown descriptions
(https://blog.thea.codes/github-flavored-markdown-on-pypi/),
so there's no need to convert the README to rst with pypandoc
any more.

* Remove readme checking

Checking markdown descriptions is not necessary.
See https://github.com/pypa/readme_renderer#markdown

* Upgrade twine
2018-06-03 19:21:04 +01:00
Matt Layman
f67d23c441 Add docs link to Caching API Guide. (#6012) 2018-05-31 09:58:02 +02:00
Teppei Fukuda
fe54575e6a Fix exceptions.md (#6003) 2018-05-25 10:42:22 +01:00
Xavier Ordoquy
a7cd1dbc43
Merge pull request #6001 from auvipy/master
updated tox and travis for django 2.1 alpha1
2018-05-23 21:10:27 +02:00
Asif Saifuddin Auvi
2634294667 updated tox and travis for django 2.1 alpha1 2018-05-23 16:33:15 +06:00
int3l
1ee3829a2f Update the http signature auth library ref link (#5997)
* Update the http signature auth library ref link

It seems that the djangorestframework-httpsignature package is outdated
and there is updated fork named drf-httpsig.

* Fixing the link ref format in the http signature section
2018-05-22 12:22:09 +01:00
Tamirlan Omarov
edfcbe076d Added pagination section to the quickstart page (#5987) 2018-05-21 13:32:07 +01:00
John Franey
f20e282d15 Update documenting-your-api.md (#5991)
Fix link to "Schemas as Documentation: Examples"
2018-05-17 00:36:41 -04:00
Eduardo GP
ff4429fad4 fix e.indexOf is not a function error (#5982) 2018-05-11 21:49:29 +01:00
Craig de Stigter
9629886915 Fixed AttributeError from items filter when value is None (#5981) 2018-05-11 08:50:08 +02:00
Daniel Hahler
c17b4ad0d0 Include coverage for tests (#5970)
It is useful to see if tests itself are covered after all - missing
coverage there typically indicates dead/missed code paths.

This also uses `source=.` and includes (with run and report), to help
Codecov with reporting.
Ref: https://github.com/encode/django-rest-framework/pull/5956
2018-05-08 14:02:45 +01:00
Daniel Hahler
275c157341 tests: remove some dead code, use assert 0 for never called methods (#5973)
* tests: remove some dead code, use `assert 0` for never called methods

* fixup! tests: remove some dead code, use `assert 0` for never called methods
2018-05-08 13:28:46 +01:00
Daniel Hahler
4527a753cd Move pytest config to setup.cfg (#5979)
Also adds `testspath` to improve test collection performance.
2018-05-08 13:28:16 +01:00
Daniel Hahler
fca39f9dbb tests: fix test_write_only_fields not being executed (#5971)
This adds the required `test_` prefix.
2018-05-08 09:27:35 +01:00
Daniel Hahler
4c29752b6a requirements-testing: update pytest and pytest-django (#5972) 2018-05-08 09:27:25 +01:00
Tom Christie
da4ecfddc2
Update .gitignore 2018-05-08 09:21:32 +01:00
Tom Christie
6957aaae85
Delete config 2018-05-08 09:20:01 +01:00
Tom Christie
0218f20ac4
Delete .editorconfig 2018-05-08 09:19:31 +01:00
Ari Rouvinen
45acfe05b4 Add missing comma (#5978) 2018-05-08 09:15:59 +01:00
Daniel Hahler
40d5985f57 requirements-optionals: use psycopg2-binary (#5969)
Ref: https://github.com/encode/django-rest-framework/pull/5967#issuecomment-386431446
2018-05-08 09:15:32 +01:00
Andreas Lutro
a6b6b6ce55 remove references to DOAC in docs (#5977)
Project has been archived on github and recommends alternative.
2018-05-08 09:10:43 +01:00
Chris Shyi
fc2143207b Update tutorial to Django 2.0 routing syntax (#5963) (#5964)
Update tutorial to Django 2.0 routing syntax
2018-05-08 09:06:14 +01:00
Xavier Ordoquy
4340ff42de
Merge pull request #5976 from victormpa/fix_filter_docs
Added import statement on filtering docs
2018-05-07 05:40:59 +00:00
Victor Martins
21c0fcf63b Added import statement on filtering docs 2018-05-06 00:02:09 -03:00
Daniel Hahler
fd4282c7fa pytest: use --strict (#5966)
This causes errors with invalid markers:

> AttributeError: 'skipUnless' not a registered marker

Fixed in https://github.com/encode/django-rest-framework/pull/5965.
2018-05-03 21:43:57 +01:00
Daniel Hahler
d4dc24ea3e requirements-optionals.txt: bump psycopg2 to 2.7.4 (#5967)
With 2.7.3 I am seeing an ImportError on Arch Linux:

> ImportError: …/.venv/lib/python3.6/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so:
> symbol __res_maybe_init version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference
2018-05-03 13:32:39 +01:00
Daniel Hahler
e79610af3a tests: fix skipping with TestPosgresFieldsMapping (#5965)
`pytest.mark.skipUnless` does not exist, it was confused with
`unittest.skipUnless` probably.
2018-05-03 13:31:46 +01:00
Çağıl
8c03c49400 update testing.md - fixes related to RequestsClient (#5959)
* Include import for RequestsClient in the docs.
* Use fully qualified URLs for `RequestsClient` in the docs.
2018-04-26 12:47:38 +01:00
Ryan O’Hara
a11938ce96 Fixed instance being overwritten in pk-only optimization try/except block (#5747) 2018-04-24 16:15:38 +02:00
Noam
7268643b25 min_value/max_value support in DurationField (#5643)
* Added min_value/max_value field arguments to DurationField.
* Made field mapping use mix/max kwargs for DurationField validators.
2018-04-24 09:24:05 +02:00
Sascha P
7d64b7016d Removed input value from deault_error_message (#5881) 2018-04-20 16:00:27 +02:00
Jimmy Merrild Krag
4260531b6c Render descriptions (from help_text) using safe (#5869)
To allow embedded HTML, and make consistent with other usages.

Fixes #5715.
2018-04-20 15:51:27 +02:00
Jimmy Merrild Krag
5ee0e5df83 Correct schema parsing for JSONField (#5878)
Fixes #5873.
* Use Object type. 
* Add test for field_to_schema
2018-04-20 15:47:20 +02:00
Mikkel Munch Mortensen
9dbb49ef22 Docs: Match original argument names (#5889)
Change argument names in overridden field methods to match those of the base classes.
2018-04-20 15:35:09 +02:00
Jochen Wersdörfer
c4676510fd Adjusted client JWT example (#5944) 2018-04-20 15:33:59 +02:00
Craig Anderson
2ebd479759 Allow hashing of ErrorDetail to fix #5919 (#5932) 2018-04-20 15:32:37 +02:00
Christian Kreuzberger
f148e4e259 Ensure that html forms (multipart form data) respect optional fields (#5927) 2018-04-20 15:11:52 +02:00
Tom Christie
7e705246ca
Ensure docs sidebar can scroll to bottom. (#5949)
Closes #5948
2018-04-20 12:11:48 +01:00
Michael
e4b63f70d6 [docs] Remove leftover from former python 3.2/3.3 support (#5947) 2018-04-20 09:22:36 +02:00
Jon Dufresne
8c47a875ec Update all pypi.python.org URLs to pypi.org (#5942)
For details on the new PyPI, see the blog post:

https://pythoninsider.blogspot.ca/2018/04/new-pypi-launched-legacy-pypi-shutting.html
2018-04-19 08:36:18 +02:00
Tom Christie
f3d41625f5
Add Cadre as a premium sponsor (#5941) 2018-04-18 10:33:02 +01:00
Arne Schauf
d5fe1f66ac Fix a typo in the 3.8 announcement (#5940) 2018-04-18 06:36:03 +01:00
Ryan P Kilby
7078afa42c Change ISO 8601 date format to exclude year/month (#5936) 2018-04-14 05:23:31 +01:00
David Jean Louis
1c53fd3212 Added djangorestframework-datatables to third-party packages (#5931) 2018-04-10 13:25:20 +01:00
Xavier Ordoquy
4b47721c6d
Merge pull request #5930 from minitux/patch-1
[DOCS] python print syntax docs/api-guide/settings.md
2018-04-10 08:39:44 +00:00
minitux
3dd90d2b46
[DOCS] python print syntax
python3 style
2018-04-09 23:31:58 +02:00
Steven Loria
8a639c6c06 Update link to django-rest-marshmallow docs (#5925) 2018-04-09 16:48:18 +02:00
Anna Ossowski
0178d3063d
Added 3.8 release + updated monthly report link 2018-04-08 21:47:50 +02:00
Carlton Gibson
fb802c0910
Update version and notes for 3.8.2 release. (#5923) 2018-04-06 15:41:11 +02:00
Carlton Gibson
42eb5a4342
Fix read_only + default unique_together validation. (#5922)
* Add test for read_only + default unique_together validation.
* Fix read_only + default validation
2018-04-06 15:20:54 +02:00
gsvr
32caca4dd3 Import coreapi from rest_framework.compat, not directly. (#5921) 2018-04-05 15:07:49 +02:00
Michael
ffac61c6fe Docs: Add missing argument 'detail' to Route (#5920)
The namedtuple Route requires `detail` to be specified, otherwise it
fails with:
`TypeError: __new__() missing 1 required positional argument: 'detail'`

See https://github.com/encode/django-rest-framework/pull/5705/files#diff-88b0cad65f9e1caad64e0c9bb44615f9R34
2018-04-05 14:24:31 +02:00
Carlton Gibson
bc353452f4
Bump version and release notes for 3.8.1 (#5916) 2018-04-04 21:10:34 +02:00
Ryan P Kilby
cba426b34c Use old url_name behavior in route decorators (#5915)
* Wrap action decorator for old url_name behavior
2018-04-04 20:50:42 +02:00
Xavier Ordoquy
3365ec23ec
Merge pull request #5914 from encode/xordoquy/fix_release_notes
release_notes: fix call to super().data
2018-04-04 13:29:48 +00:00
Xavier Ordoquy
3a29eff5f8 release_notes: fix call to super().data
`super().data()` leads to a `TypeError` saying that 'ReturnDict' object
is not callable.
2018-04-04 15:21:36 +02:00
Carlton Gibson
2621e03aa3 Added 3.8 announcement to docs
Correct release notes MD formatting
2018-04-03 16:06:06 +02:00
Carlton Gibson
fc588f539b
Version 3.8 Release (#5769) 2018-04-03 15:35:26 +02:00
Carlton Gibson
1befab795a
Added generic 500 and 400 JSON error handlers. (#5904)
* Added generic 500 and 400 JSON error handlers.
* Docs for generic error views.
2018-04-03 09:16:36 +02:00
Xavier Ordoquy
489d3415ab required extra argument should be a boolean, not a string. (fixes #5906) 2018-03-28 12:39:18 +02:00
Tom Christie
a95cffc73e
Update README.md
Drop the 'chat on gitter' badge.
2018-03-26 12:23:49 +01:00
Andrew Tallos
36119cad31 Enable OrderingFilter to handle an empty tuple (or list) for the 'ordering' field. (#5899) 2018-03-26 12:22:45 +01:00
Craig de Stigter
a5072778e9 Don't show hidden fields in metadata (#5854)
HiddenField is meant to be hidden, but we discovered it showing up in OPTIONS requests
2018-03-23 22:47:10 +00:00
Charlie McBride
a7e2a7bfcd Add LimitOffsetPagination.get_count to allow method override (#5846)
* Add LimitOffsetPagination.get_count to allow method override

* Format method docstring
2018-03-23 22:25:43 +00:00
Xavier Ordoquy
5e6abfbafe
Merge pull request #5894 from auvipy/patch-4
update pytest to 3.5
2018-03-23 13:05:36 +01:00
Asif Saifuddin Auvi
a1c9118685
update pytest to 3.5 2018-03-23 17:23:48 +06:00
Valentino Gagliardi
812d3478bd Added: Tutorial: Django REST with React (Django 2.0) (#5891) 2018-03-21 13:08:36 +00:00
George-Cristian Bîrzan
85c588b0c1 #5848 Allow traversing nullable related fields (#5849) 2018-03-20 22:02:22 +01:00
Carlton Gibson
6c0c69ed65
Correct allow_null behaviour when required=False (#5888)
* Revert "Non-required fields with 'allow_null=True' should not imply a default value (#5639)"
    This reverts commit 905a5579df.
    Closes #5708

* Add test for allow_null + required=False
    Ref #5708: allow_null should imply default=None, even for non-required fields.

* Re-order allow_null and default in field docs
    default is prior to allow_null. allow_null implies an outgoing default=None.

* Adjust allow_null note.
2018-03-20 21:24:39 +01:00
Carlton Gibson
c2b24f83a3
Alter read_only+default behaviour (#5886)
* Always exclude read_only fields from _writable_fields

* Remove `read_only` from `CreateOnlyDefault` example.
      In this context (without mentioning `save`) now slightly misleading.
2018-03-20 21:09:31 +01:00
Anna Ossowski
12569f83c9
Update funding.md 2018-03-20 02:31:44 +01:00
Xavier Ordoquy
0b6a5e568d
Merge pull request #5882 from bholagabbar/patch-2
Updated Link to Rate Limiting Article
2018-03-19 11:02:42 +01:00
Shreyans Sheth
e3f9c65362
Updated Rate Limiting Cite
The current link was broken, fixed it. A good article on rate limiting indeed.
2018-03-19 14:24:21 +05:30
Carlton Gibson
247cf096d4
Test using model objects for dotted source default (#5880)
… when path components may be null.

Ref #5375, #5727
2018-03-16 14:51:37 +01:00
Carlton Gibson
0da461710a
Corrected docs on router include with namespaces. (#5843)
* Provide both app and instance namespace examples
* Emphasise non-namespaced option
2018-03-13 15:52:04 +01:00
gthieleb
9e08a7cbec Fixed schema for UUIDField in SimpleMetadata. (#5872)
* fix schema for UUIDField

* Add unit test for d4c8f2db
2018-03-13 15:49:15 +01:00
Xavier Ordoquy
e3544f999e
Merge pull request #5870 from cgopalan/patch-1
Add admin to installed apps to avoid test failures
2018-03-09 19:56:29 +01:00
Chandrakant Gopalan
20f1203aac
Add admin to installed apps to avoid test failures.
The tests look for the "admin" app in the list of apps. If not present, running `runtests.py` gives the following error:
```
LookupError: No installed app with label 'admin'.
```
Adding admin to `INSTALLED_APPS` fixes it.
2018-03-09 13:04:15 -05:00
Oliver Newman
d2994e0596 Fix comment typo in ModelSerializer (#5844) 2018-02-21 16:39:53 +01:00
Will Vincent
ea7d414b28 Two new tutorials (#5837)
A Todo List API with React and Blog API tutorial
2018-02-19 07:19:42 +00:00
Carlton Gibson
6ea7d05979
Corrected endpoint in tutorial instructions (#5835)
Closes #5810
2018-02-16 16:57:25 +01:00
Carlton Gibson
e34fd995cd
Made TemplateHTMLRenderer render IntegerField inputs when value is 0. (#5834)
* Fix 0 value IntegerField in TemplateHTMLRenderer

Signed-off-by: Nikhil Sheoran <nikhilsheoran96@gmail.com>

* Remove unnecessary `field.value != “”` check

* Adjust test case

Uses `vertical` templates only.
2018-02-16 16:48:20 +01:00
Carlton Gibson
da535d31dd
Fixed active timezone handling for non ISO8601 datetimes. (#5833)
* Add failing test for to_representation with explicit default timezone

See discussion here:
    https://github.com/encode/django-rest-framework/pull/5435#issuecomment-364054509

* Always run enforce_timezone
2018-02-16 16:47:49 +01:00
Daniel Hahler
2854679f56 Upgrade isort (#5817)
* Fix isort

* runtests: add --diff to ISORT_ARGS

* requirements-codestyle: bump isort to 4.3.3

* isort: move config to setup.cfg
2018-02-14 20:12:14 +00:00
James Morris
2bc7cd19a3 Update jobs.md (#5828)
Add weworkcontract.com
2018-02-14 20:10:40 +00:00
Kent Kawashima
d82b332a09 Changes ternary conditionals to be PEP308 compliant (#5827) 2018-02-14 14:06:09 +00:00
Carlton Gibson
7d0d22ffaa Use single copy of static assets. Update jQuery (#5823)
* Move font-awesome to top level.

* Use top-level jQuery & Bootstrap

* Update to jQuery v3.3.1

Compatible with Bootstrap v3.3.7
c.f. https://github.com/twbs/bootstrap/issues/16834#issuecomment-251996660

* Re-add bootstrap-theme
2018-02-12 14:14:44 +00:00
Allisson Azevedo
d1c92c81ff Add Django Rest Framework Role Filters to Third party packages (#5809) 2018-02-08 09:04:51 +01:00
Daniel Hahler
1438719979 requirements-testing: update pytest to 3.4.0 (#5815) 2018-02-08 09:00:44 +01:00
Ryan P Kilby
1bc826e6fd
Fix authtoken views imports (#5818) 2018-02-07 14:46:17 -05:00
Ryan P Kilby
c456b3c510 Fix request formdata handling (#5800)
* Rename 'wsgi' request test to more accurate 'http'

* Test duplicate request stream parsing

* Fix setting post/files on the underlying request
2018-02-05 16:24:13 +01:00
Paulo Scardine
0d5a3a00b0 Add schema to ObtainAuthToken
Add encoding parameter to ManualSchema

Closes #5676

* Fixed lint errors
* Added docs for ManualSchema encoding parameter
2018-02-05 16:16:42 +01:00
Fraire, Santiago
878fe895dc Docs: Added example reimplementing ObtainAuthToken
Closes #5802
2018-02-05 15:53:49 +01:00
Jeremy Lainé
a8d129b7da Represent serializer DictField as an Object in schema
DictFields were incorrectly being output as String in the schema.
This pull request outputs an Object instead and adds a unit test.

Update s/detail_route/action/ after rebase
2018-02-01 16:23:24 +01:00
Jeremy Lainé
27f32faee4 Fix schema generation for PrimaryKeyRelatedField (#5764)
By default all subclasses of RelatedField are output as string fields in
the schema, which works well for StringRelatedField, SlugRelatedField or
HyperlinkedRelatedField.

Handle the common case of a PrimaryKeyRelatedField pointing to an
AutoField.
2018-02-01 16:14:35 +01:00
Carlton Gibson
3c7b3ac6df
Updated step 1 of contributing guide (#5799)
* Create a fork, then clone it.
* Link to GitHub’s How-To.
2018-02-01 16:02:29 +01:00
Veli-Matti Helke
2fa04caf7c small fix to API documentation: schemas (#5796)
adding missing parameters to get_manual_fields()
2018-01-31 14:25:57 +01:00
Si Feng
df77f7bb9d Make 404 & 403 responses consistent with exceptions.APIException output (#5763) 2018-01-30 22:10:02 +00:00
Ryan P Kilby
ece4171ae4 Replace background-attachment: fixed in docs (#5777)
Fixed backgrounds have performance issues on large displays.
2018-01-30 09:08:06 +01:00
Daniel Hahler
769bc1336f ErrorDetail: add __eq__/__ne__ and __repr__ (#5787)
This adds `__eq__` to handle `code` in comparisons.

When comparing an ErrorDetail to a string (missing `code` there) the
ErrorDetail's `code` is ignored, but otherwise it is taken into account.
2018-01-30 08:45:09 +01:00
Matt Prahl
2677f59d5d Refer to "NamespaceVersioning" instead of "NamespacedVersioning" in the documentation (#5754) 2018-01-29 15:33:14 +01:00
Max Goodridge
3e5d3752e7 Fixed a typo (#5783) 2018-01-29 08:41:55 +01:00
Jon Dufresne
052a20cd7b Load 'static' instead of 'staticfiles' in templates (#5773) 2018-01-26 00:43:55 -05:00
Aseem Shrey
1664588500 Updated docs to use pip show
Show the current DRF version using `pip show`

Closes #5757
2018-01-25 10:12:13 +01:00
Ryan P Kilby
73203e6b59 Rework dynamic list/detail actions (#5705)
* Merge list/detail route decorators into 'action'

* Merge dynamic routes, add 'detail' attribute

* Add 'ViewSet.get_extra_actions()'

* Refactor dynamic route checking & collection

* Refactor dynamic route generation

* Add 'ViewSet.detail' initkwarg

* Fixup schema test

* Add release notes for dynamic action changes

* Replace list/detail route decorators in tests

* Convert tabs to spaces in router docs

* Update docs

* Make 'detail' a required argument of 'action'

* Improve router docs
2018-01-25 09:40:49 +01:00
Carlton Gibson
a540acdc95
Allowed customising API documentation code samples (#5752)
* Allowed additional languages in API documentation

* Documented renderer_classes parameter and customising languages.
2018-01-25 09:39:03 +01:00
Jeremy Lainé
588b61e171 Remove unreachable code from ManualSchema (#5766)
ManualSchema.get_link had two return statements. Prune the second
(unreachable) return.
2018-01-24 08:52:33 +01:00
Teddy Cross
78367ba102 Always fully qualify ValidationError in docs (#5751) 2018-01-19 08:40:09 +01:00
Ryan P Kilby
2709de1310 Add HStoreField, postgres fields tests (#5654)
* Test postgres field mapping

* Add HStoreField

* Ensure 'HStoreField' child is a 'CharField'

* Add HStoreField docs
2018-01-15 15:52:30 +01:00
Jon Dufresne
d3f3c3d9c1 Prefer https protocol for links in docs when available 2018-01-15 15:15:21 +01:00
Jon Dufresne
d5c34aa813 Remove unused links from docs (#5735)
Each removed link has no inline use.
2018-01-15 15:03:44 +01:00
Jon Dufresne
b2ec681d8d Pass python_requires argument to setuptools (#5739)
Helps pip decide what version of the library to install.

https://packaging.python.org/tutorials/distributing-packages/#python-requires

> If your project only runs on certain Python versions, setting the
> python_requires argument to the appropriate PEP 440 version specifier
> string will prevent pip from installing the project on other Python
> versions.

https://setuptools.readthedocs.io/en/latest/setuptools.html#new-and-changed-setup-keywords

> python_requires
>
> A string corresponding to a version specifier (as defined in PEP 440)
> for the Python version, used to specify the Requires-Python defined in
> PEP 345.
2018-01-11 08:51:34 +01:00
Jon Dufresne
ffe3dbb1b1 Perfer iter(dict) over iter(dict.keys()) (#5736)
Calling dict.keys() is unnecessary. The two are functionally equivalent
on modern Pythons.

Inspired by Lennart Regebro's talk "Prehistoric Patterns in Python" from
PyCon 2017.

https://www.youtube.com/watch?v=V5-JH23Vk0I
2018-01-08 09:49:46 +00:00
Jon Dufresne
c1848d765d Drop compat workaround for unsupported Python 3.2 (#5734) 2018-01-08 10:45:29 +01:00
Jon Dufresne
06e2ad0b7d Remove unused compat._resolve_model() (#5733)
Last use removed in c674687782.
2018-01-08 09:19:08 +00:00
Cristi Vîjdea
522d453546 Add drf-yasg to documentation and schema 3rd party packages (#5720)
Also fixed broken `swagger` link.
2018-01-02 14:51:54 +01:00
Ryan P Kilby
68519c092f Test staticfiles (#5701)
* Remove 'MIDDLEWARE_CLASSES' compat setting

* Remove 'django.setup()' compat import

* Move '--no-pkgroot' handling to conftest

* Add staticfiles handling to dist build
2018-01-02 11:35:56 +01:00
Ryan P Kilby
351503907c Add exception translation test (#5700) 2018-01-02 11:28:45 +01:00
Ryan P Kilby
b65967711c Formalize URLPatternsTestCase (#5703)
* Add formalized URLPatternsTestCase

* Update versioning tests w/ new URLPatternsTestCase

* Cleanup router tests urlpatterns

* Add docs for URLPatternsTestCase
2018-01-02 11:14:25 +01:00
David De Sousa
6b0bf72bb8 using rsplit to get module and classname for imports (#5712) 2018-01-02 10:59:08 +01:00
Cristi Vîjdea
0712094ea2 Fix typo in HostNameVersioning doc (#5709) 2018-01-02 10:52:52 +01:00
Floyd Hightower
7e2cca285d Adding missing parenthesis (#5707) 2018-01-02 10:51:42 +01:00
Ryan P Kilby
b7ed645927 Disable HTML inputs for dict/list fields (#5702) 2018-01-02 10:50:49 +01:00
Ryan P Kilby
6bd773e7f8 Improve composite field child errors (#5655)
* Fixup DictField test descriptions

* Nest ListField/DictField errors under the idx/key

* Add nested ListField/DictField tests
2018-01-02 10:45:59 +01:00
Xavier Ordoquy
22f1c59099
Merge pull request #5713 from guntanis/patch-1
Fixed "typo" in example.
2017-12-28 11:05:07 +01:00
guntanis
88c75ba808
Fixed "typo" in example.
Fixing code "typo" in example.
In the original file, line 145 reads:
        url(r'^api-auth/', include('rest_framework.urls'),
It's missing the closing parenthesis.
2017-12-28 02:01:01 -08:00
Xavier Ordoquy
991868a897
Merge pull request #5711 from mbaragiola/master
Update writable nested serializers status
2017-12-27 14:33:25 +01:00
Mariano Baragiola
be0a57b0f1 FIX link 2017-12-27 10:28:59 -03:00
Mariano Baragiola
6ce60cd594 Update writable nested serializers docs 2017-12-27 10:17:10 -03:00
Ryan P Kilby
5fc35eb7eb Add missing word in 'Field.allow_null' docs 2017-12-22 12:23:07 -05:00
Bruno Alla
832267e945 Fix formatting of the 3.7.4 release note (#5704) 2017-12-22 08:28:35 +01:00
Xavier Ordoquy
6602171184
Merge pull request #5698 from encode/release/3_7_7
3.7.7 Release
2017-12-21 13:01:03 +01:00
Xavier Ordoquy
955a6b902b Add 3.7.7 release notes 2017-12-21 12:45:54 +01:00
Xavier Ordoquy
9ec3e5f965
Merge pull request #5697 from providenz/master
Fix typo to bring back locale files to installed files
2017-12-21 12:26:56 +01:00
Laurent Paoletti
67964a1bf4 Fix typo to bring locale back to installed files 2017-12-21 12:12:08 +01:00
Tom Christie
65791d8c79 Version 3.7.5. Add missing .ico to packaging. 2017-12-21 10:17:59 +00:00
Tom Christie
0d96be9266 Add 3.7.5 release notes 2017-12-21 10:13:18 +00:00
Tom Christie
3a22b1d1f0 Version 3.7.5 2017-12-21 10:03:41 +00:00
Tom Christie
df469260e1 Include woff2 in packaging. Closes #5692 2017-12-21 10:03:03 +00:00
Matthias Runge
37cfe90338 Add locale files back to installed files (#5696)
Resolves https://github.com/encode/django-rest-framework/issues/5695
2017-12-21 10:00:43 +00:00
Xavier Ordoquy
d903896d3d
Merge pull request #5693 from felixxm/django-2.0
Bumped Django 2.0 version in requirements list.
2017-12-21 06:54:19 +01:00
Mariusz Felisiak
5e21bf852b
Bumped Django 2.0 version in requirements list. 2017-12-20 21:27:22 +01:00
Carlton Gibson
a81e60ff39
Version 3.7.4 Release (#5650)
* Update version for 3.7.4 Release

* Add release notes to 01587b9eb1

* Django 2.0 is now final.

* Add trove classifer for Django 2.0

* Finalise release notes for v3.7.4

* Set release date: December 20, 2017

* Update Transifex

* Add release note for #5691

* Move Issue links to bottom
2017-12-20 15:28:31 +01:00
Cristi Vîjdea
6de12e574e Fix format_suffix_patterns behavior with Django 2 path() routes (#5691)
* Add failing test for #5672

* Add get_original_route to complement get_regex_pattern

* [WIP] Fix path handling

* needs more tests
* maybe needs some refactoring

* Add django 2 variant for all tests and fix trailing slash bug

* Add more combinations to mixed path test
2017-12-20 13:17:54 +01:00
Carlton Gibson
cf3929d88d
Add example using source=‘*’ to custom field docs. (#5688)
* Add example using `source=‘*’` to custom field docs.
* Add nested serialiser example

Closes #2032 closes #3066
2017-12-20 10:04:12 +01:00
Tilmann Becker
d38b94fd74 Fix URL pattern parsing in schema generation (#5689)
* Fix url parsing in schema generation

- Call `str(pattern)` to get non-escaped route
- Strip converters from path to comply with uritemplate format. 
   Background: https://github.com/encode/django-rest-framework/issues/5675#issuecomment-352829363

Fixes #5675
2017-12-20 09:10:28 +01:00
Jimmy Merrild Krag
ea0b3b32ad Fix typo (#5687)
Fixed `include_docs_url` to be `include_docs_urls`
2017-12-19 15:03:47 +01:00
Carlton Gibson
4bcbf691cf
Document ViewSet.action (#5685)
Closes #2941

Provides example of adjusting permission by action.
2017-12-19 12:06:57 +01:00
Carlton Gibson
e87fcbb99d
Add link to Classy DRF in docs (#5683)
Closes #5636 as per https://github.com/encode/django-rest-framework/issues/5636#issuecomment-348143281
2017-12-19 12:06:41 +01:00
Carlton Gibson
b3a0b271cd
Add example to to_representation docs (#5682)
Closes #5425 as per https://github.com/encode/django-rest-framework/issues/5425#issuecomment-341063819
2017-12-19 12:06:24 +01:00
Carlton Gibson
43c2c91dde
Add note on object permissions for FBVs (#5681)
Closes #3269
2017-12-19 12:05:59 +01:00
Carlton Gibson
6560f44912
Update OPTIONS example from “Documenting Your API” (#5680)
Closes #3489

* Updates example to post-3.0 API, using metadata class
* Adds link to metadata docs.
2017-12-19 12:05:46 +01:00
Carlton Gibson
cc25f57f7b
Add UNAUTHENTICATED_USER = None note (#5679)
When removing authentication entirely you cannot import `django.contrib.auth.models.AnonymousUser`

Closes #3494
2017-12-19 10:31:20 +01:00
Pavlin Gergov
21a9740156 Fix typo in docstring (#5678) 2017-12-19 08:45:33 +01:00
Ryan P Kilby
d12005cf90 Add 'dist' build (#5656) 2017-12-14 11:48:03 +01:00
Carlton Gibson
2359d3981b
Add docs note re generated BooleanField being required=False (#5665)
* Note that BooleanField default is required=False

Closes #5664
2017-12-14 11:39:54 +01:00
Carlton Gibson
791539acec
Add DEFAULT_SCHEMA_CLASS setting (#5658)
* Add test for new setting

* Add DefaultSchema utility

* Add new setting to docs
2017-12-14 11:24:21 +01:00
Carlton Gibson
4a200d5e66
Fix override_settings compat (#5668)
* Add test checking override_settings compat

* Refresh APISettings, rather than replace

Fix suggested by @daggaz https://github.com/encode/django-rest-framework/issues/2466#issuecomment-344297213
2017-12-14 10:33:48 +01:00
Anna Ossowski
1692feb535
Updated monthly report link 2017-12-06 03:10:41 +01:00
Hang Park
01587b9eb1 Typos in serializers documentation (#5652)
Fixes #5651.

Change `update()` to `.update()` in serializers documentation to get a
consistency with `.create()`.
2017-12-04 07:00:03 -05:00
Ryan P Kilby
7855d3bd8b Add '.basename' and '.reverse_action()' to ViewSet (#5648)
* Router sets 'basename' on ViewSet

* Add 'ViewSet.reverse_action()' method

* Test router setting initkwargs
2017-12-04 11:55:49 +01:00
Carlton Gibson
c7df69ab77
Note AutoSchema limitations on bare APIView (#5649)
AutoSchema uses GenericAPIView hooks to introspect. If these are not present it’s results will be limited. Note this.

Closes #5121
2017-12-04 10:52:59 +01:00
Carlton Gibson
a0cdba6277
Extract method for manual_fields processing (#5633)
* Extract method for `manual_fields` processing

Allows reuse of logic to replace Field instances in a field list by `Field.name`.

Adds a utility function for the logic plus a wrapper method on `AutoSchema`.

Closes #5632

* Manual fields suggestions (#2)

* Use OrderedDict in inspectors

* Move empty check to 'update_fields()'

* Make 'update_fields()' an AutoSchema staticmethod

* Add 'AutoSchema.get_manual_fields()'

* Conform '.get_manual_fields()' to other methods

* Add test for update_fields

* Make sure `manual_fields` is a list.

(As documented to be)

* Add docs for new AutoSchema methods.

* `get_manual_fields`
* `update_fields`

* Add release notes for PR.
2017-12-04 09:07:43 +01:00
Ryan P Kilby
daba5e9ba5 Fix Serializer.data when provided invalid 'data' (#5646)
* Test serializer/API renderer for invalid datatype

* Fix Serializer.data with invalid input datatype
2017-12-04 08:39:55 +01:00
Xavier Ordoquy
b01ec450b2
Merge pull request #5645 from jdufresne/dj20
Update to use the Django 2.0 release in tox.ini
2017-12-03 22:04:38 +01:00
Jon Dufresne
101d3d24f7 Update to use the Django 2.0 release in tox.ini
Was previously using a release candidate as the minimum version.
2017-12-03 10:35:34 -08:00
Ryan P Kilby
5f42cb7027 Add allow_null serialization output note (#5641) 2017-12-01 10:07:33 +01:00
Rômulo Oliveira
905a5579df Non-required fields with 'allow_null=True' should not imply a default value (#5639)
Ref #5518.
2017-12-01 09:54:25 +01:00
Carlton Gibson
97f7a82b37 Correct typos
Closes #5634
2017-11-28 16:46:34 +01:00
José Padilla
743fc247eb Update tutorial (#5622)
* Use createsuperuser email and username flags

* Only remove db.sqlite3

* Remove global permission class

This interferes with Core API schema endpoint

* Add default pagination class

* Specify changes made in snippets/urls.py

* Auth urls were already set in tutorial/urls.py

* Specify changes made in snippets/urls.py

* Use the suggested admin username from quickstart

* Move global pagination setting away from quickstart section
2017-11-27 11:34:17 +01:00
Ryan P Kilby
fc6b192b70 Fix readme, add to CI (#5625)
* Add readme build to CI

* Fix pandoc import in setup.py

* Replace sponsor HTML with markdown

This loses the image centering, but can be converted to RST.

* Fix README RST conversion

- Links do not render correctly inside italics
- Add hr between image caption and section, fixes markup on older
  versions of pandoc.
2017-11-27 11:32:17 +01:00
Ryan P Kilby
abef84fb60 Fix packaging (#5624)
* Packaging should use manifest

* Add schema.js template to MANIFEST
2017-11-27 11:28:25 +01:00
Xavier Ordoquy
fc94fbd4e8
Merge pull request #5629 from akshar-raaj/fix_serializer_get_fields_documentation
Serializer._declared_fields enable modifying fields on a serializer
2017-11-27 10:27:26 +01:00
Akshar Raaj
224d8cfb9d Serializer._declared_fields enable modifying fields on a serializer
instance without affecting every other serializer instance.
2017-11-27 13:38:18 +05:30
Xavier Ordoquy
c782376555
Merge pull request #5626 from rpkilby/update-reqs
Update test requirements
2017-11-26 12:03:41 +01:00
Ryan P Kilby
ddcb77be01 Add _pytest to .isort.cfg 2017-11-25 21:19:55 -05:00
Ryan P Kilby
5c19652080 Fix whitespace in imports 2017-11-25 21:10:30 -05:00
Ryan P Kilby
7b58a2c124 Fix bare except statements 2017-11-25 21:06:13 -05:00
Ryan P Kilby
eb61eb2b86 Update testing requirements 2017-11-25 21:04:07 -05:00
Ryan P Kilby
c63e35cb09 Fix AttributeError hiding on request authenticators (#5600)
* Update assertion style in user logout test

* Apply middlewares to django request object

* Fix test for request auth hiding AttributeErrors

* Re-raise/wrap auth attribute errors

* Fix test for py2k

* Add docs for WrappedAttributeError
2017-11-23 08:58:04 +01:00
Ryan P Kilby
a91361dd2f Perform type check on passed request argument (#5618)
* Add test for wrapped request instance

* Add 'request' argument type check to Request init

* Fix metadata tests' request object
2017-11-23 08:57:31 +01:00
Xavier Ordoquy
c2c9225782
Merge pull request #5619 from rpkilby/explicit-django20-support
Update Django 2.0 support
2017-11-23 07:12:04 +01:00
Ryan P Kilby
7a533cd8b8 Update README 2017-11-22 23:21:00 -05:00
Ryan P Kilby
bc28b0c74f Remove django 2.0 from allowable failures in CI 2017-11-22 23:16:27 -05:00
Ryan P Kilby
1922dc6e73 Update Django to 2.0rc1 2017-11-22 23:16:07 -05:00
Sander Steffann
d71bd57b64 SchemaJSRenderer renders invalid Javascript (#5607)
* SchemaJSRenderer renders invalid Javascript

Under Py3 the base64.b64encode() method returns a binary object, which gets rendered as `b'...'` in schema.js. This results in the output becoming:

    var coreJSON = window.atob('b'eyJf...'');

which is invalid Javascript. Because base64 only uses ASCII characters it is safe to decode('ascii') it. Under Py2 this will result in a unicode object, which is fine. Under Py3 it results in a string, which is also fine. This solves the problem and results in a working schema.js output.

* Add regression test for #5608

* Add regression test for #5608

* Apparently the linter on Travis wants the imports in a different order than on my box...
2017-11-22 15:47:03 +01:00
Ryan P Kilby
1a667f420d Reimplement request attribute access w/ __getattr__ (#5617)
* Add tests for proxying WSGIRequest attributes in Request.

* Add request attribute exception test

* Reimplement request attribute access
2017-11-22 11:42:59 +01:00
Ryan P Kilby
ae88f5c55b Minor cleanup for ModelSerializer tests (#5598)
* Replace assertRaises with assertRaisesMessage

* Remove outdated implicit Meta.fields test

* Simplify parent declared field test
2017-11-22 10:36:34 +01:00
Michał Bielawski
134a6f66f9 Fixed schema generation for filter backends (#5613) 2017-11-22 00:11:59 -05:00
Ryan P Kilby
a3df1c1199 Test Serializer exclude for declared fields (#5599)
* Test current behavior of exclude+declared field

* Assert declared fields are not present in exclude
2017-11-20 09:51:16 +01:00
Jon Dufresne
ff556a91fd Remove references to unsupported Django versions in docs and code (#5602)
Per the trove classifiers, DRF only supports Django versions 1.10+. Can
drop documentation, code comments, and workarounds for older Django
versions.
2017-11-20 09:35:54 +01:00
bartkim0426
9c11077cf6 Fix in documentation (#5612)
- typo in serialization document: 'intead' => 'instead'
2017-11-20 09:08:16 +01:00
Alexei Znamensky
20954469b2 Fix in documentation (#5611)
- model serializers now must provide either "fields" or "exclude" as attribute
2017-11-20 09:07:36 +01:00
Ryan P Kilby
2531998427 Rename test to reference correct issue (#5610) 2017-11-20 08:58:29 +01:00
Ryan P Kilby
9f66e8badd Fix request body/POST access (#5590)
* Modernize middleware tests

* Added a failing test for #5582

* Set data ref on underlying django request
2017-11-15 20:58:37 +01:00
Ryan P Kilby
15024f3f07 Remove set_rollback() from compat (#5591)
* Remove Django 1.6 transaction compat

* Move set_rollback from compat => views
2017-11-14 09:55:59 +01:00
Éric Araujo
265375c104 add missing template change for #5584 (#5587) 2017-11-11 08:43:00 +01:00
Anna Ossowski
c33d0069da
Updated monthly report link + added 3.7 info 2017-11-10 19:27:26 +01:00
Éric Araujo
57ad208dc6 add pygments CSS block in browsable API views (#5584) 2017-11-10 09:42:21 +01:00
Ryan P Kilby
8d7ce3726d Compat cleanup (#5581)
* Reenable flake8 on compat, cleanup style/imports

* Cleanup compat urls imports

* Refactor compat url pattern/resolver imports

* Add comment re dropping pytz compat

... when dropping Django 1.10

* Strip whitespace

Grrr. GitHub web editor 😡
2017-11-10 09:41:03 +01:00
Jon Dufresne
f9c67f04d4 Clean up all whitespace throughout project (#5578)
* Remove trailing whitespace from lines
* Remove trailing nad leading whitespace from files

Allows for cleaner diffs in future changes. For editors that
automatically clean up whitespace on save, will avoid unrelated line
changes in diffs.
2017-11-09 20:57:53 +01:00
Jon Dufresne
f8e8381c00 Drop compat wrapper for TimeDelta.total_seconds() (#5577)
TimeDelta.total_seconds() was introduced in Python 2.7 and 3.2. It is
available on all supported Python versions.

https://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds
https://docs.python.org/3/library/datetime.html#datetime.timedelta.total_seconds
2017-11-09 09:03:48 +01:00
Xavier Ordoquy
9234ac576e
Merge pull request #5579 from jdufresne/urllib
Remove ulrparse compatability shim; use six instead
2017-11-09 08:30:17 +01:00
Jon Dufresne
ea81000160 Remove ulrparse compatability shim; use six instead
The urlparse shim in compat.py duplicates Django's bundled six. Can rely
on upstream instead of duplicating their works. Unifies shim with other
files already using six.
2017-11-08 21:30:33 -08:00
Carlton Gibson
0f33e63e10
Update version and release notes for v3.7.3 (#5568) 2017-11-06 16:32:12 +01:00
Xavier Ordoquy
71a512b2d9
Merge pull request #5567 from rpkilby/importable
Add rest_framework.compat import test
2017-11-06 16:16:40 +01:00
Xavier Ordoquy
d6a8e02021 Move django.contrib.auth import out of compat.
Fixed some regressions where compat was imported during app loading and
led to importing django.contrib.auth.models which ended in a
`AppRegistryNotReady` exception.
2017-11-06 09:57:51 -05:00
Ryan P Kilby
ca341ef705 Add compat import test 2017-11-06 09:56:57 -05:00
Xavier Ordoquy
7d0fa02dc0 Revert "Move django.contrib.auth import out of compat."
This reverts commit d4d9cc1d53.
2017-11-06 15:23:54 +01:00
Xavier Ordoquy
d4d9cc1d53 Move django.contrib.auth import out of compat.
Fixed some regressions where compat was imported during app loading and
led to importing django.contrib.auth.models which ended in a
`AppRegistryNotReady` exception.
2017-11-06 15:06:47 +01:00
Carlton Gibson
3dc40f9572
Version 3.7.2 Release (#5563)
* Begin release notes for 3.7.2

* Add release notes fro merged issues.

* Finalise release notes

* Increment version number to 3.7.2

* Update translations
2017-11-06 12:05:08 +01:00
Yuri Nikulin
7a278b3540 fix processing unicode symbols in query_string by Python 2 (#5552)
* fix processing unicode symbols in query_string by Python 2

* Add comments for encoded test strings.

* Add file encoding for Python 2.
2017-11-06 11:46:37 +01:00
Sergei Azarkin
d49d796c85 Change ImageField validation pattern, use validators from DjangoImageField (#5539) 2017-11-06 11:14:37 +01:00
Jon Dufresne
0552810410 Use dict and set literals instead of calls to dict() and set() (#5559)
Set literals are available on all supported Python versions. They are
idiomatic and always faster:

$ python3 -m timeit '{}'
10000000 loops, best of 3: 0.0357 usec per loop
$ python3 -m timeit 'dict()'
10000000 loops, best of 3: 0.104 usec per loop

$ python3 -m timeit '{1, 2, 3}'
10000000 loops, best of 3: 0.0754 usec per loop
$ python3 -m timeit 'set([1, 2, 3])'
1000000 loops, best of 3: 0.228 usec per loop
2017-11-06 10:03:01 +01:00
Jon Dufresne
f77e794dc8 Fix all BytesWarning caught during tests (#5561)
Running the tests with bytes warning enabled shows some bytes/str
mixups. Fix them all.

Some examples of mixing usage:

str(b'foo') -- calling str() on bytes
b'foo' == 'foo' -- compare str with bytes
'foo' + b'bar' -- concatenating str and bytes
2017-11-06 10:02:48 +01:00
Carlton Gibson
331c31370f
Add rounding parameter to DecimalField (#5562)
* Adding rounding parameter to DecimalField.

* Using standard `assert` instead of `self.fail()`.

* add testcase and PEP8 multilines fix

* flake8 fixes

* Use decimal module constants in tests.

* Add docs note for `rounding` parameter.
2017-11-06 09:55:09 +01:00
Carlton Gibson
565c722762
Add interactive docs error template (#5548) 2017-11-06 09:04:07 +01:00
Xavier Ordoquy
e5cee43000
Merge pull request #5560 from jdufresne/escape-seq
Fix invalid escape sequence deprecation warnings
2017-11-06 08:20:35 +01:00
Jon Dufresne
44823b0e1d Fix invalid escape sequence deprecation warnings
When running tests with warnings enabled, appear as:

  DeprecationWarning: invalid escape sequence \d

Starting with Python 3.6, invalid escape sequences are deprecated. In a
future Python versions they will be a syntax error. For more details, see:

https://docs.python.org/3/whatsnew/3.6.html#deprecated-python-behavior

> A backslash-character pair that is not a valid escape sequence now
> generates a DeprecationWarning. Although this will eventually become a
> SyntaxError, that will not be for several Python releases.
2017-11-05 10:09:38 -08:00
Xavier Ordoquy
5f9faab769
Merge pull request #5557 from jdufresne/bdist
Rename [wheel] section to [bdist_wheel] as the former is legacy
2017-11-04 10:07:21 +01:00
Xavier Ordoquy
eb32c97ca7
Merge pull request #5556 from jdufresne/cache
Add pip cache support to the Travis CI configuration
2017-11-04 09:55:56 +01:00
Xavier Ordoquy
5455771cc6
Merge pull request #5555 from jdufresne/trove
Add trove classifier for Python 3.6 support.
2017-11-04 09:49:20 +01:00
Jon Dufresne
da266fb864 Rename [wheel] section to [bdist_wheel] as the former is legacy
For additional details, see:

54ddbcc9ce/wheel/bdist_wheel.py (bdist_wheel.py-119):125

http://pythonwheels.com/
2017-11-03 17:40:14 -07:00
Jon Dufresne
18180c9fc6 Add pip cache support to the Travis CI configuration
For documentation on the feature, see:

https://docs.travis-ci.com/user/caching/#pip-cache

With packages cached, builds will be slightly faster and help reduce
load on PyPI.
2017-11-03 16:08:34 -07:00
Jon Dufresne
64cfa3b64d Add trove classifier for Python 3.6 support.
Helps users know, at a glance, if the library is compatible with a
project.
2017-11-03 16:03:23 -07:00
Xavier Ordoquy
526bdacc54
Merge pull request #5553 from adrienbrunet/patch-1
Update link to documentation
2017-11-03 17:30:49 +01:00
Adrien Brunet
1575bd98d8
Update link to documentation
Previous link led to a maze. :/
2017-11-03 15:49:21 +01:00
Vasyl Dizhak
5d71d8d4b8 Increase test coverage for drf_create_token command (#5550) 2017-11-02 10:26:42 +01:00
Allisson Azevedo
3ddc22f708 Add djangorestframework-rapidjson to third party packages (#5549) 2017-11-02 10:19:33 +01:00
Stephen Chisholm
93e75ec138 Catch OverflowError for "out of range" datetimes (#5546)
* Add test for #5545 
* Catch OverflowError for "out of range" datetimes
2017-10-31 10:17:08 +01:00
Danilo Akamine
4249245123 Add import to example in api-guide/parsers (#5547) 2017-10-30 17:11:54 +01:00
Tom Christie
2b6245db53
Ensure Location header is strictly a 'str', not subclass. Closes #5541 (#5544) 2017-10-30 13:08:52 +00:00
Ryan P Kilby
5009aeff18 Fields with 'allow_null=True' should imply a default serialization value (#5518)
* Add test for dotted source + allow_null

* Field 'allow_null' implies 'default=None'

* Field 'allow_null' provides serialization default
2017-10-30 10:17:53 +01:00
Carlton Gibson
1f693c331e Fix dotted source ordering (#5533)
* replaced '.' for '__' in dotted ordering sources

* Add test for non-dotted source.
2017-10-25 11:46:21 +02:00
Carlton Gibson
7261ae653a Schema: Exclude OPTIONS/HEAD for ViewSet actions (#5532)
Closes #5528.

Viewset custom actions (@detail_route etc) OPTIONS (and HEAD) methods were not being excluded from Schema Generations.

This PR adds a test reproducing the reported error and adjusts `EndpointEnumerator.get_allowed_methods()` to filter ViewSet actions in the same way as other `APIView`s
2017-10-25 10:56:40 +02:00
Jamie Cockburn
efb047fa07 JSONField renders as textarea (#5529) (#5530) 2017-10-25 10:55:41 +02:00
Jamie Cockburn
91fa8b923a Stop JSONBoundField mangling invalid JSON (#5526) (#5527) 2017-10-25 10:54:38 +02:00
Carlton Gibson
1c9ad52cb6 Clarify pagination system check (#5524)
* Add `id` to allow silencing.
* Expand `hint` to clarify.

Ref #5170 Closes #5523
2017-10-23 12:31:59 +02:00
andrewhannum
916a4a27ef Interactive docs - make bottom sidebar items sticky (#5516) 2017-10-23 12:02:04 +02:00
Xavier Ordoquy
f5e98efcf2 Merge pull request #5519 from bittner/patch-1
Make Travis CI include/exclude faster to read
2017-10-22 09:22:45 +02:00
Peter Bittner
e67605f707 Make Travis CI include/exclude faster to read 2017-10-21 08:32:47 +02:00
Matteo Nastasi
9ec81e32da substitute '@@' code block delimiter with triple backtick, more con… (#5513)
* substitute '@@' code block delimiter with triple back-tick,  more consistent with other markdown extensions

* remove development print and allow spaces between triple backtick and syntax name in codeblock

* update comparison content for markdown test
2017-10-20 11:39:29 +02:00
Jason Kraus
22a71a6322 include date and date-time format for swagger 2 schema generation (#5511) 2017-10-20 09:14:33 +02:00
Pratyush Mittal
f87699e2ca Adding examples and documentation for caching (#5514) 2017-10-20 09:10:09 +02:00
Dustin Wyatt
e704dd2e40 Add import for TextLexer. (#5512)
If pygments did not recognize the language name it was being passed,
this would raise a `NameError` because `TextLexer` import was missing.
2017-10-18 20:53:05 +02:00
Mariusz Felisiak
1a526c153e Fixed Django 2.1 compatibility due to removal of django.contrib.auth.login()/logout() views. (#5510) 2017-10-18 09:46:27 +02:00
Asif Saifuddin Auvi
320f10ad00 update tox to django 2.0 beta1 (#5507) 2017-10-17 08:58:09 +02:00
Carlton Gibson
80320ed615 Version 3.7.1 Release (#5505)
* Release notes for 3.7.1

* Update version to 3.7.1
2017-10-16 15:11:54 +02:00
Ryan P Kilby
6221124e0d Docs about default value for dotted source, additional tests (#5489)
* Add docs note on dotted source + default value

* Add additional dotted source tests
2017-10-16 11:33:46 +02:00
Marcin
5d7b6e5b2f Fixed issues with schema name collisions (#5486)
* Fixed issues with schema name collisions

* Fixed mutating issues in python 3

* Optimized solution

* Fixed isort

* Removed not needed cast

* Fix for key collision

* Added preferred key to preserve if available

* Add accidently removed test
2017-10-16 11:32:48 +02:00
Carlton Gibson
c7fb60bcd4 Django 2.0a1 compat (#5503)
* Update remaing `include` calls

Missed as part of #5481 cleanup.

* Provide app_name in include_docs_urls

* Update remaining get_regex_pattern usages

* Allow functools.partial in is_simple_callable check
2017-10-16 11:31:13 +02:00
Ryan P Kilby
cbfa444454 Fix HiddenField stripping in BrowsableAPIRenderer (#5499) 2017-10-16 09:35:53 +02:00
Maxim Kuznetsov
c91b081837 Support URLPattern and URLResolver from Django 2.0 (#5500)
* Support URLPattern and URLResolver from Django 2.0

* fix import order
2017-10-16 09:33:31 +02:00
Matthew Egan
e39d9337da Version 3.7 annoucement fix (#5501) 2017-10-15 21:51:55 +02:00
Tom Christie
bafbc60006 Update rollbar logo 2017-10-13 14:40:10 +01:00
Tom Christie
f3fe13f707 New logo (#5497) 2017-10-13 14:35:53 +01:00
Levi Payne
41188dfba0 Interactive documentation always uses false for boolean fields in requests (#5492) 2017-10-11 21:11:44 +02:00
Xavier Ordoquy
f585eee125 Remove duplicated line 2017-10-09 22:19:53 +02:00
Ed Morley
22565d9a65 Docs: Fix a few typos in the release notes and tutorial (#5483) 2017-10-06 15:46:42 +01:00
Carlton Gibson
eb3d078a2c Version 3.7: Announcement etc (#5437)
* Set version number for 3.7.0 release

* Rename release notes section

Moved issue links to top for easier access.
(Can move back later)

* Add release note for #5273

* Add release note for #5440

* Add release note for #5265

Strict JSON handling

* Add release note for #5250

* Add release notes for #5170

* Add release notes for #5443

* Add release notes for #5448

* Add release notes for #5452

* Add release not for #5342

* Add release notes for 5454

* Add release notes for #5058 & #5457

Remove Django 1.8 & 1.9 from README and setup.py

* Release notes for merged 3.6.5 milestone tickets

Tickets migrated to 3.7.0 milestone.

* Add release notes for #5469

* Add release notes from AM 2ndOct

* Add final changes to the release notes.

* Add date and milestone link

Move issue links back to bottom.

* Update translations from transifex

* Begin releae anouncement

* Add release note for #5482

* 3.7 release announcement & related docs.
2017-10-06 13:18:31 +02:00
Carlton Gibson
b2ca2c1911 Remove deprecated schema code from DefaultRouter (#5482) 2017-10-05 21:29:56 +02:00
Carlton Gibson
c674687782 Remove Django 1.8 & 1.9 compatibility code (#5481)
* Identify code that needs to be pulled out of/removed from compat.py

* Extract modern code from get_names_and_managers in compat.py and remove compat code

* Extract modern code from is_authenticated() in compat.py and remove.

* Extract modern code from is_anonymous() in compat.py and remove

* Extract modern code from get_related_model() from compat.py and remove

* Extract modern code from value_from_object() in compat.py and remove

* Update postgres compat

JSONField now always available.

* Remove DecimalValidator compat

* Remove get_remote_field compat

* Remove template_render compat

Plus isort.

* Remove set_many compat

* Remove include compat
2017-10-05 20:41:38 +02:00
Carlton Gibson
2edeb74e0e Have is_list_view recognise RetrieveModel… views (#5480)
Fixes #5165
2017-10-05 20:41:14 +02:00
Carlton Gibson
d8da6bb29b Update coreapi JS to 0.1.1 (#5479)
Ref #5059
2017-10-05 13:40:28 +02:00
Jascha Geerds
161dc2df2c Call Django's authenticate function with the request object (#5295)
As of Django 1.11 the `authenticate` function accepts a request as an
additional argument. This commit fixes compatibility between newer Django
versions and custom authentication backends which already depend on the request
object.

See also:

[Django 1.11 release](https://docs.djangoproject.com/en/1.11/releases/1.11/)

```
authenticate() now passes a request argument to the authenticate() method of
authentication backends. Support for methods that don’t accept request as the
first positional argument will be removed in Django 2.1.
```
2017-10-05 10:43:49 +01:00
Carlton Gibson
d138f30a86 Fix naming collisions in Schema Generation (#5464)
* Add failing tests for #4704

* Add generic view based test case.

* Adjust insert_into to raise ValueError
2017-10-05 11:06:09 +02:00
Carlton Gibson
2befa6c316 Document documentation.py (#5478)
Closes #5198. Closes #5142. Closes #4980
2017-10-04 12:12:06 +02:00
Jerome Leclanche
cc7f4f543f Fix missing six.text_type() call on APIException.__str__ (#5476)
Pull up method from subclass to superclass

The call was added in 426547c61c
to allow for dict-style arguments to ValidationError but does not
apply to other APIException descendants.
2017-10-04 09:00:21 +02:00
Tom Christie
5dcb460793 Update link to monthly report.
Closes #5474.
2017-10-03 12:15:52 +01:00
Ryan P Kilby
e0a6c4b5bd Clarify 'to_internal_value()' validation behavior (#5466) 2017-10-02 13:51:48 +01:00
Carlton Gibson
dc4a98fbe8 Fix documentation data rendering (#5472)
* Add failing test for #5395

* Add data filter for use in templates

Closes #5395

* Fix isort
2017-10-02 13:26:44 +02:00
Matteo Nastasi
063534ae50 Docstrings highlighting with pygments (#5462)
* add 'docstrings-with-pygments' feature without packages checks and tests

* move syntax_highlight doc filter in compatibility module and define it conditionally

* typo fixed

* add test for optional code highlight ('pygments' and 'markdown' packages must be installed)
2017-10-02 11:44:29 +02:00
Lim H
62ecbf2817 Add drf-openapi (#5470)
* Add DRF OpenAPI as a 3rd party tool for DRF doc

* Add image

* Add third party packages section to schema doc

* Add DRF OpenAPI reference
2017-10-02 11:16:33 +02:00
Shreyans Sheth
e6193cfd9e Added Response import in Code Snippet (#5468)
Added `from rest_framework.response import Response` in the viewset code snippet example
2017-10-02 09:04:55 +02:00
Matteo Nastasi
efc427dfc8 Reuse 'apply_markdown' function in 'render_markdown' templatetag func (#5469)
* reused 'apply_markdown' function in 'render_markdown' templatetag function

* typo fixed
2017-10-02 08:59:53 +02:00
Ryan P Kilby
018e43e908 Remove old django-filter templates (#5465) 2017-09-29 15:42:24 +01:00
Carlton Gibson
5c2290d973 Add note on not using floats with CursorPagination (#5459)
Closes #5160, closes #5164.
2017-09-27 12:23:54 +02:00
Thierry Bastian
760268ade2 Fixed a deprecation warning (#5058) 2017-09-27 10:51:45 +02:00
Carlton Gibson
296904099f Update test matrix: Add Django 2.0, drop 1.8 (#5457)
* Add Django 2.0 to tox/travis.

Updated requirements

* Drop Django 1.8 & 1.9
2017-09-27 10:29:48 +02:00
Carlton Gibson
b1c6ea1240 Adjust schema get_filter_fields rules to match framework (#5454)
Closes #5237

Generics/ModelViewset performs filtering on: list, retrieve, put, patch and destroy (plus method equivalents).

i.e. on list plus anything that calls `get_object`.

This PR makes schema generation follow that.

It adds `AutoSchema._allows_filters()` which can be overridden in subclasses.

I’ve made this initially “private” so we can make quick changes if needs be in a 3.7.1 etc.
2017-09-27 09:13:10 +02:00
Rokker Ruslan
ab7e5c4551 Added default value for 'detail' param into 'ValidationError' exception (#5342) 2017-09-26 10:24:30 +02:00
John Eskew
607e4edca7 Defer translated string evaluation on validators. (#5452)
* Customize validators to defer error string evaluation.

* Add docstring for `CustomValidatorMessage`
2017-09-26 10:02:20 +02:00
Ryan P Kilby
50acb9b2fe Fix warning in AutoSchema.get_serializer_fields() (#5451) 2017-09-25 21:09:54 +02:00
Sigve Sebastian Farstad
bf0fbd5df1 Catch APIException in doc generation (#5443)
The documentation generator calls view.get_serializer() in order to
inspect it for documentation generation. However, if get_serializer()
throws an APIException (e.g. PermissionDenied), it doesn't get caught at
the call site, but instead propagates up and aborts the entire view.
With the try/except in this commit, the documentation generator instead
gratiously ignores that particular view and moves on to the next one
instead. Practical concequences of this commit is that the docs no
longer break if any view's get_serializer(..) throws an APIException.
2017-09-25 18:28:36 +02:00
Carlton Gibson
8812e6c47a Merge pull request #5448 from carltongibson/pr/5309-docs-view-custom-auth
Allow setting custom authentication and permissions on docs view.
2017-09-25 16:50:16 +02:00
Carlton Gibson
1bcee8c60c Document extra parameters to get_schema_view 2017-09-25 16:25:40 +02:00
Katharyn Garcia
5333565fe6 allow custom authentication and permission classes for docs view 2017-09-25 16:17:25 +02:00
Matt Davis
107e8b3d23 Make DEFAULT_PAGINATION_CLASS None by default. (#5170)
* Changes to the paginator defaults and settings

Require a default paginator be specified when using the page size
setting.
https://github.com/encode/django-rest-framework/issues/5168

* DRF-5168 import warnings

missed this in last commit

* Add a system checks file

Add a check for pagination settings for the 3.7 upgrade cycle.

* more compatible import approach

* missing bactic

* revised language and approach to import the system check

Adds a rest framework app config.

* Adjust doc wording
2017-09-25 15:36:30 +02:00
Paolo Melchiorre
11e5851196 Update pagination.md
Fixed 2 missing spaces in Custom Pagination snippet
2017-09-25 11:30:21 +02:00
Kris Dorosz
60b9e58a12 Add support for page_size parameter in CursorPaginator class 2017-09-25 11:25:51 +02:00
Carlton Gibson
aecca9d8e8 Add note on force_authenticate + refresh_from_db
…in case you’re reusing the same in-memory user whilst updating it in the DB.

Closes #5016, closes #5066, closes #4102
2017-09-25 11:14:36 +02:00
Carlton Gibson
e29ad1e7b3 JSONEncoder: Don’t strip microseconds from time
Closes #4749.

This is the matching commit to the fix for `datetime` in #4256
2017-09-25 10:10:44 +02:00
Ryan P Kilby
ea894cd90a Add docstring to json wrapper module 2017-09-25 09:08:20 +02:00
Ryan P Kilby
215248c042 Add 'STRICT_JSON' docs 2017-09-25 09:08:20 +02:00
Ryan P Kilby
c98223f231 Pass on invalid value (Inf, NaN) encoding in JSONBoundField 2017-09-25 09:08:20 +02:00
Ryan P Kilby
901657e7e8 Add banned imports to prevent standard json import 2017-09-25 09:08:20 +02:00
Ryan P Kilby
8ab75a2f01 Add 'STRICT_JSON' API setting.
STRICT_JSON controls the renderer & parser behavior on whether or not
to accept non-standard float values (NaN, Infinity).
2017-09-25 09:08:20 +02:00
Ryan P Kilby
d740bae95a Update json imports 2017-09-25 09:08:20 +02:00
Ryan P Kilby
b64f8066c0 Add json util wrapper, failing JSONField test 2017-09-25 09:08:20 +02:00
Ryan P Kilby
f6c19e5eac Remove DjangoFilterBackend and associated tests 2017-09-20 16:47:54 +02:00
Carlton Gibson
cb6e7e0fdd Drop erroneous ) in release notes 2017-09-20 14:23:51 +02:00
Carlton Gibson
7d6d043531 Fix DateTimeField TZ handling (#5435)
* Add failing TZ tests for DateTimeField

- tests "current" timezone activation
- tests output for non-UTC timezones

* Update DateTimeField TZ aware/naive test output

* Fix DateTimeField TZ handling

* Add Release Note for BC change
2017-09-20 12:15:15 +02:00
Xavier Ordoquy
89daaf6276 Add the project layout to the quickstart to have a milestone for the project creation. (#5434) 2017-09-20 12:05:04 +02:00
Jeremy Nauta
c0a48622e1 Allow ChoiceField.choices to be set dynamically (#5426)
## Description

The `choices` field for the `ChoiceField` class should be able to be edited after `ChoiceField.__init__` is called.

```
field = ChoiceField(choices=[1,2])
field.choices = [1]  # Should no longer allow `2` as a choice
```

Currently, you must update `choices`, `grouped_choices`, and `choice_strings_to_values` to achieve this. This P/R keeps `grouped_choices` and `choice_strings_to_values` in sync whenever the `choices` are edited.
2017-09-20 11:33:50 +02:00
Carlton Gibson
7b1582e00e Allow schema = None. Deprecate exclude_from_schema (#5422)
* Add tests for schema exclusions

* Move exclusion check to should_include_endpoint

* Update docs

* Switch to using `schema = None`

* Test PendingDeprecationWarnings

* Add note to release notes.

* s/deprecated/pending deprecation/

* Add PR link to release notes

* Correct typo in test class name

* Test 'exclude_from_schema' deprecation warning message (#1)

* Correct deprecation warning message
2017-09-20 11:29:47 +02:00
Carlton Gibson
efff9ff338 5378 fix schema generation markdown (#5421)
* Test case for #5240
* Remove unnecessary strip()  from get_description

Closes #5240

* Adjust test case
2017-09-14 12:20:41 +01:00
Carlton Gibson
d54df8c438 Refactor schema generation to allow per-view customisation (#5354)
* Initial Refactor Step

* Add descriptor class
* call from generator
* proxy back to generator for implementation.

* Move `get_link` to descriptor

* Move `get_description` to descriptor

* Remove need for generator in get_description

* Move get_path_fields to descriptor

* Move `get_serializer_fields` to descriptor

* Move `get_pagination_fields` to descriptor

* Move `get_filter_fields` to descriptor

* Move `get_encoding` to descriptor.

* Pass just `url` from SchemaGenerator to descriptor

* Make `view` a property

Encapsulates check for a view instance.

* Adjust API Reference docs

* Add `ManualSchema` class

* Refactor to `ViewInspector` plus `AutoSchema`

The interface then is **just** `get_link()`

* Add `manual_fields` kwarg to AutoSchema

* Add schema decorator for FBVs

* Adjust comments

* Docs: Provide full params in example

Ref feedback b52e372f8f (r137254795)

* Add docstring for ViewInstpector.__get__ descriptor method.

Ref https://github.com/encode/django-rest-framework/pull/5354#discussion_r137265022

* Make `schemas` a package.

* Split generators, inspectors, views.

* Adjust imports

* Rename to EndpointEnumerator

* Adjust ManualSchema to take `fields`

… and `description`.

Allows `url` and `action` to remain dynamic

* Add package/module docstrings
2017-09-14 09:46:34 +01:00
Tom Christie
5ea810d526 Drop unnecessary TODO notes. 2017-09-14 09:44:59 +01:00
Sergei Azarkin
9aaea2586b Fix authtoken managment command (#5415)
* Fix authtoken managment command username param
2017-09-12 14:03:29 +01:00
Jozef
7037ce88e9 Fix throttling documentation about Remote-Addr (#5414)
Clarify in docs that REMOTE_ADDR is part of the WSGI environ, not an HTTP header.
2017-09-12 12:08:32 +01:00
Carlton Gibson
a560a49d56 Merge pull request #5409 from rpkilby/fieldvalues-output
Add value repr to the assertion output in FieldValues tests
2017-09-11 17:34:02 +02:00
Ryan P Kilby
ae95ed1ec2 Add repr(value) to the assert msg in FieldValues 2017-09-11 05:18:39 -04:00
Sanjuro Jogdeo
0e341c24b4 Update get_object() example in permissions.md (#5401)
* Update get_object() example in permissions.md 

I'm a bit confused about the example that's provided in the 'Object level permissions' section.  Other examples (e.g. Tutorial 3 - Class Based Views) provided a pk to get_object().  It doesn't seem like this example has any way of identifying a specific object.  

Just in case I'm correct, I've prepared this pull request. But if I'm wrong, would it be possible for you to explain the example I modified?  

Many Thanks...

* Adjust patch
2017-09-08 18:51:16 +02:00
ersel-ionova
13222e45bc Make status_code documentation more readable. (#5400)
* Make status_code documentation more readable.

* Update status-codes.md
2017-09-08 16:53:17 +01:00
Carlton Gibson
e2b5cef52c Merge pull request #5398 from dolphinigle/master
Fixed the MultipleFieldLookupMixin example to properly check for object level permission
2017-09-07 07:45:58 +02:00
Irvan
b11f37eaf3 Fixed the MultipleFieldLookupMixin example to properly check for object level permission. 2017-09-07 11:06:44 +08:00
Carlton Gibson
71ad99e0b2 Merge pull request #5388 from founders4schools/fix/named-source
Fix ModelSerializer custom named fields with source on model
2017-09-04 17:24:36 +02:00
jhg14
66b2c6149e Fix code style 2017-09-04 16:17:43 +01:00
jhg14
4345894445 Add simplest possible failing test 2017-09-04 15:44:10 +01:00
jhg14
3c1bf6bfd5 Add failing test for named attribute
Fix test crudely

Remove comment
2017-09-04 15:44:04 +01:00
Igor Tokarev
79be20a7c6 Updated supported values for the NullBooleanField (#5387)
* Updated supported values for the NullBooleanField.
* Added check for unhashable types in NullBooleanField.
2017-09-04 10:11:53 +01:00
Daniele Varrazzo
e42eb42d49 Don't make the content mandatory in the generic content form (#5372)
Sometimes, probably in the upgrade from Django 1.9 to 1.10, a post with
empty content is forbidden by javascript, with the message "Please fill
in this field". Filling the form with '{}' allows an application/json
request to be submitted.

The API call itself works perfectly well with a post with empty content:
the interface shouldn't make assumptions about it.
2017-09-04 10:04:48 +01:00
Carlton Gibson
7cd59147ea Merge pull request #5376 from rpkilby/django-perms-queryset
DjangoModelPermissions should perform auth check before accessing the view's queryset
2017-09-04 08:24:40 +02:00
Ryan P Kilby
23b2d8099b Unify QS handling for model/object permissions 2017-09-01 13:56:39 -04:00
Ryan P Kilby
af460d2b69 Add PR 5376 to release notes 2017-09-01 13:37:06 -04:00
Carlton Gibson
139c8fe3d1 Merge pull request #5380 from blueyed/fix-doc
Fix doc for ErrorDetail
2017-09-01 12:39:55 +02:00
Carlton Gibson
dedd9c3863 Merge pull request #5381 from rpkilby/fix-test-name
Fix test name
2017-09-01 12:39:31 +02:00
Ryan P Kilby
bc49746dd3 Fix test name 2017-08-31 08:26:14 -04:00
Daniel Hahler
fff3db5517 Fix doc for ErrorDetail 2017-08-31 12:19:03 +02:00
Carlton Gibson
27c382c98d Merge pull request #5351 from rpkilby/requestfactory-contenttype
Unexpected result when passing empty body to RequestFactory
2017-08-31 12:13:49 +02:00
Ryan P Kilby
0ec915e623 Force content_type inclusion in APIRequestFactory 2017-08-31 05:45:12 -04:00
Carlton Gibson
bafb3ec22a Merge pull request #5375 from rpkilby/related-source-serialization
Fix default value handling for dotted sources
2017-08-31 08:52:32 +02:00
Ryan P Kilby
07258ca032 Remove None handling from fields.get_attribute() 2017-08-30 17:42:12 -04:00
Denis Untevskiy
c8773671e7 + Rejecting anonymous in DjangoModelPermissions *before* the .get_queryset call 2017-08-30 17:10:39 -04:00
Ryan P Kilby
2ea368e80f Add failing test for #5367 2017-08-30 16:53:08 -04:00
Ryan P Kilby
79c1f2154a Fix authorization few perms tests 2017-08-30 16:52:38 -04:00
Ryan P Kilby
94e5d05caa Add failing test for #5371 2017-08-30 14:06:43 -04:00
Carlton Gibson
7e3ba8b3ed Merge pull request #5373 from kiss90benedek/patch-1
Fix pyc/pycache excludes from manifest
2017-08-30 07:25:31 +02:00
Benedek Kiss
ff2fa7a866 Fix excludes
I definitely see files from `__pycache__` as well as `.pyc` files in the package. Fixed according to https://www.reddit.com/r/Python/comments/40s8qw/simplify_your_manifestin_commands and https://github.com/django/django/pull/5817
2017-08-29 22:22:00 +02:00
Carlton Gibson
1c5710bf6c Merge pull request #5369 from beda-software/master
Update link to drf-writable-nested repository in third-party serializers
2017-08-29 07:22:21 +02:00
Vadim Laletin
c0475d059d Update link to drf-writable-nested repository in third-party serializers 2017-08-29 10:39:52 +07:00
Xavier Ordoquy
1c4d277f53 Merge pull request #5362 from ashishnitinpatil/master
~api-clients documentation: installation code fix
2017-08-24 13:16:14 +02:00
Ashish Patil
26d4977cd0 ~api-clients documentation: installation code fix 2017-08-24 15:06:48 +04:00
Carlton Gibson
36cc8df85a Merge pull request #5361 from ScottKelly/response-data-doc-fix
Fix doc Response data attribute description
2017-08-24 09:45:35 +02:00
Scott Kelly
807b9c716c Fix doc Response data attribute description 2017-08-23 21:30:56 -05:00
Carlton Gibson
08ec276850 Merge pull request #5348 from fbidu/4585
Adding a more explicit error message when a view does have a get_queryset method but it returned nothing
2017-08-22 21:09:11 +02:00
Carlton Gibson
698d8b7507 Merge pull request #5350 from qwhex/patch-1
Update 2-requests-and-responses.md: consistency
2017-08-22 21:07:58 +02:00
Ryan P Kilby
eb88687e28 Test RequestFactory with empty body 2017-08-22 15:02:18 -04:00
Carlton Gibson
6a3b8cfa4c Adjust wording 2017-08-22 20:44:19 +02:00
qwhex
9b829bec2d Update 2-requests-and-responses.md: consistency
Made it consistent with Part I. Catched it when commiting the code into my local tutorial repo.
2017-08-22 20:37:31 +02:00
Felipe Bidu
6f2c3bcb12 Further clarifying the message when get_queryset returns None to include the class name that was called 2017-08-22 12:13:22 -03:00
Felipe Bidu
5fd01d06ab Adding a more explicit error message when a view does have a get_queryset method but it returned nothing 2017-08-22 11:00:19 -03:00
Carlton Gibson
fed85bc29d Merge pull request #5344 from carltongibson/3.6.4-release
Release notes etc for 3.6.4
2017-08-22 08:55:38 +02:00
Carlton Gibson
0a0bb6a871 Update release notes
For the last minute #5346
2017-08-21 20:33:51 +02:00
Carlton Gibson
0a8fa5219a Merge pull request #5346 from blueyed/docs-link-fix-undefined-schema
docs/link.html: fix/remove undefined template var "schema"
2017-08-21 20:29:01 +02:00
Daniel Hahler
e389336ad7 docs/link.html: fix/remove undefined template var "schema" 2017-08-21 14:47:43 +02:00
Carlton Gibson
1a7ed29639 Update version number 2017-08-21 12:06:14 +02:00
Carlton Gibson
d875fb3272 Update compiled translations. 2017-08-21 12:05:25 +02:00
Carlton Gibson
68d818fcc7 Update content from Transifex 2017-08-21 12:02:14 +02:00
Carlton Gibson
81527a2863 Release notes for 3.6.4 2017-08-21 11:50:00 +02:00
Carlton Gibson
d2286ba658 Merge pull request #5326 from limdauto/limdauto-patch-1
Fix introspection of list field in schema
2017-08-21 10:09:57 +02:00
Lim H
56021f9e77 Add tests for list field to schema 2017-08-20 17:12:56 +01:00
Carlton Gibson
4d5e846ca7 Merge pull request #5334 from Woile/woile-nested-docs-fix
Fix docs multiple nested and multiple methods
2017-08-18 11:05:06 +02:00
Carlton Gibson
4e08abb605 Merge pull request #5339 from kycool/master
Update fields.py
2017-08-18 09:11:59 +02:00
kycool
c868378c71 Update fields.py
modify to_choices_dict document
2017-08-18 12:12:01 +08:00
Woile
a1546cc266 [NEW] Tests for templatetags.schema_links 2017-08-17 21:14:26 +02:00
Woile
11bc1fe282 Fix JS data binding 2017-08-17 12:33:59 +02:00
Carlton Gibson
43c7af0bb5 Adjust ListField & DictField signature docs (#5333)
Closes #5301
2017-08-17 10:06:09 +01:00
Woile
ed38371c3a Fix docs multiple nested and multiple methods 2017-08-15 16:59:50 +02:00
Carlton Gibson
3110635685 Update JS constructor syntax (#5332)
Fixes #5247
2017-08-15 14:33:06 +01:00
Oliver Eidel
bf4b3ff0d5 Fix token param in force_authenticate example (#5284)
related_name for Token is `auth_token`, not `token`.
2017-08-14 13:09:47 +01:00
Berker Peksag
52e0f3ae08 Fix indentation of code example in chapter 7 (#5329) 2017-08-14 13:04:52 +01:00
Carlton Gibson
be7657c672 Merge pull request #5328 from andreagrandi/update-token-docs
Add documentation to create user token with the new command
2017-08-13 13:52:58 +02:00
Andrea Grandi
1799b569d8 Add documentation to create user token with the new command 2017-08-13 11:08:44 +01:00
Lim H
32a0b62508 Fix introspection of list field in schema 2017-08-12 18:59:03 +01:00
Alexander Dutton
e80b78d1cb RemoteUserAuthentication, docs, and tests (#5306)
RemoteUserAuthentication, docs, and tests
2017-08-11 10:35:00 +01:00
Steven Johns
9b5a6bea67 Fix typo on fields.md (#5320)
> keeps you error messages

to

> keeps your error messages

and 

> more cleanly separated from your code

to 

> cleaner and more separated from your code
2017-08-09 15:21:23 -04:00
Yury V. Zaytsev
96d6a9a6da Docs: update link in pagination.py (#5321)
The blog post referenced in the documentation has been since moved to a new location.
2017-08-09 15:19:43 -04:00
Vašek Dohnal
1f2e2dea96 Fixed typo in docs/Documenting your API (#5316) 2017-08-08 10:01:19 -04:00
Ryan P Kilby
26ebb88306 Revert 3288 (#5313)
* Add regression test for #2505. Thanks @pySilver!

* Add regression test for #5087

* Revert "Cached the field's root and context property."

This reverts commit 792005806b.
2017-08-07 16:52:09 +01:00
Anna Ossowski
21074a02b4 Changed monthly report link (#5308)
* Removed Micropyramid as a sponsor

* Changed monthly report link
2017-08-04 15:23:54 -04:00
Xavier Ordoquy
83c535e9cc Merge pull request #5300 from ribalba/patch-1
Added the django user model
2017-07-31 15:01:48 +02:00
Didi Hoffmann
1368d3677c Added the separator line back
Accidentally also deleted a line.
2017-07-31 15:00:26 +02:00
Didi Hoffmann
ad501d41f5 Added the django user model
So it is possible to copy paste the example and it will work out of the box.
2017-07-31 14:50:36 +02:00
José Padilla
3eade5abeb Merge pull request #5285 from minusf/master
typo: may -> many
2017-07-20 22:30:58 -04:00
minusf
9ec89141ee typo: may -> many 2017-07-20 23:42:51 +02:00
Tom Christie
2d4226c2bd Update README.md 2017-07-18 09:16:13 +01:00
Tom Christie
0c9c951c1d Update README.md 2017-07-18 09:15:22 +01:00
Anna Ossowski
2e534b31c1 Removed Micropyramid as a sponsor (#5280) 2017-07-18 09:14:49 +01:00
Erick Delfin
089887d56e Simplified chained comparisons and minor code fixes (#5276) 2017-07-16 17:12:29 +01:00
Tommy Beadle
2a1fd3b45a Add link to third-party package for LinkHeaderPagination. (#5270) 2017-07-12 16:45:41 +01:00
José Padilla
8a8389bd4b Merge pull request #5264 from rpkilby/search-filter-reverse
Fix SearchFilter to-many behavior/performance
2017-07-11 10:08:37 -04:00
Ryan P Kilby
d1cfec8d87 Fix SearchFilter to-many behavior by ANDing cond's 2017-07-10 14:50:47 -04:00
Ryan P Kilby
f02b7f1329 Add failing test for #4655 2017-07-10 14:20:23 -04:00
Tom Christie
6d4d4dfd04 Ensure closables in request.FILES get closed. (#5262)
Ensure closables on `.FILES` get closed.
2017-07-10 13:42:02 +01:00
elmccarthy
b905197f24 Fix issue #5258 (#5259)
Sanitize serializer.data to remove hidden fields before rendering template JSON instance to raw data form.

* Fix lint issues
2017-07-10 11:43:36 +01:00
Tom Christie
39f6f1137c Merge pull request #5261 from encode/validation-error-on-invalid-timezone-parsing
Raise validation error on invalid timezone parsing.
2017-07-10 11:27:28 +01:00
Tom Christie
41901185d2 Ignore timezone test case for Django 1.8, due to differing behavior. 2017-07-10 11:18:26 +01:00
Tom Christie
fbb3490989 Merge pull request #5188 from andreagrandi/auth-token-cmd
Add Django manage command to create a DRF user Token
2017-07-10 10:35:05 +01:00
Tom Christie
7d240a2e50 Minor cleanup in test. 2017-07-10 10:30:39 +01:00
Tom Christie
c7e2bad524 Merge pull request #5189 from myrubapa/master
Fix API documentation templates do not check for user authentication #5162
2017-07-10 10:28:33 +01:00
Tom Christie
bf7fcc495b Raise validation error on invalid timezone parsing. 2017-07-10 10:14:31 +01:00
Tom Christie
3dab905656 Merge pull request #5231 from dmmatson/feature/slugfield-allow-unicode
Fixed tests on Windows. Added unicode support to SlugField
2017-07-07 12:41:52 +01:00
Tom Christie
1a31959d45 Merge pull request #5229 from IndustriaTech/fix/set-request-args-kwargs
Fixed #5228 Set ViewSet args/kwargs/request before dispatch
2017-07-07 12:39:50 +01:00
José Padilla
d5896b9f7d Merge pull request #5251 from davesque/master
Add information in docs about djangorestframework-simplejwt package
2017-07-06 10:53:52 -04:00
David Sanders
4091607d94 Add information in docs about djangorestframework-simplejwt package 2017-07-05 14:48:54 -06:00
Tom Christie
75fec24e25 Merge pull request #5248 from ossanna16/master
Updated monthly report link
2017-07-04 17:55:19 +01:00
Anna
fd6cc1e395 Updated monthly report link 2017-07-04 17:53:03 +02:00
dmmatson
302a9d089e Fixed tests on Windows. Added unicode support to SlugField 2017-06-23 23:11:17 -06:00
José Padilla
0dd3aa4126 Merge pull request #5230 from nacosta/patch-1
Link in the home page is broken
2017-06-23 20:02:09 -04:00
Neftalí Acosta
900cae1507 Link broken
The link to the Python Exception Handling Techniques article written by Doug Hellmann is broken.

I could find the article in the URL I proposed.
2017-06-23 08:09:10 +01:00
Venelin Stoykov
0e5d26fa6a Fixed #5228 Set ViewSet args/kwargs/request before dispatch 2017-06-22 16:22:17 +03:00
José Padilla
506ec8594d Merge pull request #5227 from mhrivnak/patch-1
typo fix
2017-06-20 15:32:17 -04:00
Michael Hrivnak
5fe984b657 typo fix
removes an extraneous word
2017-06-20 15:07:45 -04:00
José Padilla
9e72736af8 Merge pull request #5219 from blueyed/fix-doc-_authenticate
doc: fix documentation for Request._authenticate
2017-06-17 09:21:00 -04:00
José Padilla
f70e74dca2 Merge pull request #5222 from menecio/menecio-update-dot-drf-contrib-path
Update API guide section referring to DOT
2017-06-17 09:19:56 -04:00
Aristóbulo Meneses
5002d1a9ae Update DOT docs
DOT renamed `ext` to `contrib` on their new release `1.0.0`
2017-06-17 15:02:22 +02:00
Tom Christie
b069b0d33a Merge pull request #5176 from levic/browsable-api-multipart-form-data
Fix browsable API not supporting multipart/form-data correctly
2017-06-16 15:08:27 +01:00
Levi Cameron
5cbfcbc56f Fix regex typo allowing '[' in boundary string 2017-06-16 21:53:06 +10:00
Daniel Hahler
fe95ab675b doc: fix documentation for Request._authenticate
It does not return anything.
2017-06-16 13:23:26 +02:00
Tom Christie
598e5877cd Merge pull request #5192 from matteius/DRF-5135-one-to-one-pk
Special case for when OneToOneField is also primary key.
2017-06-16 12:06:12 +01:00
Tom Christie
d48a745f4d Merge pull request #5218 from ossanna16/master
Added FAQ section for funding site
2017-06-15 21:47:42 +01:00
Anna
462378ba99 Added FAQ section for funding site 2017-06-15 19:02:40 +02:00
José Padilla
0e106c1657 Merge pull request #5214 from dmkoch/patch-1
Quote nested API parameters in api.js
2017-06-13 17:47:18 -04:00
Dan Koch
4701f12c3e Quote nested API parameters in api.js
I sometimes have parameter names with a period (.) in them, to represent nested objects, e.g. containerobj.inner_param. The Javascript was throwing an error in the browsable API when interacting with those parameters.
2017-06-13 16:01:02 -04:00
Xavier Ordoquy
b96a22011b Merge pull request #5210 from blueyed/DeprecationWarning-stacklevel
Use stacklevel=2 with DeprecationWarnings
2017-06-12 21:15:10 +02:00
Daniel Hahler
515fe928d5 Use stacklevel=2 with DeprecationWarnings
This makes the warnings refer to the code where it is used, which makes
it easier to find and fix.
2017-06-12 14:59:29 +02:00
Tom Christie
3c420cfad5 Merge pull request #5196 from Pierre-Sassoulas/master
Added aria-label and a new region for accessibility purposes in base.html
2017-06-09 10:22:27 +01:00
Tom Christie
836e49b535 Merge pull request #5202 from ossanna16/master
Updated monthly report link + added Tom's PyCon talk
2017-06-05 19:12:21 +01:00
Anna
b296d3b9a3 Updated monthly report link + added Tom's PyCon talk 2017-06-05 18:19:03 +02:00
Andrea Grandi
d2459710ca Implement option to reset User token 2017-06-03 11:58:01 +01:00
Andrea Grandi
34c38e0cfe Use self.sdtout and CommandError to print output 2017-06-03 11:06:14 +01:00
Andrea Grandi
cf196a4424 Get UserModel from get_user_model and do not infer the natural key 2017-06-03 10:38:01 +01:00
Pierre Sassoulas
903ef4917a Feat - Added aria-label and a new region for accessibility purpose
Navigating the page with a reader is easier is there is aria-label
and region.

https://www.w3.org/WAI/
2017-06-02 09:49:00 +02:00
Andrea Grandi
be590d61c0 Handle invalid User situation 2017-05-31 23:01:35 +01:00
Xavier Ordoquy
99382f3ccb Merge pull request #5194 from MattBroach/master
Updated DjangoRestMulipleModel documentation to point to new repo loc…
2017-05-31 05:39:39 +00:00
Matt Broach
e4ec1d744e Updated DjangoRestMulipleModel documentation to point to new repo location 2017-05-30 23:39:18 -04:00
Levi Cameron
6b8d6019ea Fix boundary detection regex not handling spaces inside boundary marker correctly 2017-05-31 13:18:17 +10:00
Matt Davis
88f9dbceec Silly linting change
import ordering matters
2017-05-30 14:13:29 -04:00
Matt Davis
6115815108 Special case for when OneToOneField is also primary key.
https://github.com/encode/django-rest-framework/issues/5135
2017-05-30 13:57:45 -04:00
Bekhzod Tillakhanov
31d6ef1ba2 Remove new line 2017-05-30 20:36:46 +05:00
Levi Cameron
1c44ef2b11 Improvements to code clarity 2017-05-30 10:43:33 +10:00
Bekhzod Tillakhanov
c96fa224c7 Fix ul inner li 2017-05-30 00:29:11 +05:00
Bekhzod Tillakhanov
84e22cc2f3 Scheme fix when unauth and Flask8 lint fix 2017-05-30 00:15:07 +05:00
Andrea Grandi
d198b1abe6 Add Django manage command to create a DRF user Token 2017-05-29 17:07:50 +01:00
Tom Christie
9c9525b130 Merge pull request #5187 from mathpresso-mom/list_route_regex
Fix list_route, detail_route with kwargs contains curly bracket in url_path
2017-05-29 13:47:19 +01:00
이동환
0ad017a573 requested changes 2017-05-29 20:55:06 +09:00
Tom Christie
5267fcc8c6 Merge pull request #5159 from carltongibson/docs/get_schema_view_params
Add `generator_class` parameter to `get_schema_view` docs.
2017-05-29 12:53:49 +01:00
Tom Christie
823eea2d59 Merge pull request #5147 from imdark/patch-1
Improve memory footprint when reading large JSON requests.
2017-05-29 11:55:53 +01:00
Tom Christie
7de34cf187 Merge pull request #5163 from khakulov/patch-2
Added documentation from where to import get_schema_view
2017-05-29 11:55:02 +01:00
Tom Christie
e2157fbf7c Merge pull request #5174 from tadhg-ohiggins/html_cutoff_none
Fix exception when HTML_CUTOFF is set to None
2017-05-29 11:54:03 +01:00
Xavier Ordoquy
6c7a7ccb1c Merge pull request #5186 from dryice/max_length_for_file_field
make sure max_length is in FileField kwargs
2017-05-29 07:54:13 +00:00
Dryice Liu
836328594b add test 2017-05-29 08:27:07 +08:00
이동환
973860d9fe Added: test for list_route and detail_route with regex url_path 2017-05-28 18:38:09 +09:00
Dryice Liu
04adfb9c94 make sure max_length is in FileField kwargs 2017-05-28 04:14:56 +08:00
Carlton Gibson
26623436f3 Merge pull request #5179 from felixxm/issue-uri-to-iri
Fixed test_hyperlinked_related_lookup_url_encoded_exists.
2017-05-26 10:12:31 +02:00
Mariusz Felisiak
a002bb5c67
Fixed test_hyperlinked_related_lookup_url_encoded_exists.
Space character ' ' is prohibited in IRIs, therefore we shouldn't
rely on encoding '%20' to ' ' in the HyperlinkedRelatedField tests.
2017-05-26 09:56:26 +02:00
이동환
e6c9f89a12 Fixed curly bracket in regexp of @list_route 2017-05-25 19:13:45 +09:00
Levi Cameron
94c37c09c5 Fix browsable API not supporting multipart/form-data correctly
- Autodetect missing boundary parameter for Content-Type header
- textarea value normalises EOL chars to \n when multipart/form-data requires \r\n
2017-05-25 20:07:34 +10:00
imdark
cdeab1c490 fixed to pass isort linting 2017-05-24 18:12:38 -07:00
imdark
9a22811671 modified to use a reader
modified to use a reader since direct decoding is not supported
2017-05-24 17:56:49 -07:00
Tadhg O'Higgins
99782c2160 Add tests for HTML_CUTOFF setting and fix issue where setting it to None would raise an exception. 2017-05-24 16:46:18 -07:00
Azim Khakulov
d1093b5326 Added documentation from where to import get_schema_view 2017-05-23 02:08:20 +02:00
Tom Christie
871ce34983 Merge pull request #5161 from matteius/master
If pagination class, include the schema generation
2017-05-22 16:46:34 -07:00
Matt Davis
99569190ab If pagination class, include the schema generation
https://github.com/encode/django-rest-framework/issues/5144
2017-05-22 19:10:54 -04:00
Carlton Gibson
53b3b83b04 Add generator_class parameter to docs.
`get_schema_view` accepts `generator_class` parameter
2017-05-22 11:55:19 +02:00
Xavier Ordoquy
6831472a62 Remove ambiguous reference to former DjangoFilterBackend. 2017-05-19 23:50:13 +02:00
Xavier Ordoquy
703655bc65 Non model Viewset requires base_name when registering to router. 2017-05-19 23:35:25 +02:00
Xavier Ordoquy
8ee706a69e Merge pull request #5155 from encode/carltongibson-patch-1
Update Django-Filter requirement
2017-05-19 10:13:30 +00:00
Carlton Gibson
167fd05857 Update Django-Filter requirement
A quick fix. Latest is 1.0.4
2017-05-19 09:00:56 +02:00
Xavier Ordoquy
1e9e1a5bfe Merge pull request #5149 from tomchuk/master
Don't trim whitespace from authtoken passwords
2017-05-18 09:12:47 +00:00
Thomas Achtemichuk
70205cc64e
Lint 2017-05-17 15:17:55 -04:00
Thomas Achtemichuk
c9c383dfad
Don't trim whitespace from authtoken passwords
* Fixes #5148
2017-05-17 14:52:39 -04:00
imdark
3a2ad8e68c in order to solve the memory leak at #5146
Large encoded string take a very long time to to release from memory, but if we just pass the stream directly into json.load we get much better memory performance.
2017-05-17 11:49:30 -07:00
José Padilla
1ca5a9d042 Merge pull request #5143 from carltongibson/update-django-filter
Update Django Filter requirement
2017-05-16 15:44:31 -04:00
Carlton Gibson
1d72b8f758 Update Django Filter requirement
Latest is v1.0.3 — improving support for schema generation
2017-05-16 21:16:19 +02:00
Tom Christie
25f65ab96b Merge pull request #5139 from blueyed/flake8-config
Move flake8 config to setup.cfg
2017-05-16 11:39:31 +01:00
Tom Christie
a8e527a462 Merge pull request #5138 from blueyed/fix-star-source-with-HyperlinkedModelSerializer
Fix source="*" with HyperlinkedModelSerializer
2017-05-16 11:38:22 +01:00
Daniel Hahler
89276e6cfc Move flake8 config to setup.cfg
This allows for flake8 to pick it up when running it by itself.
2017-05-16 12:18:33 +02:00
Daniel Hahler
17bf312408 fixup! Add failing test
[ci skip]
2017-05-16 12:10:45 +02:00
Daniel Hahler
09f62e11a0 Possible fix 2017-05-16 12:07:04 +02:00
Daniel Hahler
2b199f7588 Add failing test 2017-05-16 12:02:23 +02:00
Tom Christie
003c304115 Merge pull request #5131 from vimarshc/issue4989
Ignore any invalidly formed query parameters for OrderingFilter.
2017-05-15 09:45:48 +01:00
Vimarsh Chaturvedi
7b4afdc737 Merge branch 'master' into issue4989 2017-05-13 19:10:47 +05:30
vimarshc
b2d6149301 importing regex constant to remove invalid parameters. 2017-05-13 05:14:32 +05:30
Tom Christie
996e587398 Remove broken bit of merge commit 2017-05-12 18:25:06 +01:00
Tom Christie
cdd15f3769 Remove broken bit of merge commit 2017-05-12 18:23:35 +01:00
Tom Christie
5f386f5839 Merge pull request #5133 from encode/version-3-6-3
Version 3.6.3
2017-05-12 17:13:41 +01:00
Tom Christie
a99f12f1c6 Merge branch 'master' into version-3-6-3 2017-05-12 17:03:32 +01:00
Tom Christie
42f80c65a9 Version 3.6.3 2017-05-12 16:52:27 +01:00
Tom Christie
e8ff5e268b Javascript fixes for API docs 2017-05-12 16:48:53 +01:00
Xavier Ordoquy
a251b93792 Merge pull request #5126 from njamaleddine/get_object_or_404_fix
Add ValidationError to except in get_object_or_404 for django 1.11
2017-05-11 08:16:17 +00:00
vimarshc
ed70f5636a Added failing test case for multiple hyphens in orderingfilter paramter 2017-05-11 12:56:41 +05:30
Nabil Jamaleddine
cdb8a3c3c8 Add ValidationError to except in get_object_or_404 for django 1.11 2017-05-05 21:17:12 -04:00
Tom Christie
69b0ac52c2 Merge pull request #5117 from rpkilby/fix-filter-backend
Fix DjangoFilterBackend mro
2017-05-04 12:32:03 +01:00
Xavier Ordoquy
36aea309fd Merge pull request #5119 from yunmanger1/yunmanger1-comment-typo-fix
Fix a typo in a comment
2017-05-04 05:37:26 +00:00
German Ilyin
5246a5a44e Fix a typo in a comment 2017-05-04 10:13:58 +06:00
Ryan P Kilby
01ffb8961d Fix DjangoFilterBackend mro 2017-05-03 12:51:44 -04:00
Ryan P Kilby
53b100d03d Add failing test for filter backend mro 2017-05-03 12:50:40 -04:00
Tom Christie
c22e61d3c3 Merge pull request #5113 from rpkilby/update-filter-docs
Simplify django-filter docs, add drf integration link
2017-05-03 16:57:21 +01:00
Ryan P Kilby
7322aa6b68 Simplify django-filter docs, add drf integration link 2017-05-03 11:03:11 -04:00
Tom Christie
67f382394b Update third-party-packages.md 2017-05-03 09:25:40 +01:00
Tom Christie
97312699f5 Merge pull request #5085 from hurturk/schema-method-limited
Generate schema with respect to http_method_names provided by CBV
2017-05-03 09:16:01 +01:00
hurturk
518bb44a9e Remove excessive class instance while getting http_method_names 2017-05-03 03:49:04 -04:00
Xavier Ordoquy
a1e6d83533 Add missing pk keyword argument to the detail_route. 2017-05-03 02:19:30 +02:00
hurturk
6075f8051a Refactor CBV schema method limitation for set operations 2017-05-02 17:34:53 -04:00
Tom Christie
60dbe72a62 Merge pull request #4437 from dfavato/master
Set self.count before self.limit in LimitOffsetPagination
2017-05-02 10:21:36 +01:00
Tom Christie
dea601dc86 Merge pull request #4222 from NewVadim/master
Fix partial update for the ListSerializer.
2017-05-02 10:17:12 +01:00
Tom Christie
d2d0a06faf Merge pull request #5084 from Nerlin/fix-render-required-nested-serializer-error
Fixed render error of required nested serializer.
2017-05-02 10:05:25 +01:00
Tom Christie
e1fdb895b5 Included Python 3.6 in the requirements
Refs #5108
2017-05-02 09:54:45 +01:00
Tom Christie
007e86ab27 Included Python 3.6 in the requirements
Refs #5108.
2017-05-02 09:54:01 +01:00
Tom Christie
e7483133ea Update browsable-api.md 2017-05-01 11:49:42 +01:00
Tom Christie
a857dab79c Merge pull request #5103 from folz/patch-1
Improve grammar in .force_authenticate() docs
2017-04-30 17:56:33 +01:00
Xavier Ordoquy
0e0404ecb1 Merge pull request #5105 from Afrowave/master
Updating the Django version "runserver" output and enforcing code block styling
2017-04-28 15:30:31 +00:00
Jimmy Gitonga
6e7c9594fe Updating the Django version "runserver" output and enforcing code block styling
CHANGED the Django version run server output to “1.11”
ADDED “```” to a code block on line 44 of
“/tutorial/7-schemas-and-client-libraries/“ to enforce code wrap.
Perhaps, we might need to do this to all code blocks. I would be happy
to do that.
2017-04-28 18:08:54 +03:00
Rodney Folz
971bc066c5 Improve grammar in .force_authenticate() docs
* Remove unnecessary comma
* Remove the "and simple" copied from the line above.
* Add "entirely" to emphasize that this function bypasses the authentication step.
2017-04-27 15:44:06 -07:00
Tom Christie
80d0ee563a Merge pull request #5042 from boxingwizards/i4999
PoC Add JSONBoundField to serializers (Fixes #4999)
2017-04-27 20:26:40 +01:00
Tom Christie
5ba2368ff9 Merge pull request #4987 from halfstrik/master
Added test for DateTimeField validation when server has timezone with…
2017-04-27 17:22:27 +01:00
Tom Christie
aafd0a644f Merge pull request #4979 from linovia/feature/improve_schema_shortcut
Restrict doc & schema shortcuts to a subset of urls
2017-04-27 16:58:01 +01:00
Tom Christie
5e5fd67899 Merge pull request #5086 from valohai/limit-offset-pagination-schema
SchemaGenerator: Avoid crashing with pagesizeless paginators
2017-04-27 16:57:28 +01:00
Tom Christie
ee1a9fcef6 Merge pull request #5078 from rooterkyberian/issue-4748
add URL path unquote to HyperlinkedRelatedField.to_internal_value
2017-04-27 16:27:04 +01:00
Dave Allan
f56b117064 Pass non-JSON serializable values through unmodified 2017-04-26 14:10:47 -04:00
Dave Allan
7a0bd1c4d1 Use text area for JSON fields and indent JSON 2017-04-26 14:10:47 -04:00
Dave Allan
11d8e4df88 PoC Add JSONBoundField to serializers (Fixes #4999)
Per issue #4999, JSONFields are not rendered properly in the DRF
browsable API HTML forms.  This patch attempts to fix that behavior by
introducing a JSONBoundField helper similar to the NestedBoundField
helper.
2017-04-26 14:10:47 -04:00
Tom Christie
66e015c5ec Merge pull request #5099 from jpadilla/books
Improve books section
2017-04-26 14:28:31 +01:00
José Padilla
d45c12ff8c
Improve books section 2017-04-26 09:16:45 -04:00
José Padilla
fff9837195 Merge pull request #5098 from pydanny/fix-book-order
Corrected order of books. Apologies to @limedaring
2017-04-25 21:31:39 -04:00
Daniel Roy Greenfeld
dfb0e6ff2d Corrected order of books. Apologies to @limedaring 2017-04-25 17:42:14 -07:00
Xavier Ordoquy
10c22af81e Merge pull request #5097 from pydanny/add-tsd111-to-resources
add Two Scoops of Django 1.11 to tutorials and resources
2017-04-25 21:40:43 +00:00
Daniel Roy Greenfeld
4be21cf854 add Two Scoops of Django 1.11 to tutorials and resources 2017-04-25 14:36:36 -07:00
Tom Christie
a0602bce4c Merge pull request #5088 from mlissner/patch-1
Updates the core json media type in the docs
2017-04-24 20:14:17 +01:00
Mike Lissner
b8520a1f2e Updates the core json media type in the docs
Per: http://www.django-rest-framework.org/topics/3.5-announcement/#corejson-media-type

(I was *wondering* why this didn't seem to work!)
2017-04-20 11:37:46 -07:00
Aarni Koskela
72da73310d SchemaGenerator: Avoid crashing with pagesizeless paginators 2017-04-19 09:43:28 +03:00
Xavier Ordoquy
778aee1bb3 Merge master. 2017-04-19 07:56:39 +02:00
Xavier Ordoquy
36e5759498 Add documentation for the get_schema_view new argument: patterns 2017-04-19 07:49:13 +02:00
hurturk
2196cd2bbb Generate schema with respect to http_method_names provided by CBV 2017-04-18 23:44:18 -04:00
nerlin
ed72603d35 Fixed render error of required nested serializer.
Fixes an error that occurs on rendering response with error that says that required nested serializer field must be specified in data.
2017-04-19 03:18:52 +03:00
Tom Christie
8f6173cd8a Merge pull request #5082 from valohai/customizable-schema-generator
Customizable schema generator classes
2017-04-18 13:39:40 +01:00
Aarni Koskela
53f48d1564 Allow customizing DefaultRouter's schema generator class 2017-04-18 14:14:04 +03:00
Aarni Koskela
51a6c076e2 Allow customizing the SchemaGenerator class for docs 2017-04-18 14:14:04 +03:00
José Padilla
bd768d6253 Merge pull request #5081 from smirnoffs/add_django_1_11_to_setup
Add Django 1.11 into *.md and setup.py
2017-04-17 14:12:33 -04:00
Sergey Smirnov
34f88dc3f8 Add Django 1.11 into *.md and setup.py 2017-04-17 19:42:50 +02:00
Maciej Urbanski
5e185aa26b add URL path unquote to HyperlinkedRelatedField.to_internal_value 2017-04-14 01:56:44 +02:00
Xavier Ordoquy
d757127e9a Merge remote-tracking branch 'reference/master' into feature/improve_schema_shortcut
* reference/master: (22 commits)
  Clarify get_schema_fields signature
  Updated monthly report link on funding page
  Bumped django-guardian version.
  remove django 1.11 from allow_failure matrix
  update django 1.11 to stable release in tox
  Update existing vary headers in response instead of overwriting them.
  Update links after moving to encode org
  Use overridden settings exception handler
  Pass initkwargs stored on view to instance
  Update 7-schemas-and-client-libraries.md
  Update Boolean field to more closely match python library
  Fix parser names in docstring.
  Fix typo at docstring
  update test case
  update test case
  fix unique=True validation for ChoiceField
  Added drfpasswordless to Authentication docs
  Document adding django_filters to installed apps
  Added drfpasswordless to third party packages topic page.
  Added drfpasswordless to authentication topic page.
  ...
2017-04-13 08:29:47 +02:00
Tom Christie
fd72a814f8 Merge pull request #5073 from khakulov/patch-1
Clarify get_schema_fields signature
2017-04-12 17:22:33 +01:00
Tom Christie
853f393112 Merge pull request #5065 from felixxm/django-guardian-version
Bumped django-guardian version.
2017-04-12 17:02:52 +01:00
Azim Khakulov
613aa61ada Clarify get_schema_fields signature
I had to look for the signature of `get_schema_fields()`in source code.
2017-04-12 12:25:27 +02:00
José Padilla
f884814b89 Merge pull request #5071 from ossanna16/master
Updated monthly report link on funding page
2017-04-10 17:33:10 -04:00
Anna
1bbfc0e87c Updated monthly report link on funding page 2017-04-10 22:37:49 +02:00
Mariusz Felisiak
e70b920d2e
Bumped django-guardian version. 2017-04-09 22:21:42 +02:00
Xavier Ordoquy
06d64bd74a Merge pull request #5063 from auvipy/patch-3
remove django 1.11 from travis allow_failure matrix
2017-04-08 22:00:06 +02:00
Xavier Ordoquy
01eda156bd Merge pull request #5062 from auvipy/patch-1
django 1.11 to stable release in tox
2017-04-08 21:29:04 +02:00
Asif Saifuddin Auvi
82c855c407 remove django 1.11 from allow_failure matrix 2017-04-09 01:23:07 +06:00
Asif Saifuddin Auvi
2e546f02ba update django 1.11 to stable release in tox 2017-04-09 01:20:56 +06:00
Tom Christie
d300c3c648 Merge pull request #5047 from kirberich/merge-vary-headers
Update existing vary headers in response instead of overwriting them.
2017-04-07 20:44:58 +01:00
Tom Christie
33290170e8 Merge pull request #5060 from jpadilla/encode
Update links after moving to encode org
2017-04-07 17:20:51 +01:00
Robert Kirberich
9ebd5a29e4 Update existing vary headers in response instead of overwriting them.
Previously, any existing vary headers would simply be wiped out by DRF. Using patch_vary_headers assures that existing headers remain.
2017-04-07 17:06:09 +01:00
José Padilla
c1f31492ae
Update links after moving to encode org 2017-04-07 10:28:35 -04:00
Tom Christie
bbe0df2916 Merge pull request #5053 from s-m-b/patch-1
Pass initkwargs stored on view to instance
2017-04-07 08:29:34 +01:00
Tom Christie
95df489808 Merge pull request #5055 from sigmavirus24/bug/5054
Use overridden settings exception handler
2017-04-07 08:27:18 +01:00
Ian Cordasco
c2ee1b3033 Use overridden settings exception handler
Instead of using the api_settings exception handler, we use the
overridden settings attribute to find the correct handler.

Closes #5054
2017-04-06 14:05:29 -05:00
s-m-b
f1ca71ce21 Pass initkwargs stored on view to instance 2017-04-06 16:38:28 +04:00
Tom Christie
5e6b233977 Merge pull request #5040 from minusf/master
fix whitespace in code example
2017-03-30 12:31:48 +01:00
minusf
471065ebc6 Update 7-schemas-and-client-libraries.md 2017-03-30 12:28:55 +02:00
Tom Christie
fe33b2d0b6 Merge pull request #5038 from htmis/master
Update Boolean field to support 'yes' and 'no' values
2017-03-30 08:58:00 +01:00
htmis
4a54d9f474 Update Boolean field to more closely match python library
Python Reference:
distutils.util.strtobool(val)
Convert a string representation of truth to true (1) or false (0).
True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.
2017-03-29 20:21:18 -04:00
Xavier Ordoquy
4369157529 Merge pull request #5037 from linovia/master
Fix parser names in docstring.
2017-03-29 05:58:57 +00:00
Xavier Ordoquy
d417c6d1b9 Fix parser names in docstring. 2017-03-29 07:57:14 +02:00
Xavier Ordoquy
3a17391e27 Merge pull request #5036 from ir4y/patch-1
Fix typo at doc string
2017-03-29 05:54:27 +00:00
Ilya Beda
f27c551218 Fix typo at docstring 2017-03-29 12:51:01 +07:00
José Padilla
a652ebd292 Merge pull request #5028 from Ekluv/ekluv_5004
fix unique=True validation for ChoiceField
2017-03-28 13:57:52 -07:00
Ekluv
d66304abe6 update test case 2017-03-28 12:02:03 +05:30
Ekluv
ef8092ba2f update test case 2017-03-28 11:50:55 +05:30
Tom Christie
20c7a24c14 Merge pull request #5025 from aaronn/thirdparty
Add drfpasswordless to Third Party Packages and Authentication pages
2017-03-27 20:12:38 +01:00
Ekluv
56fe0e4b3f fix unique=True validation for ChoiceField 2017-03-28 00:38:21 +05:30
aaronykng
0400cbbc4c Added drfpasswordless to Authentication docs 2017-03-27 12:08:07 -07:00
Tom Christie
c684147e65 Merge pull request #5027 from Jackevansevo/patch-1
Document adding django_filters to INSTALLED_APPS
2017-03-27 20:05:28 +01:00
Jack Evans
73bd709813 Document adding django_filters to installed apps
Reminds users to add `django_filters` to their `INSTALLED_APPS` as detailed in the django-filter documentation https://django-filter.readthedocs.io/en/develop/guide/install.html
2017-03-27 16:13:50 +01:00
aaronykng
10d8ad601c Added drfpasswordless to third party packages topic page. 2017-03-27 07:27:46 -07:00
aaronykng
aa92736d72 Added drfpasswordless to authentication topic page. 2017-03-27 07:19:11 -07:00
Tom Christie
63a4021472 Add whitespace between user quotes on funding page 2017-03-27 11:18:20 +01:00
Tom Christie
4e5b59cc5c Merge pull request #5008 from akhilputhiry/4758
Fix docs 404 pages with nested paths.
2017-03-27 11:17:20 +01:00
Akhil Lawrence
2f6773e99c updated mkdocs 2017-03-24 20:48:58 +05:30
Xavier Ordoquy
6ad0be44d3 Merge remote-tracking branch 'reference/master' into feature/improve_schema_shortcut
* reference/master:
  use django 1.11rc1 in tox
  Leave parameters with regex pattern as String
  restored original formatting
  Do not hint BigAutoField as integer (outside of range)
  Mention where the mixins live
  Try to improve browser support
  Cleanup and refactor docs api.js script
  Move bootstrap modal data attrs to anchor
  Remove unused base.js script
  Correctly set scheme in coreapi TokenAuthentication
  reverted to fix the issue without changing setting
  DEFAULT_PAGINATION_CLASS is changed to 'None'
  add content block and breadcrumbs_empty block to allow base.html to be reused
  Update 7-schemas-and-client-libraries.md
  Updated testimonial name on funding site
  ID must start from 1 again
2017-03-24 15:21:43 +01:00
Tom Christie
0fdaf4f481 Merge pull request #5001 from jpadilla/docs-cleanup
JavaScript cleanup in API Docs.
2017-03-22 14:01:00 +00:00
Tom Christie
ac1d230482 Merge pull request #5015 from auvipy/patch-1
use django 1.11rc1 in tox
2017-03-22 09:38:01 +00:00
Tom Christie
8e9cb1e614 Merge pull request #5014 from dczech/feature/decouple-bigautofield
Include URL path regexs in API schemas where valid.
2017-03-22 09:37:07 +00:00
Asif Saifuddin Auvi
db4dd0c977 use django 1.11rc1 in tox 2017-03-22 14:40:23 +06:00
Sergey Petrunin
b0a0c30bfe Added pytz exception in compat module.
Mock pytz.timezone localize in tests.
Ref: #4986
2017-03-22 00:03:32 -04:00
Dariusz Czech
54d0901f38 Leave parameters with regex pattern as String 2017-03-21 15:15:20 +01:00
Dariusz Czech
9074e3e478 restored original formatting 2017-03-21 08:40:59 +01:00
Sergey Petrunin
e4a1bd140b Update error message.
Ref: #4986
2017-03-20 18:47:25 -04:00
Dariusz Czech
c7e2d1d976 Do not hint BigAutoField as integer (outside of range) 2017-03-20 22:21:07 +01:00
Tom Christie
7d64cf568a Merge pull request #4998 from COCOLMAN/master
Ensure that pagination is not included in API schema when `page_size=None`.
2017-03-20 15:32:44 +00:00
Tom Christie
9a8d29e784 Merge pull request #5000 from jpadilla/issue-4994
Correctly set scheme in coreapi TokenAuthentication
2017-03-20 09:55:06 +00:00
Xavier Ordoquy
1c33e84e28 Merge pull request #5005 from nicktimko/patch-1
Mention where the mixins live
2017-03-20 06:59:56 +01:00
Nick Timkovich
51c6d23a05 Mention where the mixins live
Ctrl-F on the ViewSets page doesn't show where the `mixins.SomeMixin...` classes come from.
2017-03-19 17:17:37 -05:00
Sergey Petrunin
d4726dab81 Fix bug for not existent or ambiguous datetime during native to aware conversion in timezone with DST.
Ref: #4986
2017-03-18 23:13:26 -04:00
José Padilla
9e18d005d1
Try to improve browser support 2017-03-17 22:21:14 -04:00
José Padilla
b0f2ec785e
Cleanup and refactor docs api.js script 2017-03-17 21:44:40 -04:00
José Padilla
d8507d3f9c
Move bootstrap modal data attrs to anchor 2017-03-17 21:44:11 -04:00
José Padilla
be0e196e65
Remove unused base.js script 2017-03-17 21:43:20 -04:00
José Padilla
7e76cd8695
Correctly set scheme in coreapi TokenAuthentication 2017-03-17 20:27:36 -04:00
sol HYUN
16aad89459 reverted to fix the issue without changing setting 2017-03-18 06:17:35 +09:00
sol HYUN
9c3edb0921 DEFAULT_PAGINATION_CLASS is changed to 'None'
because the default value was specified, it did not work properly in API
Document
2017-03-18 04:50:01 +09:00
Tom Christie
73ad88eaae Merge pull request #4993 from jeffcjohnson/master
add content block and breadcrumbs_empty block to base.html for reuse
2017-03-17 14:35:36 +00:00
Jeff Johnson
323f59091c add content block and breadcrumbs_empty block to allow base.html to be reused 2017-03-16 09:03:45 -04:00
Tom Christie
fb8cbab4cf Merge pull request #4991 from fakepoet/patch-1
Fix Django url syntax.
2017-03-16 12:26:46 +00:00
Dark Goat
3cf01b7350 Update 7-schemas-and-client-libraries.md
fix django url syntax.
2017-03-16 19:37:48 +08:00
Tom Christie
f3ccad8fea Merge pull request #4988 from ossanna16/master
Updated testimonial name on funding site
2017-03-16 09:11:00 +00:00
Xavier Ordoquy
e438c532ae Merge pull request #4985 from COCOLMAN/master
ID must start from 1 again
2017-03-16 07:18:49 +01:00
Anna
6a8aed03a8 Updated testimonial name on funding site 2017-03-16 06:00:57 +01:00
Sergey Petrunin
1ee54fb85c Added test for DateTimeField validation when server has timezone with DST and input is a native time in a DST shift interval.
Added pytz to requirements-testing.txt to reproduce the case.
2017-03-15 23:45:41 -04:00
sol HYUN
eb8c658f33 ID must start from 1 again
At the beginning of tutorial4, The database had been removed
2017-03-16 06:34:30 +09:00
Xavier Ordoquy
b558c9ecc4 Allow the documentation and schema shortcut functions to get a list of urls to introspect. 2017-03-15 08:07:12 +01:00
Tom Christie
3b466fabe7 Merge pull request #4973 from tomchristie/support-head-in-viewsets
Support HEAD in viewsets
2017-03-13 13:16:04 +00:00
Tom Christie
e94011eb77 Merge pull request #4972 from tomchristie/use-items-template-tag
Use 'items' templatetag throughout.
2017-03-13 12:53:25 +00:00
Tom Christie
43b38964ea Support HEAD in viewsets 2017-03-13 12:51:03 +00:00
Tom Christie
0173e9bd21 Use 'items' templatetag throughout. 2017-03-13 12:35:19 +00:00
Tom Christie
df2adbb423 Merge pull request #4957 from ossanna16/master
Updated funding page
2017-03-13 10:43:03 +00:00
Tom Christie
2df80c3c9d Merge pull request #4688 from theosotr/feature-source
Support usage of 'source' in `extra_kwargs`.
2017-03-13 10:25:38 +00:00
Tom Christie
d508a3dd1e Merge pull request #4967 from 0xKD/patch-2
Update coreapi.js version in JavaScript API docs.
2017-03-13 10:06:35 +00:00
Tom Christie
de9a8c4811 Fix mime type on schema.js endpoint. Closes #4968. 2017-03-13 10:03:13 +00:00
Kedar
9e62bc51ec Update coreapi.js version 2017-03-11 11:19:26 +05:30
Anna
ade7a254d5 Fixed mistakes for funding page PR 2017-03-10 23:06:01 +01:00
Anna
628c356832 Merge remote-tracking branch 'upstream/master' 2017-03-10 22:28:20 +01:00
Tom Christie
1d34bc0b92 Update release notes 2017-03-10 14:38:24 +00:00
Tom Christie
928f7cb40f Version 3.6.2 2017-03-10 13:00:08 +00:00
Tom Christie
7a8fb262f2 Fallback to more widely supported JS feature sets. (#4961) 2017-03-10 12:07:15 +00:00
Tom Christie
9ccdc4366f Merge branch 'master' of github.com:tomchristie/django-rest-framework 2017-03-10 10:59:39 +00:00
Tom Christie
9baa1fde15 Add 'mark_safe' in template tags. Closes #4952. Closes #4953. 2017-03-10 10:59:31 +00:00
Michael Palmer
81887bdc4e Add glyphicon fonts to static docs (#4951)
* Fixes #4950.
2017-03-10 10:37:31 +00:00
Tom Christie
5128004f54 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2017-03-10 09:10:54 +00:00
Tom Christie
f51bb5ac8b Drop unneeded comment 2017-03-10 09:10:29 +00:00
Tom Christie
8818aa9d58 Merge branch 'master' of https://github.com/cartyc/django-rest-framework into cartyc-master 2017-03-10 09:09:51 +00:00
Asif Saifuddin Auvi
baea07c511 converted testing test asserts to pytest (#4949)
* converted testing test asserts to pytest

* moved 3rd arg from test_empty_post_uses_default_boolean_value test assert
2017-03-10 09:00:00 +00:00
Tom Christie
0fe0a91aed Remove erronous HTML in example. Closes #4958 2017-03-10 08:51:19 +00:00
Anna
60bb3b0958 Updated funding page 2017-03-10 06:30:31 +01:00
Chris Carty
bc2c76a000 fixed issue on schemas.py where if model._meta.get_field(variable) failed model_field was not set to None and would reult in an error 2017-03-09 21:11:52 -05:00
Tom Christie
544b4b9948 Ensure 'markdown' dependancy is optional. Refs #4941. (#4947) 2017-03-09 16:50:00 +00:00
Tom Christie
b884bdd391 Add 3.6 release to index 2017-03-09 16:16:22 +00:00
Tom Christie
1d4290eb7b Tweak docs 2017-03-09 15:59:29 +00:00
Tom Christie
86931b01b6 Note dependancies in docs 2017-03-09 14:59:00 +00:00
Tom Christie
52db57a6e7 Version 3.6 (#4943) 2017-03-09 14:49:51 +00:00
Xavier Ordoquy
537df7a6ad Extract APISchemaView and APIRootView out of the DefaultRouter. (#4707) 2017-03-07 13:39:08 +00:00
Tibo Beijen
cf5d401a0e Allow required false and default (#4692)
* Default value will now be used when serializing if key or attribute is missing.
2017-03-07 13:19:19 +00:00
Md. Al-Amin
8a14b39e7d Added doc for removing pagination in generic-view. (#4940) 2017-03-06 18:33:27 +00:00
Tom Christie
0b708f04e1 Client library & API documentation docs (#4939) 2017-03-06 12:42:51 +00:00
Tom Christie
68d2020112 Live API documentation (#4755) 2017-03-03 15:24:37 +00:00
atkawa7
7f59ce1ec2 Directly using Django's JSONResponse in the Tutorial (#4935)
* directly using Django's JSONResponse

* fixed JsonResponse typo

* added safe=False to JsonResponse

* removed unnecessary 'safe=False' in JsonResponse
2017-03-03 14:04:41 +00:00
Tim Watts
8df340908b Add failing tests and fix for dict that have a key items #4931 (#4932) 2017-03-03 09:23:09 +00:00
José Padilla
35bccaab90 Merge pull request #4934 from ossanna16/master
Fixed broken mail link in tutorials and resources
2017-03-02 20:04:56 -05:00
Anna
ff4f252003 Fixed broken mail link in tutorials and resources 2017-03-03 00:40:57 +01:00
Peter JJ MacDonald
dfea596b0f Update django-filter requirement (#4933) 2017-03-01 21:27:23 +00:00
José Padilla
95380f7717 Merge pull request #4928 from tdruez/patch-1
Added a failing test for #4927
2017-03-01 08:52:27 -05:00
tdruez
d616c1591f Added a test to cover the DjangoModelPermissions #4927 issue
`DjangoObjectPermissions` and `DjangoModelPermissions` are now properly cover for the `METHOD_NOT_ALLOWED` issue
2017-03-01 09:50:21 +01:00
José Padilla
51b6a5cd9c Merge pull request #4930 from dbinoj/patch-1
Fix Schemas Example URL
2017-02-28 15:06:58 -05:00
Binoj David
d58c89adc1 Fix Schemas Example URL 2017-02-28 22:45:17 +05:30
tdruez
e9a68e575a Merge pull request #1 from tdruez/master
Fixed Permissions.get_required_object_permissions for #4927
2017-02-28 17:55:02 +01:00
tdruez
06a1e12fd8 Fixed Permissions.get_required_object_permissions for #4927 2017-02-28 17:51:32 +01:00
tdruez
c30ccac38e Added a failing test for #4927 2017-02-27 20:39:47 +01:00
José Padilla
b936d829a6 Fix mailto link (#4923) 2017-02-26 09:08:03 +00:00
Anna Ossowski
e922d91614 Created Tutorials and Resources, cleaned up Third Party Packages (#4910)
* Updated Support section and added funding email
* Created new tutorials and resources section, cleaned up third party packages section
* Created Jobs section
2017-02-24 12:55:34 +00:00
Xavier Ordoquy
e40d363e6c Merge pull request #4919 from bluetech/not-readonly_fields
Guard against the possible misspelling `readonly_fields` in model serializers
2017-02-22 14:25:02 +01:00
Ran Benita
7a408f6cd2 Guard against the possible misspelling readonly_fields in model serializers
Fixes #4897.
2017-02-22 13:27:23 +02:00
Tom Christie
d82dbc0925 Add MicroPyramid 2017-02-21 21:18:53 +00:00
Xavier Ordoquy
21e33dcc80 Merge pull request #4916 from auvipy/patch-1
added django 1.11 beta 1 for testing
2017-02-21 10:16:10 +01:00
Asif Saifuddin Auvi
1a49318522 added django 1.11 beta 1 for testing 2017-02-21 10:31:05 +06:00
Vadim
d390762e18 Add drf-writable-nested package to third-party serializers (#4913) 2017-02-20 15:16:27 +00:00
Lanrik
5986f95c8d Rearrange code (#4908)
Minor refactor. Move assignment to after `None` check.
2017-02-20 09:48:19 +00:00
Pavlin Gergov
eacb93d453 Update _not_authenticated's docstring (#4906) 2017-02-20 09:33:54 +00:00
Xavier Ordoquy
625eb4c53f Merge pull request #4911 from jisaacstone/feature/serializer-mappings
Check for collection.Mapping instead of dict
2017-02-19 23:04:43 +01:00
Isaac Stone
289e1e440e Check for collection.Mapping instead of dict
issue #4901
2017-02-19 13:10:03 -08:00
José Padilla
300e46a9e5 Merge pull request #4909 from akhilputhiry/ISSUE-4706
[ISSUE-4706] API guide for serializers is outdated
2017-02-18 07:41:42 -04:00
Akhil Lawrence
963cb4cdc6 Corrected documentation 2017-02-18 13:20:03 +05:30
José Padilla
e5ba567b37 Merge pull request #4902 from felixxm/encoders-coverage
Increased utils/encoders.py test coverage.
2017-02-15 04:23:46 -05:00
Mariusz Felisiak
cd469f616a
Increased utils/encoders.py test coverage. 2017-02-15 07:17:33 +01:00
Xavier Ordoquy
eb14f478d0 Merge pull request #4900 from toidi/fix-datetime-format-documentation
Refs: #4256 delete not relevant documentation
2017-02-14 12:32:44 +01:00
Eduard Iskandarov
de8fcbf696 Refs: #4256 delete unrelevant documentation 2017-02-14 13:27:33 +03:00
Carlton Gibson
20e3717ae4 Merge pull request #4895 from felixxm/reverted-4852
Reverted "Removed multi-table inheritance auto created PK from serialize".
2017-02-11 20:23:14 +01:00
Mariusz Felisiak
40e3462767
Reverted "Removed multi-table inheritance auto created PK from serialize" 1ecbeebbe5. 2017-02-11 17:39:47 +01:00
Tom Christie
eb5774229f Version 3.5.4 (#4894) 2017-02-10 11:15:39 +00:00
Michael Borisov
176831e22b Missing comma (#4889) 2017-02-08 15:17:58 +00:00
李扬
cbad236f6d Add max_length and min_length arguments for ListField (#4877) 2017-02-06 09:36:03 +00:00
Tom Christie
79f431c44a Update sponsors on README to include rollbar (#4876) 2017-02-03 17:10:52 +00:00
Tom Christie
222f80f340 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2017-02-03 16:54:23 +00:00
Tom Christie
3c93c3f7b4 Added Rollbar to premium sponsors 2017-02-03 16:54:13 +00:00
Xavier Ordoquy
f4707ad0e0 Merge pull request #4870 from felixxm/issue-dedent
Fixed `dedent` for tab indent.
2017-02-02 11:01:37 +01:00
Mohammad Ashraful Islam
2ec3db8177 fixed url checker ':' to 'http' (#4678) 2017-02-01 12:20:06 +00:00
Mariusz Felisiak
b99272c425
Fixed dedent for tab indent. 2017-01-31 20:57:52 +01:00
José Padilla
f9a0db3ee0 Merge pull request #4867 from micgeronimo/pagination-tests
Add test for pagination when limit not set
2017-01-31 12:03:59 -05:00
Artem Muterko
d610d150f1 Add test for pagination when limit not set 2017-01-31 16:51:09 +02:00
Mariusz Felisiak
3001b56e06 Fixed Django 2.0 compatibility due to django.conf.urls.include parameters change. (#4866) 2017-01-30 16:11:19 +00:00
Artem Muterko
31e9f7dfbb Add remaining tests for generics (#4865) 2017-01-30 11:08:03 +00:00
José Padilla
f572862d0f Merge pull request #4862 from felixxm/issue-cleanup-importlib
Removed unnecessary importlib wrapper.
2017-01-29 14:52:27 -05:00
Mariusz Felisiak
1c437a793c
Removed unnecessary importlib wrapper. 2017-01-29 20:38:39 +01:00
Anna Ossowski
a8dbc22028 Updated Support section and added funding email (#4860) 2017-01-28 22:41:21 +00:00
Artem Muterko
220be31791 Git add remaining tests for BaseSerializer (#4857) 2017-01-27 15:44:00 +00:00
Tom Christie
b1eade4e32 Update machinalis links 2017-01-27 12:57:26 +00:00
Anna Ossowski
245b356ee7 Updated Machinalis links (#4856) 2017-01-27 10:35:25 +00:00
Artem Muterko
d0eb2e6cae Add remaining tests for metadata (#4855) 2017-01-27 09:25:51 +00:00
Mariusz Felisiak
1ecbeebbe5 Fixed #4574 -- Removed multi-table inheritance auto created PK from serialize. (#4852) 2017-01-26 14:18:43 +00:00
Artem Muterko
21166a3ab6 Add couple of tests for filters (#4849) 2017-01-25 14:35:12 +00:00
Artem Muterko
48b5aa71f2 Refactor according to comments in PR (#4848) 2017-01-25 10:38:27 +00:00
Artem Muterko
9c8adb4812 Add couple of tests for compat module (#4845) 2017-01-24 12:50:35 +00:00
nmgeek
ab0c57718a Direct readers to info on how to add viewset docs (#4844)
I believe the original statement was wrong.  You can, in fact, document the various API endpoints of a ViewSet.
2017-01-24 09:57:14 +00:00
Mariusz Felisiak
6b399f1193 Fixed test_one_to_one_with_inheritance. Added required on_delete attribute to OneToOneField field. (#4838) 2017-01-24 09:56:46 +00:00
Mariusz Felisiak
df8f0c8de9 Fixed typo in .travis.yml. (#4842) 2017-01-24 09:24:18 +00:00
Ekwenugo Mirabel
217a81f19b Use correct label for username field in login template (#4841) 2017-01-24 09:07:32 +00:00
Mariusz Felisiak
5c0f9f147c Removed unnecessary utc wrapper. (#4839) 2017-01-23 16:22:32 +00:00
Artem Muterko
247954d497 Add tests for BasicAuthentication and TokenAuthentication (#4837)
* Add tests for BasicAuthentication

* Add tests for Token authentication

* Adjust test to pass on Django 1.8
2017-01-23 15:08:59 +00:00
José Padilla
d686b2cb15 Merge pull request #4834 from auvipy/slug
converted test asserts of relations slug to pytest
2017-01-20 15:42:20 -05:00
Asif Saifuddin Auvi
d2ae41529c fix wrong assert 2017-01-21 02:25:36 +06:00
Asif Saifuddin Auvi
63d8dc0b9b converted test asserts of relations slug to pytest 2017-01-21 02:14:33 +06:00
Artem Muterko
8043ff3fef Add test for urlquote_wrapper (#4832) 2017-01-20 20:09:47 +00:00
José Padilla
e21afbe750 Merge pull request #4833 from auvipy/hyper
converted test asserts of hyperlin relations to pytest
2017-01-20 14:51:59 -05:00
Asif Saifuddin Auvi
1ef334875f converted test asserts of hyperlin relations to pytest 2017-01-21 01:41:45 +06:00
José Padilla
2a64569006 Merge pull request #4830 from micgeronimo/routers-pytest
Refactor router tests to pytest style
2017-01-19 12:26:22 -05:00
Artem Muterko
0186b073bf Refactor router tests to pytest style 2017-01-19 18:00:07 +02:00
Luca
635dc03529 Parametrizable viewset custom views reverse name (#4821) 2017-01-19 15:20:34 +00:00
José Padilla
8844082d0b Merge pull request #4829 from micgeronimo/negotiation-tests
Negotiation tests
2017-01-19 08:39:32 -05:00
Artem Muterko
c2ce2fb3f0 Add tests for BaseContentNegotiation 2017-01-19 12:50:17 +02:00
Artem Muterko
076ca6e765 Add test for filter_renderers 2017-01-19 12:43:18 +02:00
Artem Muterko
46210205a4 Add tests for some template tags (#4815) 2017-01-18 20:41:32 +00:00
Artem Muterko
a8534baa41 Add remaining tests for validators (#4827) 2017-01-18 20:39:20 +00:00
Xavier Ordoquy
5e9249f429 Merge pull request #4824 from auvipy/newv
new matrix for python 3.6 and django 1.11
2017-01-18 17:24:44 +01:00
Asif Saifuddin Auvi
026a8d8707 make lint happy with isort --recursive 2017-01-18 22:15:44 +06:00
Asif Saifuddin Auvi
73a0a78fc6 allow failure for django 1.11 branch 2017-01-18 22:02:58 +06:00
Asif Saifuddin Auvi
006ae46092 remove trailing comma 2017-01-18 21:40:07 +06:00
Xavier Ordoquy
25049c48ba Merge pull request #4825 from manosim/include-drf-api-key
Include a link to the django-rest-framework-api-key package
2017-01-18 15:38:57 +01:00
Emmanouil Konstantinidis
81195aabbf Include a link to the django-rest-framework-api-key package 2017-01-18 14:36:43 +00:00
Asif Saifuddin Auvi
326e09dde9 added utc compat to tests of fields 2017-01-18 20:01:18 +06:00
Asif Saifuddin Auvi
bc3849bd59 added utc compat to fields 2017-01-18 19:31:04 +06:00
Asif Saifuddin Auvi
5717e853db fix import of utc 2017-01-18 19:28:57 +06:00
Asif Saifuddin Auvi
5436df54c6 added compat shim for utc/UTC 2017-01-18 19:06:41 +06:00
Asif Saifuddin Auvi
e2337e1072 restructure travis matrix 2017-01-18 18:17:19 +06:00
Asif Saifuddin Auvi
9268850db2 removed python 3.6 from global travis matrix 2017-01-18 18:07:15 +06:00
Artem Muterko
0a496a423d Add tests for qs_exists (#4822) 2017-01-18 11:46:12 +00:00
Asif Saifuddin Auvi
7d4706fbcc remved python3.4 for django master as 3.5 is the min 2017-01-18 14:04:30 +06:00
Asif Saifuddin Auvi
e50b223a31 resturctured supported python and django versions on travis 2017-01-18 14:01:31 +06:00
Asif Saifuddin Auvi
d75b7761c8 re organized supported django versions and releases 2017-01-18 13:54:42 +06:00
Artem Muterko
06a5bcc88e Add mediatype tests (#4813) 2017-01-16 18:17:51 +00:00
Artem Muterko
e965270f51 Template html renderer tests (#4817) 2017-01-16 18:16:43 +00:00
Ryan P Kilby
50c2d71a80 tox/travis maintenance (#4811)
* Use py36 on travis

* Remove basepython from tox

* Use py27 on travis

* Use version ranges for dependencies

* Use tox-travis to sync python/env factors

* Add toxenv/django env vars to codecov build vars

* Use raw string to fix py36 invalid escape sequence
2017-01-16 13:51:07 +00:00
Artem Muterko
41ac3565de Add test for delete field (#4819)
* Add test for delete field

* Remove unused import
2017-01-16 13:46:32 +00:00
Artem Muterko
514b5a6dd1 Add couple of test for AuthToken (#4816)
* Add couple of test for AuthToken

* PEP8 cleanup
2017-01-15 08:41:47 +00:00
José Padilla
5efbe17a86 Merge pull request #4808 from micgeronimo/pytest-cleanup
Refactor some tests to pytest style
2017-01-14 08:08:02 -05:00
Artem Muterko
ebd840c19f Revert several tests 2017-01-12 22:53:01 +02:00
Artem Muterko
c686749eef Throttle tests fix (#4810) 2017-01-12 17:53:48 +00:00
Artem Muterko
b4a9a1b9a3 Throttle tests (#4807) 2017-01-12 17:03:32 +00:00
Artem Muterko
9a6352789e Refactor request tests style 2017-01-12 18:41:27 +02:00
Artem Muterko
bd86104861 Refactor reverse tests style 2017-01-12 18:41:16 +02:00
Artem Muterko
401ab54275 Refactor schemas tests style 2017-01-12 18:33:24 +02:00
Asif Saifuddin Auvi
8fcb8d6350 converted metadata test asserts to pytest (#4806) 2017-01-12 08:21:15 +00:00
Artem Muterko
dd11bd42a2 Add remaining tests for SimpleRateThrottle (#4803) 2017-01-11 20:39:48 +00:00
Asif Saifuddin Auvi
14baf7eb7a converted serializer bulk update test asserts to pytest (#4805) 2017-01-11 20:38:32 +00:00
José Padilla
f67f2ab8af Merge pull request #4804 from micgeronimo/parser-tests-refactoring
Convert parser tests to pytest style
2017-01-11 14:44:21 -05:00
Artem Muterko
06afe6b1bf Convert tests to pytest style 2017-01-11 21:13:30 +02:00
Artem Muterko
66ffaaf5d3 Add more tests for Base and SimpleRate throttles (#4802) 2017-01-11 09:42:25 +00:00
Mitchel Humpherys
d6c6df40c6 docs: tutorial: Minor grammar "fix" (#4801) 2017-01-10 09:04:07 +00:00
Artem Muterko
e9d371f29a Add couple of basic tests for SimpleRateThrottle (#4800) 2017-01-09 20:43:54 +00:00
Artem Muterko
b6b2c4bb5b Renderer tests (#4791) 2017-01-08 16:33:43 +00:00
Artem Muterko
99d57df990 Convert encoders tests to pytest style (#4796) 2017-01-08 16:10:47 +00:00
Artem Muterko
4dd71d68d2 Remove extra parentheses (#4789) 2017-01-08 16:09:23 +00:00
Asif Saifuddin Auvi
44a99a11c3 update python and virtualenv versions in travis (#4795) 2017-01-08 16:08:07 +00:00
Asif Saifuddin Auvi
1880f6e0a4 added python3.6 on tox (#4794) 2017-01-08 16:06:06 +00:00
José Padilla
38aa1413a2 Merge pull request #4797 from micgeronimo/fix-typos
Fix several spelling errors
2017-01-08 09:28:46 -05:00
José Padilla
125f593e1d Merge pull request #4793 from auvipy/patch-1
updated version of test dependencies
2017-01-08 09:25:33 -05:00
Artem Muterko
773b68e188 Fix typos in Python files 2017-01-08 15:36:49 +02:00
Artem Muterko
b352c8a24c Fix some typos in documentation 2017-01-08 15:34:52 +02:00
Asif Saifuddin Auvi
d7c00e8b7a updated version of test dependencies
in test requirements text
2017-01-07 21:51:59 +06:00
wim glenn
e2c35920d1 fix a spelling error in api-guide (#4788) 2017-01-06 22:46:56 +00:00
Roman Vasilyev
64e801e479 get view for django 'virtual hosts' (#4776)
Brill, thanks! 👍
2017-01-06 22:46:36 +00:00
Artem Muterko
a5fcf10c0e Raise RuntimeError when trying to encode coreapi objects (#4790) 2017-01-06 22:32:13 +00:00
Tom Christie
cf3862d56d Update 3.0-announcement.md
Closes #4785
2017-01-06 07:24:28 +00:00
wim glenn
718764f591 add links to djangorestframework-queryfields to docs (#4786) 2017-01-06 06:40:50 +00:00
Xavier Ordoquy
3750aefb5d Merge pull request #4783 from vpetersson/doc_fix
Fixes documentation.
2017-01-05 13:31:12 +01:00
Viktor Petersson
eed8f5bb42 Fixes comment from @xordoquy. 2017-01-05 12:06:08 +00:00
Viktor Petersson
7ef6e96725 Fixes documentation.
Django==1.8.17 chokes on this unless it’s just `snippets`.
2017-01-05 11:14:57 +00:00
Xavier Ordoquy
20d4d790b2 Merge pull request #4782 from auvipy/patch-1
updated django minor versions
2017-01-05 11:41:58 +01:00
Asif Saifuddin Auvi
cd6acfcfcf updated django minor versions 2017-01-05 16:30:04 +06:00
José Padilla
559a0a89fc Merge pull request #4779 from auvipy/pyts0
converted throttling tests asserts to pytest
2017-01-04 10:31:44 -05:00
José Padilla
c524925e14 Merge pull request #4781 from auvipy/nego
converted negotiation tests asserts to pytest
2017-01-04 10:01:42 -05:00
Asif Saifuddin Auvi
88a910ebc8 converted negotiation tests asserts to pytest 2017-01-04 18:58:01 +06:00
Asif Saifuddin Auvi
6ca7f76c67 Merge branch 'master' into pyts0 2017-01-04 18:43:55 +06:00
Xavier Ordoquy
0f4cd2710c Merge pull request #4780 from auvipy/multi
converted multi-table-inheritence test asserts to pytest
2017-01-04 13:16:14 +01:00
Asif Saifuddin Auvi
43677b8baf flake8 fix 2017-01-04 17:54:14 +06:00
Asif Saifuddin Auvi
8fa5846e51 conerted multi-table-inheritence test asserts to pytest 2017-01-04 17:46:55 +06:00
Asif Saifuddin Auvi
a7d33f4519 conerted throttling tests asserts to pytest 2017-01-04 15:59:21 +06:00
Asif Saifuddin Auvi
7874bcabe9 convert some more test asserts to pytest (#4778)
* converted urlpatterns test asserts to pytest

* converted test utils asserts to pytest

* removed extra newlines
2017-01-04 09:13:32 +00:00
Ian Clark
eddc34f4c8 Add Serializer Extensions documentation (#4777) 2017-01-04 08:40:42 +00:00
Ryan P Kilby
11fd3bf108 Add disabling of declared fields on serializer subclasses (#4764)
* Add test for disabling declared fields on child
* Check that declared base field is not in attrs
* Update meta inheritance docs to include serializer
* Test that meta fields cannot be declared as None
* Add docs example for declarative field disabling
2017-01-03 21:14:19 +00:00
Xavier Ordoquy
8579683170 Merge pull request #4774 from iMakedonsky/master
modify documenting-your-api docs topic with additional package
2017-01-03 12:26:19 +01:00
Makedonsky
69366a11d7 modify documenting-your-api docs topic 2017-01-03 13:17:07 +02:00
Xavier Ordoquy
67e0090ea0 Merge pull request #4773 from rsinger86/flexfields-docs
added drf-flexfields addon info
2017-01-03 00:09:26 +01:00
robert
492444eb2e added drf-flexfields addon info 2017-01-02 17:03:03 -06:00
Xavier Ordoquy
6d48223a35 Merge pull request #4772 from nanuxbe/patch-2
Add DRF-Base64 to third-party serializers
2016-12-31 15:16:57 +01:00
Emmanuelle Delescolle
d98a0772d0 Add DRF-Base64 to third-party serializers
Add DRF-Base64, which provides serializers to handle base64-encoded files, to third-party serializers packages
2016-12-31 08:16:45 +01:00
José Padilla
56f0138bb9 Merge pull request #4766 from nanuxbe/patch-1
Add drf-schema-adapter to 3rd party metadata mods
2016-12-25 17:34:11 -04:00
Emmanuelle Delescolle
f1cbf51b43 Add drf-schema-adapter to 3rd party metadata mods 2016-12-25 10:06:47 +01:00
José Padilla
b52de0a871 Merge pull request #4762 from nikolas/patch-6
docs: typo fix: it's -> its
2016-12-22 17:00:54 -04:00
Nik Nyby
24e082b142 docs: typo fix: it's -> its 2016-12-22 12:44:43 -05:00
Matthew Medal
93fe531dea Breadcrumb view name suffix fix (#4750)
* add failing testcase for breadcrumb suffixes missing when using ModelViewSets

* fix get_breadcrumbs to honor overridden get_view_name and keep viewset suffixes

* ensure suffixes are appended in breadcrumb util
2016-12-20 22:19:00 +00:00
Christian Hess
f38734ef98 Add new line correctly in docstring sections (#4759)
The order of the line break was wrong
2016-12-20 16:26:18 +00:00
Masashi SHIBATA
c2367fb017 Fix documentation's sample code in API Guide (#4756) 2016-12-17 13:00:29 +00:00
Eduard Iskandarov
ebe174c0d7 add per-view custom exception handler support (#4753) 2016-12-15 12:36:40 +00:00
José Padilla
ecb905267f Merge pull request #4752 from ByteInternet/document-drf-oidc-auth
Add drf-oidc-auth to docs
2016-12-14 16:24:36 -05:00
Allard Hoeve
0175ea4809 Add drf-oidc-auth to 3rd party mods 2016-12-14 20:15:39 +01:00
Tom Christie
89d22942a6 Add missing docs on RequestsClient. Closes #4747. 2016-12-12 10:08:54 +00:00
Tom Christie
7ecd4f7813 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2016-12-09 16:07:11 +00:00
Tom Christie
38bde343f8 Update sponsor link 2016-12-09 16:06:59 +00:00
Xavier Ordoquy
2230784fab Merge pull request #4745 from auvipy/authtest
converted authentication test asserts to pytest
2016-12-06 08:15:27 +01:00
Asif Saifuddin Auvi
841a91e950 fix authentication_test pytest failure 2016-12-06 00:47:58 +06:00
Asif Saifuddin Auvi
85807e1958 converted authentication_test asserts to pytest 2016-12-06 00:33:13 +06:00
Xavier Ordoquy
792b50feee Merge pull request #4738 from netsyno/master
Updated Link ti Django Docs
2016-12-05 11:38:55 +01:00
Daniel Rech
761d53e923 Updated Link ti Django Docs
The Url to the settings/#caches Link changed in Django documentation.
2016-12-05 11:36:03 +01:00
Raphael Pierzina
238783f2ed Change DEFAULT_PERMISSION_CLASSES to a list in quickstart.md (#4733) 2016-12-02 17:01:37 +00:00
Asif Saifuddin Auvi
932d04a4be Browsable API tests asserts to pytest (#4725) 2016-12-01 16:17:36 +00:00
Carlton Gibson
16f5d42cbc Add additional link to HTML & Forms topic page (#4726)
Just makes the topic page easier to find.

Closes #1673
2016-12-01 09:11:25 +00:00
Xavier Ordoquy
22578525ef Documentation update (#4717) 2016-11-30 12:58:34 +00:00
Asif Saifuddin Auvi
4f6c326a99 converted remaining unittes asserts of fields test to pytest (#4724) 2016-11-30 12:52:32 +00:00
Asif Saifuddin Auvi
1a741bb2a2 converted asserts of exceptions test to pytest (#4723) 2016-11-30 11:12:01 +00:00
Xavier Ordoquy
6e30dc75e0 Merge pull request #4722 from auvipy/pytest7
converted descriptions and ecoders test asserts to pytest
2016-11-30 12:00:29 +01:00
Asif Saifuddin Auvi
7e8b01dbd2 converted asserts of encoders test to pytest 2016-11-30 16:45:48 +06:00
Asif Saifuddin Auvi
9a3f8d9a9c converted asserts of descriptions test to pytest 2016-11-30 16:42:43 +06:00
Xavier Ordoquy
01cd09155b Merge pull request #4721 from auvipy/pytest6
converted asserts of atomic requests and decorators tests to pytest
2016-11-30 11:34:02 +01:00
Asif Saifuddin Auvi
a9b6c97485 converted asserts of decorators test to pytest 2016-11-30 16:24:48 +06:00
Asif Saifuddin Auvi
504f4b44c6 converted asserts of atomic requests test to pytest 2016-11-30 16:17:30 +06:00
Asif Saifuddin Auvi
e03d88ced7 more pytest style assert (#4719) 2016-11-30 09:48:33 +00:00
Xavier Ordoquy
4c41f2bfea Merge pull request #4715 from auvipy/pytest4
converted test asserts of generics-test to pytest
2016-11-30 07:53:58 +01:00
Asif Saifuddin Auvi
10b5f36fec added fixes 2016-11-30 12:35:34 +06:00
Xavier Ordoquy
f2a8252660 Merge pull request #4718 from jfw/patch-4
typo
2016-11-30 07:35:22 +01:00
Asif Saifuddin Auvi
f5a900a404 some reverts to fix test 2016-11-30 10:01:37 +06:00
Asif Saifuddin Auvi
a5bb9825f3 attempt to fix test again 2016-11-30 09:56:22 +06:00
Jeff Fein-Worton
a5c8a8c226 typo 2016-11-29 18:00:10 -08:00
Asif Saifuddin Auvi
4a0829d6ec attempt to fix test 2016-11-30 02:08:37 +06:00
Asif Saifuddin Auvi
27641e07b5 converted test asserts of generics-test to pytest 2016-11-30 01:13:21 +06:00
Germán Larraín
aed8387e05 docs: Fix description of DecimalField's max_digits (#4714)
As of PR #4377, `max_digits=None` is allowed for `DecimalField`.
2016-11-29 15:35:43 +00:00
Xavier Ordoquy
1e0988686c Update the Python doc links to use https and point to Python 3 (#4713) 2016-11-29 12:27:00 +00:00
Ryan P Kilby
6498766749 Fix django deprecation warnings (#4712) 2016-11-29 09:49:18 +00:00
Asif Saifuddin Auvi
9f4c9691f4 converted filters tests asserts to pytest style (#4711) 2016-11-28 14:31:27 +00:00
Asif Saifuddin Auvi
42d6098c74 converted primary key relations test asserts to pytest (#4709) 2016-11-28 09:43:48 +00:00
Xavier Ordoquy
ea8fc99d6a Merge pull request #4708 from auvipy/pytest2
converted generic relations assert to pytest style
2016-11-28 07:40:20 +01:00
Asif Saifuddin Auvi
cd3fd36d0e converted generic relations assert to pytest style 2016-11-27 23:55:09 +06:00
Nik Nyby
abc62afddb docs typo fix (#4701)
Remove unnecessary "a"
2016-11-24 09:39:18 +00:00
Nik Nyby
eaec60ae1d docs: grammar fix - it's -> its (#4698) 2016-11-23 16:10:39 +00:00
Xavier Ordoquy
36552eb5fe Merge pull request #4699 from nikolas/patch-4
docs: grammar fix
2016-11-23 16:19:02 +01:00
Nik Nyby
a13b8d5560 docs: grammar fix 2016-11-23 10:13:03 -05:00
Asif Saifuddin Auvi
5ec223bca0 converted validators and write_only_fields test to pytest style (#4697) 2016-11-23 14:05:34 +00:00
Asif Saifuddin Auvi
4b59ec27fa convert tests asserts to pytest style (#4696) 2016-11-23 13:17:00 +00:00
Carlton Gibson
3e1b31bb9b Merge pull request #4694 from auvipy/patch-1
update django-filter to version 1.0.0
2016-11-23 11:20:12 +01:00
Xavier Ordoquy
f0872a6201 Merge pull request #4695 from vinayan3/patch-1
Edit to the import in Setting filter backends
2016-11-23 07:47:29 +01:00
Vinay Anantharaman
8030f5b74f Edit to the import in Setting filter backends
`django_filters` doesn't export `rest_framework` by default so it's required to import it.
2016-11-22 14:50:47 -08:00
Asif Saifuddin Auvi
1b9013ebae update django-filter to version 1.0.0 2016-11-22 19:46:12 +06:00
Thodoris Sotiropoulos
4c2d6b9bb7 Do not ignore source when building fields dynamically
This commit fixes the issue when you set the keyword argument `source`
and your have not set the serializer fields explicitly. Then the
construction of field failed because there is not actually any model
field with that name.

However, you are still able to imply the name of model field by
providing the `source` keyword argument.
2016-11-17 18:51:22 +02:00
Xavier Ordoquy
45e90c3398 Merge pull request #4679 from browniebroke/exceptions-docs-typo
Correct a small typo in exceptions documentation
2016-11-14 18:03:30 +01:00
Bruno Alla
0c02bbbfa7 Correct a small typo in exceptions documentation 2016-11-14 16:58:16 +00:00
Tom Christie
24791cb353 Invalidate any existing prefetch cache on PUT requests. (#4668) 2016-11-11 09:44:35 +00:00
Tom Christie
8bab7f8d58 Only apply the nested writes test to writable fields. (#4669) 2016-11-10 16:36:56 +00:00
Michael Barr
388cf7622c Adds Django/Python Trove Classifiers (#4662) 2016-11-09 12:59:11 +00:00
Tom Christie
ea60872e9e Version 3.5.3 [ci skip] 2016-11-07 13:38:48 +00:00
Tom Christie
8d72535be9 Fix FilterSet warnings. (#4660) 2016-11-07 12:55:18 +00:00
Rex Salisbury
06df61e38c handle error when no links are found (#4649)
This is to address https://github.com/tomchristie/django-rest-raml/issues/5

The problem is that if you try to generate RAML docs when you haven't set up any views, you get the above error (min called on an empty list).  

unfortunately, this PR is not very helpful since it doesn't actually surface a readable error to the user.  Not sure what the best way to address this would be...
2016-11-07 11:41:10 +00:00
Angel Velasquez
ee60aaa945 Update versions of Django on tox.ini (#4651)
Bump release versions to 1.10.3, 1.9.11 and 1.8.16

More info on:

https://www.djangoproject.com/weblog/2016/nov/01/security-releases/
2016-11-07 11:37:58 +00:00
James Beith
befacfb00d Add autofocus support for input.html templates (#4650)
This change adds support to use `'autofocus': True` in the style options and have the `autofocus` attribute included on the input field when rendered.
2016-11-07 11:34:53 +00:00
Aaron Lelevier
0b9304014d Add documentation link for single 'field-level validation' to the Validator docs page (#3772) (#4657) 2016-11-07 11:30:46 +00:00
pkrzyzaniak
7f437123bd Added "drf_tweaks" to third party packages (#4659) 2016-11-06 22:12:52 +00:00
Carlos de la Torre
d55e176a1e Fix documentation error: removed unused variable (#4647) 2016-11-02 14:03:53 +00:00
Andrzej Pragacz
45e058d7ba Fix unhandled Http404, PermissionDenied in schema generation (#4645) (#4646) 2016-11-02 09:04:01 +00:00
Tom Christie
2bf082a623 Version 3.5.2 [ci skip] (#4641) 2016-11-01 11:31:20 +00:00
Tom Christie
276ed80fd3 Support 'on'/'off' literals with BooleanField. Closes #4624 (#4640) 2016-11-01 11:11:34 +00:00
Kennedy Mwenja
7038571157 Enable cursor pagination of value querysets. (#4569)
To do `GROUP_BY` queries in django requires one to use `.values()`
eg this groups posts by user getting a count of posts per user.

```
Posts.objects.order_by('user').values('user').annotate(post_count=Count('post'))
```

This would produce a value queryset which serializes its result
objects as dictionaries while `CursorPagination` requires a queryset
with result objects that are model instances.

This commit enables cursor pagination for value querysets.

- had to mangle the tests a bit to test it out. They might need
  some refactoring.
- tried the same for `.values_list()` but it turned out to be
  trickier than I expected since you have to use tuple indexes.
2016-11-01 10:42:01 +00:00
Nicolas Delaby
97d848413e Fix support of get_full_details() for Throttled exceptions (#4627)
Since `str` objects are immutable, appending to existing `str` creates
in fact a new `str` instance.

Thus `ErrorDetail.detail.code` attribute is lost after `str` concatenation operation.
2016-11-01 10:38:56 +00:00
Kieran Spear
98df932194 Fix FilterSet proxy (#4620) 2016-11-01 10:30:17 +00:00
Ryan P Kilby
d92b24a0b7 Make serializer fields import explicit (#4628) 2016-11-01 10:27:11 +00:00
Tom Christie
5c54b227c1 Drop redundant requests adapter (#4639) 2016-11-01 10:24:53 +00:00
Tom Christie
7eb6cdca00 Don't lose exception info (#4638) 2016-11-01 10:22:30 +00:00
Alex Kahan
895c67c9a2 Fixes #4532 (#4636) 2016-10-31 20:41:54 +00:00
Josep Cugat
46f837a9d1 Fix APIException full_details() typo in documentation (#4633)
APIException has a get_full_details() method but the documentation refers to full_details().
2016-10-28 12:05:32 +01:00
Ryan P Kilby
eafc9a2393 Fix is_simple_callable with variable args, kwargs (#4622) 2016-10-25 20:47:24 +01:00
José Padilla
1bd35ad355 Merge pull request #4617 from tuffnatty/docs-pagination-add-drf-proxy-pagination
Add `drf-proxy-pagination` reference to Pagination docs
2016-10-23 09:46:57 -04:00
Phil Krylov
72dc6d1d5c Add drf-proxy-pagination reference to Pagination docs 2016-10-23 04:36:36 +03:00
Mads Jensen
8ac524915c added on_delete=models.CASCADE to models.ForeignKey in the documentation (#4614) 2016-10-22 16:37:23 +01:00
Tom Christie
3b39d2d13a Version 3.5.1 [ci skip] 2016-10-21 17:10:38 +01:00
Tom Christie
30bf9df5d0 Fix guardian import (#4612) 2016-10-21 16:59:43 +01:00
Tom Christie
0fe0e1e703 Fix schema base paths (#4611) 2016-10-21 16:59:34 +01:00
Tom Christie
d647d37a99 Fix Accept header in tutorial. Closes #4604. [ci skip] 2016-10-21 15:45:28 +01:00
Tom Christie
f1bdce17b5 Fix for case of ListSerializer with single item (#4609) 2016-10-21 15:21:23 +01:00
Lukasz Karolewski
0b346e94b1 changing order of imports (#4601)
when using with django-filter and rest_framework_swagger need to import coreapi before django-filter as django filter tries to load rest_framework.coreapi which is undefined at this point
2016-10-21 15:00:25 +01:00
Tom Christie
e3686aca93 Don't use bare 'raise'. [ci skip] 2016-10-21 14:47:26 +01:00
Tom Christie
856f086ce3 Remove broken wheel check in setup.py [ci skip] 2016-10-21 14:42:42 +01:00
Maxime Lorant
1aa6dff0b5 Fix code formatting missing in 3.5 announcement (#4597)
... in section ModelSerializer 'fields' and 'exclude'
2016-10-20 16:47:59 +01:00
Tom Christie
c6f1686571 Remove erronous file [ci skip] 2016-10-20 16:26:56 +01:00
Tom Christie
3b9afb571b Version 3.5.0 (#4596) 2016-10-20 16:25:40 +01:00
Tom Christie
2395fb5386 Deprecate DjangoFilter backend (#4593)
Deprecate the built-in `rest_framework.filters.DjangoFilterBackend` in favour of the third-party `django_filters.rest_framework.DjangoFilterBackend`.
2016-10-20 10:47:09 +01:00
Tom Christie
3f6004c5a9 Use pk for URL conf and views. (#4592) 2016-10-20 09:42:40 +01:00
Xavier Ordoquy
f9cf237e0b Merge pull request #4590 from zwernberg/patch-1
Fixed minor sentence in Filter.py filter_queryset() Comment
2016-10-19 09:01:42 +02:00
Zach Wernberg
fcff16c5c6 minor typo 2016-10-18 23:14:55 -05:00
Fa773N M0nK
d5e63d2d7f Reflect that '@detail_route' responds to GET only by default. (#4582) 2016-10-18 11:06:04 +01:00
Alex Poleha
a83997e1ed Removed incorrect line from generic-views.md (#4583) 2016-10-14 11:29:48 +01:00
Akshay Sharma
cca9792ae7 contributing.md django fix. (#4581)
* installation for django added in requirements.txt
* added line to install django first in contributing.md

* added line to install django first in contributing.md and CONTRIBUTING.md
2016-10-14 11:20:09 +01:00
Tom Christie
de08f28a91 Test one to one with inheritance (#4575) 2016-10-13 14:21:23 +01:00
Tom Christie
8d0a91b002 Fix 3674 (#4571)
Handle ModelSerializer case for relationships to models with custom pk.
2016-10-13 12:43:43 +01:00
Tom Christie
88c6c380c5 Use field.source to perform check for writable nested field, not key (#4568) 2016-10-12 16:51:01 +01:00
Alexey Evseev
2519ce9128 Fix schema generation with custom page_size pagination param (#4567) 2016-10-12 16:09:45 +01:00
Tom Christie
5677d063d8 Do not treat empty non-form input as HTML. (#4566) 2016-10-12 15:46:24 +01:00
Tom Christie
26e51ecd6c When HTML form input is used with JSONField, treat the input as a JSON encoded string, not a JSON primative. (#4565) 2016-10-12 14:04:10 +01:00
Tom Christie
b419970431 Handle empty data with serializer (#4564) 2016-10-12 10:47:17 +01:00
Tom Christie
4c9b14bd97 Add --minimum-perc to transifex pull command [ci skip] 2016-10-12 10:13:46 +01:00
Tom Christie
11a89ebff4 Removous erronous duplicate Danish translation file (#4563) 2016-10-12 10:02:21 +01:00
SerenityCode
02fcf6a334 Use field name instead of source when generating docs (#4559) 2016-10-12 09:46:59 +01:00
Tom Christie
7f29cfc931 Lazy hyperlink names (#4554) 2016-10-11 12:18:00 +01:00
Tom Christie
d0b3b6470a Fix prefetch_related updates. (#4553) 2016-10-11 11:07:40 +01:00
Akshay Sharma
aed4ed5e73 Browsable API navbar gets overlapped by highlighted pagination item fix (#4547) 2016-10-11 10:59:00 +01:00
Tom Christie
a3802504a0 Error codes (#4550)
Add error codes to `APIException`
2016-10-11 10:25:21 +01:00
Xavier Ordoquy
5f6ceee7a5 Merge pull request #4552 from duoi/master
Corrected `artist` and `album_name` typo in docs
2016-10-11 07:55:37 +02:00
Steven Johns
072d14c2e1 Corrected artist and album_name
`The Roots` are the band: https://en.wikipedia.org/wiki/The_Roots

`Undun` is their album: https://en.wikipedia.org/wiki/Undun
2016-10-11 11:20:48 +11:00
Tom Christie
0dec36eb41 Version 3.5 (#4525)
* Start test case

* Added 'requests' test client

* Address typos

* Graceful fallback if requests is not installed.

* Add cookie support

* Tests for auth and CSRF

* Py3 compat

* py3 compat

* py3 compat

* Add get_requests_client

* Added SchemaGenerator.should_include_link

* add settings for html cutoff on related fields

* Router doesn't work if prefix is blank, though project urls.py handles prefix

* Fix Django 1.10 to-many deprecation

* Add django.core.urlresolvers compatibility

* Update django-filter & django-guardian

* Check for empty router prefix; adjust URL accordingly

It's easiest to fix this issue after we have made the regex.  To try
to fix it before would require doing something different for List vs
Detail, which means we'd have to know which type of url we're
constructing before acting accordingly.

* Fix misc django deprecations

* Use TOC extension instead of header

* Fix deprecations for py3k

* Add py3k compatibility to is_simple_callable

* Add is_simple_callable tests

* Drop python 3.2 support (EOL, Dropped by Django)

* schema_renderers= should *set* the renderers, not append to them.

* API client (#4424)

* Fix release notes

* Add note about 'User account is disabled.' vs 'Unable to log in'

* Clean up schema generation (#4527)

* Handle multiple methods on custom action (#4529)

* RequestsClient, CoreAPIClient

* exclude_from_schema

* Added 'get_schema_view()' shortcut

* Added schema descriptions

* Better descriptions for schemas

* Add type annotation to schema generation

* Coerce schema 'pk' in path to actual field name

* Deprecations move into assertion errors

* Use get_schema_view in tests

* Updte CoreJSON media type

* Handle schema structure correctly when path prefixs exist. Closes #4401

* Add PendingDeprecation to Router schema generation.

* Added SCHEMA_COERCE_PATH_PK and SCHEMA_COERCE_METHOD_NAMES

* Renamed and documented 'get_schema_fields' interface.
2016-10-10 13:03:46 +01:00
Manjit Kumar
d49e26f127 add drf-url-filters in third party filtering resources and fixed typo (#4548) 2016-10-10 12:35:38 +01:00
Camille Harang
e99b30d28b Fix rest_framework.filters.OrderingFilter doesn't pass context to ser… (#4543)
* Fix rest_framework.filters.OrderingFilter doesn't pass context to serializers #4541

* #4541 Additional fix for remove_invalid_fields()
2016-10-10 11:59:02 +01:00
Alex Kahan
4ff9e96b4c Adding tests to encoder.py (#4536) 2016-10-05 09:54:59 +01:00
Alex Kahan
915ac22aeb Adding tests for rest_framework.py (#4523) 2016-10-04 21:22:56 +01:00
Rowan Seymour
883efbc19f Case insensitive uniqueness validation (#4534) 2016-10-04 13:44:50 +01:00
Xavier Ordoquy
0b373be712 Merge pull request #4531 from angvp/update-tox
Update Django security release 1.10.2
2016-10-02 10:29:09 +02:00
Angel Velasquez
b8fcb7807a Update Django security release 1.10.2 2016-10-02 03:11:40 -03:00
Danilo Bargen
1b882f7281 Add drf-dynamic-fields to third party packages (#4530) 2016-09-30 17:06:36 +01:00
Manjit Kumar
73fd1ff4e7 add drf-url-filters app to django-rest-framework in filtering docs (#4528)
- enabling validtions on incoming query params with the ease of adding new filters as easy as adding a new key in a dict.
2016-09-30 12:02:23 +01:00
Tom Christie
1c23b0392e Merge branch 'master' of github.com:tomchristie/django-rest-framework 2016-09-29 21:29:31 +01:00
Tom Christie
e7fd166048 Docs tweaks 2016-09-29 21:29:21 +01:00
Xavier Ordoquy
12576275c4 Merge pull request #4519 from jpadilla/master
Update Django security releases 1.9.10 and 1.8.15
2016-09-28 09:16:46 +02:00
José Padilla
38aa0ac281
Update Django security releases 1.9.10 and 1.8.15 2016-09-28 00:05:22 -04:00
Dmitry Dygalo
b82ec540ad Remove code for old Django versions (#4513) 2016-09-23 23:03:02 +01:00
Tom Christie
7ab4a587d9 Version 3.4.7 (#4501) 2016-09-21 12:24:26 +01:00
Tom Christie
be74d11165 Fallback behavior for request parsing when request.POST already accessed. (#4500) 2016-09-21 11:49:09 +01:00
Xavier Ordoquy
e82ee91078 Merge pull request #4497 from knaperek/fix-readme-token-model-name
Rename an invalid reference to BasicToken in the docs
2016-09-19 22:43:47 +02:00
Jozef Knaperek
76cc2f0319
Rename an invalid reference to BasicToken in the docs 2016-09-19 21:52:06 +02:00
Ollie Ford
fe96ceced0 fixes response rendering with empty context (#4495)
This commit allows `response.render` to be called when
`response.rendered_context == {}`. This should be allowed, since
if [the JSONRenderer, for example](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/renderers.py#L85-L92) receives a `None` context, it
sets it to an empty dictionary itself.
2016-09-17 03:13:34 +01:00
Tanner Hobson
fe4c4fa751 Fix indentation regression in API listing (#4493)
In commit 5392be4ddb, there was a change
made when cleaning up the template for the API listing that caused 2
spaces to appear before every header item (except the first) and before
the first line of the body of the response. This meant that it often
looked like:

HTTP 200 OK
  Allow: GET, OPTIONS
  Content-Type: application/json
  Vary: Accept

  {
    "key": "value",
    "key2": "value2"
}

This change removes those leading spaces, so that it will now look like:

HTTP 200 OK
Allow: GET, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "key": "value",
    "key2": "value2"
}
2016-09-17 03:09:49 +01:00
Tom Christie
4655501d51 Fix regression of RegexField. (#4490)
* Don't deepcopy 'regex' arguments, instead treat as immutable.
2016-09-15 12:44:45 +01:00
Jeff Willette
a68b37d8bc Update to correct location of reverse relation doc (#4481) 2016-09-13 09:31:48 +01:00
Xavier Ordoquy
e91ffc87cb Ignore empty args in the MultipleFieldLookupMixin definition - Closes #4484 2016-09-13 07:21:10 +02:00
José Padilla
6b6f319509 Add missing comma (#4473) 2016-09-08 14:01:26 +01:00
TakesxiSximada
5df54a711f Set a view function's __module__ value to the WrappedAPIView object's __module__ (#4465) 2016-09-05 11:16:41 +01:00
Mathieu Pillard
07efbdb45e Fix APIClient.get() when path contains unicode arguments (#4458) 2016-09-02 17:00:03 +01:00
Jakub Moliński
80bd3b9722 [documentation] Throttling random request code example fix (#4451) 2016-08-30 10:37:48 +01:00
Tom Christie
b683cd7afc Update sponsor info [ci skip] 2016-08-25 22:29:38 +01:00
Tom Christie
f7b4511715 Update sponsor info [ci skip] 2016-08-25 22:27:51 +01:00
dfavato
ec4761225e Set self.count before self.limit in LimitOffsetPagination
By doing this it is possible to override get_limit in order to return all records if the request has a predefined param.

For example, if one wants that all records are retrieved if url has &limit=-1, get_limit could return self.count in this case.

Otherwise, if self.count is set after self.limit then, to achive the same result, one has to override get_limit and paginate_queryset, or run get_limit twice.
2016-08-23 14:52:20 -03:00
Tom Christie
f064ec6ac6 Version 3.4.6 (#4436) 2016-08-23 16:59:47 +01:00
Tom Christie
97806f9724 Add missing comma 2016-08-23 09:46:03 +01:00
José Padilla
d0ed482d70 Skip HiddenField from Schema fields (#4429) 2016-08-22 16:53:53 +01:00
orf
d540f0262b Improve Create to show the original exception traceback (#3508) 2016-08-19 14:42:13 +01:00
Tom Christie
a335309b33 Add __str__ method to PKOnlyObject (#4423) 2016-08-19 14:37:27 +01:00
Tom Christie
63342e81db Version 3.4.5 (#4421) 2016-08-19 12:45:20 +01:00
Robert Jensen
59ca61abcd Add django-rest-framework-roles to third party packages in permissions docs (#4417) 2016-08-19 11:44:31 +01:00
Tom Christie
382ea770b5 Improve debug error handling (#4416) 2016-08-18 14:42:15 +01:00
Tom Christie
b76984d222 Allow custom CSRF_HEADER_NAME setting. (#4415) 2016-08-18 11:24:03 +01:00
nevun
966330a85a Replace utf8 character ' with its ascii counterpart, makes bdist_rpm.py happy on centos7 (#4412) 2016-08-17 19:42:40 +01:00
Tom Christie
e3f8d06baf Include .action attribute on viewsets when generating schemas (#4408) 2016-08-15 17:10:55 +01:00
Tom Christie
101fd29039 Do not include uploads in request.POST (#4407) 2016-08-15 16:53:17 +01:00
Tom Christie
785b206b81 Tweak doctsring. Closes #4404 [ci skip] 2016-08-15 16:21:51 +01:00
James Beith
075a0bde5a Fix template syntax error for as_list_of_strings (#4403) 2016-08-15 09:28:46 +01:00
José Padilla
b508bc8da6 Merge pull request #4396 from wimglenn/docs_bugfix
fix a b0rked code example in the permissions section of api guide
2016-08-12 21:22:35 -04:00
Wim Glenn
0a48d21e09 fix a b0rked code example in the permissions section of api guide 2016-08-12 14:33:35 -05:00
Tom Christie
964f82528c Tweak formatting in release notes [ci skip] 2016-08-12 12:13:56 +01:00
Tom Christie
a7525d838a Version 3.4.4 (#4395) 2016-08-12 12:08:25 +01:00
Tom Christie
ae720d9bde Fix issue with generating categories for schema endpoints (#4394) 2016-08-12 10:58:47 +01:00
Neil Parsons
7466b61e62 Don't strip empty query params when paginating (#4260) 2016-08-12 10:50:16 +01:00
Leonid Shvechikov
1d26b398ad Fix comment for SerializerMethodField.bind method (#4389)
It seems that the example was copy&pasted and not updated properly.
2016-08-11 22:15:21 +01:00
Tom Christie
ebf43346a1 Do not re-run query for empty results with LimitOffsetPagination (#4388) 2016-08-11 16:54:55 +01:00
Tom Christie
1312acaf8b Minor docs update [ci skip] 2016-08-11 16:53:34 +01:00
Tom Christie
116917dbed Add form field descriptions to schemas (#4387) 2016-08-11 16:18:33 +01:00
Tom Christie
01b498ec51 Fix schema categories for custom list actions (#4386) 2016-08-11 14:07:40 +01:00
Tom Christie
b50d8950ee Pass request to schema generation (#4383)
Pass request to schema generation
2016-08-11 11:27:28 +01:00
Kyle Hornberg
3698d9ea2e Update permissions.md (#4381) 2016-08-10 17:23:10 +01:00
Tom Christie
f16e880167 Stricter type validation for CharField. (#4380)
Stricter type validation for CharField
2016-08-10 17:22:19 +01:00
Tom Christie
f1a2eeb818 .choices property of RelatedField should preserve non-string values. (#4379)
Update RelatedField.choices to support non-string values
2016-08-10 16:38:59 +01:00
Tom Christie
9857cd9889 Add failing test for issue #3868 (#4378) 2016-08-10 16:04:32 +01:00
Akhil Lawrence
fa4ce50be7 Modified exception handler to throw django error page in case of 500 error (#4172)
Show Traceback HTML in browsable API
2016-08-10 15:24:32 +01:00
Daniel Hahler
378b04eeaa Fix handling of ALLOWED_VERSIONS and no DEFAULT_VERSION (#4370)
When only `ALLOWED_VERSIONS` but no `DEFAULT_VERSION` is specified, a
version should be enforced.
2016-08-10 15:19:56 +01:00
Tom Christie
48f3db36d6 Allow optional max_digits on DecimalField (#4377) 2016-08-10 14:39:26 +01:00
Tom Christie
2d43b17f9a Limit queryset when rendering relational choices. (#4375)
Limit querysets to html_cutoff when rendering relational choices
2016-08-10 13:01:10 +01:00
Tom Christie
8105a4ac5a Resolve form display with ChoiceField, MultipleChoiceField and non-string choices. (#4374)
* Add tests for html-form-rendering choice fields
* Resolve issues with ChoiceField, MultipleChoiceField and non-string options
* Ensure None template comparisons don't match string None
2016-08-10 12:02:33 +01:00
Tom Christie
0781182646 Fix call to .resolve_context (#4371) 2016-08-09 17:48:29 +01:00
Dmitry Dygalo
e1768bdc16 Fixed various typos (#4366) 2016-08-08 09:32:22 +01:00
Tom Christie
febaa4db00 Add import in docs. [ci skip] 2016-08-08 09:28:15 +01:00
José Padilla
e7eccac6df Merge pull request #4363 from mcastle/patch-2
Fix minor typo
2016-08-05 15:37:55 -04:00
Marlon
672e5a0f96 Fix minor typo 2016-08-05 11:57:43 -07:00
Tom Christie
bb613c5ad1 Version 3.4.3 (#4361)
* Version 3.4.3
2016-08-05 13:33:25 +01:00
Tom Christie
35320b1f2d Add bullet points to release notes [ci skip] 2016-08-05 12:41:15 +01:00
Tom Christie
f9cf22edc8 Version 3.4.2 (#4360) 2016-08-05 12:38:19 +01:00
Tom Christie
d5178c9246 Include kwargs passed to 'as_view' when generating schemas (#4359) 2016-08-05 11:19:39 +01:00
Tom Christie
11a2468379 Access request.user.is_authenticated as property not method, under Django 1.10+ (#4358)
* For Django >=1.10 use user.is_authenticated, not user.is_authenticated()
2016-08-05 11:04:01 +01:00
Tom Christie
aff146ae83 Filter HEAD out from schemas (#4357) 2016-08-05 10:23:40 +01:00
Corentin Smith
54096dc22f Add imports in validators docs (#4355) 2016-08-04 22:06:35 +01:00
Tom Christie
a9a097496e extra_kwargs takes precedence over uniqueness kwargs (#4349) 2016-08-02 14:33:15 +01:00
Tom Christie
5500b265bc Test cases for DictField with allow_null options (#4348) 2016-08-02 14:14:36 +01:00
Tom Christie
bda16a518a Dedent tabs. (#4347) 2016-08-02 13:33:14 +01:00
René Fleschenberg
9f5e841daf Change template context generation in TemplateHTMLRenderer (#4236)
- Change the name of ``resolve_context()`` to ``get_template_context()``.
- Pass the renderer context to this method, to give subclasses more flexibility
  when overriding.
2016-08-02 13:11:41 +01:00
Tom Christie
e37619f741 Serializer defaults should not be included in partial updates. (#4346)
Serializer default values should not be included in partial updates
2016-08-02 13:05:12 +01:00
Tom Christie
296e47a9f8 Update from Django 1.10 beta to Django 1.10 (#4344) 2016-08-02 10:23:56 +01:00
Tom Christie
3ef3fee926 Descriptive error from FileUploadParser when filename not included. (#4340)
* Descriptive error from FileUploadParser when filename not included.
* Consistent handling of upload filenames
2016-08-01 18:44:58 +01:00
Tom Christie
46a44e52aa Quantize incoming digitals (#4339) 2016-08-01 17:15:41 +01:00
Tom Christie
aa349fe767 Handle non-string input for IP fields (#4338) 2016-08-01 16:14:26 +01:00
jsurloppe
e997713313 urljoin with leading slash remove part of path (#4332) 2016-08-01 14:14:55 +01:00
Jaap Roes
5b071ab35e Remove note about Django 1.3 (#4334)
Remove note about Django 1.3
2016-08-01 12:05:47 +01:00
Tom Christie
48a2f084aa Minor docs tweak [ci skip] 2016-07-28 13:38:05 +01:00
Tom Christie
449ec1d724 Version 3.4.1 [ci skip] (#4326) 2016-07-28 13:34:35 +01:00
Tom Christie
e407dc7f01 Added root_renderers argument (#4323) 2016-07-28 12:50:51 +01:00
Tom Christie
306726d9e8 Improve datetime format docs (#4322) 2016-07-28 12:25:21 +01:00
Tom Christie
061e0ed084 Added url and schema_url arguments (#4321) 2016-07-28 12:08:34 +01:00
Tom Christie
6a7d34ec34 Unique together checks should apply to fields that are read only, but have a default. (#4316) 2016-07-27 15:40:04 +01:00
Tom Christie
1acbc29d58 Minor style tweak. [ci skip] 2016-07-27 15:39:46 +01:00
Alexander Gaevsky
46a870c002 Fix schema generation for APIView, since it does not have get_serializer_class method. (#4285) 2016-07-27 15:36:36 +01:00
Tom Christie
3586c8a61a Set view.format_kwarg in schema generator (#4315) 2016-07-27 14:43:45 +01:00
Tom Christie
8ebf81b150 Schema support should function when 'pagination_class = None' (#4314) 2016-07-27 13:02:48 +01:00
Tom Christie
351e0a4a99 Fix json indent parameter. Closes #4281 (#4313) 2016-07-27 11:49:01 +01:00
Tom Christie
f9df0dc965 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2016-07-26 16:45:37 +01:00
Tom Christie
19b415ec25 Improve pagination docs. Refs #4304 [ci skip] 2016-07-26 16:45:27 +01:00
Tom Christie
5d3b56f957 Test case for #4272 (#4310)
* Test case for #4272
2016-07-26 16:28:10 +01:00
Sassan Haradji
f0f61aa077 use verbose_name instead of object_name in field_mapping (#4299)
* use verbose_name instead of object_name in error messages
2016-07-26 15:12:51 +01:00
Asif Saifuddin Auvi
b63099084f twitter bootstrap minor update (#4307)
* updated bootstrap min css to 3.3.7
* updated bootstrap min javascript to 3.3.7
2016-07-26 14:09:04 +01:00
Gustavo Pantuza
da2ff1bc4a Adding support for RFC 4918 status codes (#4291)
* Added HTTP status codes from RFC 4918

* Updated documentation about status codes

* Added reference to RFC 4918
2016-07-26 11:09:12 +01:00
Andi Albrecht
3ca0b15b17 Restore meta information for each search field. (#4298)
The meta information stored in opts needs to be restored for
each search field. Otherwise it references the wrong model
when an attribute of a related model comes before an attribute
of the original model in search fields. This doesn't apply to
m2m relations since must_call_distinct returns True in that
case.
2016-07-26 11:07:03 +01:00
Hendra
48465a667a Remove outdated resources (#4295)
Removed links to Youtube videos that are no longer available and updated a link to a tutorial that has moved.
2016-07-26 11:03:05 +01:00
Xavier Ordoquy
0f61c9ec29 Merge pull request #4286 from osantana/patch-1
Fix SwaggerRenderer implementation example
2016-07-19 19:39:48 +02:00
Osvaldo Santana Neto
02a81d3362 Fix SwaggerRenderer implementation example 2016-07-19 14:15:49 -03:00
Xavier Ordoquy
6d4ada05ec Merge pull request #4283 from auvipy/up
updated minor django versions
2016-07-19 10:46:52 +02:00
Asif Saifuddin Auvi
71cdda9399 updated minor django versions 2016-07-19 11:31:29 +06:00
Philippe Ombredanne
e476c222f9 Add LICENSE.md to the built wheel (#4270)
The wheel released on Pypi does not include the license file .
The way to do this is by updating the setup.cfg accordingly
2016-07-18 16:08:44 +01:00
Marc Gibbons
d80b0eaead Update schema generator example (#4267)
1. The returns from the views needs to be a Response
2. I found that instantiating the generator at the module level caused an import error when starting Django, likely because it is executing before all the app load magic happened. Moving it into the view method solved this.
2016-07-18 16:04:23 +01:00
Xavier Ordoquy
bea243a0ca Fix coreapi param arguments. (#4274) 2016-07-18 15:56:36 +01:00
Xavier Ordoquy
6b713207d2 Merge pull request #4273 from aaugustin/issue-4272
Add missing return statement.
2016-07-17 13:54:18 +02:00
José Padilla
ad9c96ebe2 Merge pull request #4269 from glarrain/patch-1
docs.settings: fix name of `VERSION_PARAM`
2016-07-16 18:27:15 -04:00
Aymeric Augustin
a436515196 Add missing return statement.
Fix #4272.
2016-07-16 22:44:49 +02:00
Germán Larraín
1a65f72f71 docs.settings: fix name of VERSION_PARAM 2016-07-15 14:34:27 -04:00
Xavier Ordoquy
91aad9299b Merge pull request #4263 from anoopmalav/master
Fix Typo in index.md
2016-07-14 20:01:09 +02:00
anoopmalav
faf6f226cd Fix Typo in index.md
Currently generating invalid URL at index page.
http://www.django-rest-framework.org/'api-guide/schemas.md'

Though it is correct in navigation.
2016-07-14 22:57:38 +05:30
Tom Christie
70e4a43ae3 Update coreapi requirement 2016-07-14 12:56:57 +01:00
Tom Christie
a9218e460f Minor tutorial updates 2016-07-14 12:44:13 +01:00
Tom Christie
aa40c58381 Note 'coreapi dump' command 2016-07-14 12:33:54 +01:00
Tom Christie
28820449f0 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2016-07-14 12:29:46 +01:00
Tom Christie
5dd3d1b5d9 Update coreapi version in docs 2016-07-14 12:29:37 +01:00
Rashid Al Abri
df33035a3c Change incorrect example URL (#4261)
Changed http://example.com/api/items/4/.json to http://example.com/api/items/4.json
2016-07-14 12:28:28 +01:00
Tom Christie
06751f8548 Minor docs tweaks 2016-07-13 16:59:15 +01:00
Tom Christie
6f8a0f2a68 Update release docs 2016-07-13 16:46:50 +01:00
Tom Christie
e107c1dc35 Resize sponsor images 2016-07-13 16:33:27 +01:00
Tom Christie
8385ae42c0 3.4.0 Release (#4258)
* 3.4.0 Release

* Version 3.4 release

* Full release notes

* Update translation files

* Update release documentation

* Update release notes

* Docs on supporting alternate schema formats

* Add schema_renderers to DefaultRouter
2016-07-13 16:30:41 +01:00
Mads Jensen
6defb8da47 lookup_type is deprecated in favor of lookup_expr (#4259)
* lookup_type is deprecated in favor of lookup_expr
* assertEquals is deprecated in favor of assertEqual
* app_name is a required keyword as of Django 1.10
2016-07-13 14:40:42 +01:00
Tom Christie
549210b50f Don't strip microseconds in JSON output. (#4256) 2016-07-11 14:34:23 +01:00
Tom Christie
7bfa5a9141 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2016-07-11 13:49:21 +01:00
Tom Christie
321c060dbe Resolve incorrect media type (#4254) 2016-07-11 12:04:11 +01:00
Tom Christie
f319e073e8 Client docs 2016-07-11 11:54:53 +01:00
Tom Christie
c21994e778 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2016-07-08 16:38:47 +01:00
Tom Christie
c56d6d6bd3 Docs tweaks 2016-07-08 16:38:38 +01:00
Kenneth Schnall
ff5cfe3e84 Replace "class based views" occurrences with "class-based views" (#4251) 2016-07-08 08:38:50 +01:00
Tom Christie
7c171dfd83 Add tutorial 7 to homepage [ci skip] 2016-07-07 09:55:26 +01:00
Tom Christie
4a07d31d70 Add stream to premium backers [ci skip] (#4249) 2016-07-07 09:34:01 +01:00
kiyoqoko
6338ce80ab Add localize keyword argument to DecimalField (#4233)
Add `localize` keyword argument for DecimalField
2016-07-06 16:07:16 +01:00
Tom Christie
b10de37476 Funding text tweaks [ci skip] (#4247) 2016-07-05 15:58:36 +01:00
cobaltchang
b04bd8618c Fix the error without specified encoding when compiling (#4246)
Fix setup.py error on some platforms
2016-07-05 15:36:52 +01:00
Tom Christie
6ff9840bde Schemas & client libraries. (#4179)
* Added schema generation support.
* New tutorial section.
* API guide on schema generation.
* Topic guide on API clients.
2016-07-04 16:38:17 +01:00
Vikalp Jain
1d2fba906e Fix issues with routers for custom list-route and detail-routes (#4229) 2016-06-29 17:27:17 +01:00
Tom Christie
d41ddc9e5f Update README.md 2016-06-29 12:16:42 +01:00
Vadim
c752e9618f Fix test for py32-django18. 2016-06-29 10:21:28 +03:00
Vadim
c0f4dfd8f3 Add tests for the ListSerializer for the TestSerializerPartialUsage.
Additional fix partial update for the ListSerializer.
2016-06-29 09:48:31 +03:00
José Padilla
1359061789 Merge pull request #4226 from waytai/patch-1
Update pagination.md
2016-06-27 22:50:32 -04:00
decore
1037a2742e Update pagination.md 2016-06-28 10:15:42 +08:00
Xavier Ordoquy
151a60b64b Merge pull request #4224 from kneckinator/patch-1
Added missing colon in extra_kwargs documentation
2016-06-25 22:12:59 +02:00
Ken Lewerentz
57122f0422 Added missing colon in extra_kwargs documentation 2016-06-25 22:05:28 +07:00
Vadim
53a1205dd0 Fix partial update for the ListSerializer. 2016-06-24 15:04:18 +03:00
Tom Christie
3a7bfdfa70 Add sentry as a premium sponsor [skip ci] (#4221)
Add Sentry as a premium sponsor.
2016-06-24 11:05:19 +01:00
Tom Christie
8ab684187c Tweak funding text. [skip ci] 2016-06-24 10:06:02 +01:00
Laurent De Marez
fdde44d9d1 Fix parsing multipart data using a nested serializer with list (#3820)
It is possible that a key in a MultiValueDict has multiple values, lists
are represented this way. When accessing a key in a MultiValueDict
it only returns the last element of that key. This becomes a problem
when parsing an html dict with a list inside of it.

To fix this problem we have to get and set the value using .getlist()
and .setlist().
2016-06-23 16:03:24 +01:00
Tom Christie
bc3485ab7d Namespace versioning with nested namespaces (#4219)
Support nested namespaces with namespaced versioning.
2016-06-23 16:00:11 +01:00
Tom Christie
ea92d50582 Resolve tests against Django master (#4218) 2016-06-23 15:41:25 +01:00
Tom Christie
f81d516ae4 Robust uniqueness checks. (#4217)
* Robust uniqueness checks
* Add master to test matrix (allow_failures)
2016-06-23 15:09:23 +01:00
José Padilla
a20a75636c Test against Django 1.10b1 (#4210)
* Test against Django 1.10b1
* Test against Django master
2016-06-23 14:12:51 +01:00
Tom Christie
e1f7cc4082 Minor refactoring of must_call_distinct (#4215) 2016-06-23 14:02:25 +01:00
Simon Charette
90bb0c58ce Prevented unnecessary distinct() call in SearchFilter. (#3938)
* Prevented unnecessary distinct() call in SearchFilter.

* Refactored SearchFilter lookup prefixes.
2016-06-23 13:49:23 +01:00
Tom Christie
2a3b4c9822 README sponsorship placement (#4214)
README sponsorship placement.
2016-06-23 13:29:38 +01:00
Rowan Seymour
36ca4b8e06 Make offset_cutoff a class attribute in CursorPagination so that it can be easily overridden in subclasses (#4212) 2016-06-23 10:37:15 +01:00
Ankush Thakur
879652ec2e Update 2-requests-and-responses.md (#4209)
Make the usage of httpie accept headers more explicit.
2016-06-21 21:07:55 +01:00
Kenneth Love
498ce85f34 Update third-party-resources.md (#4200) 2016-06-15 21:17:16 +01:00
Tom Christie
798a971f20 Simplfy TimeField passing through strings (#4197)
* Simplfy TimeField passing through strings
2016-06-14 16:05:00 +01:00
Tom Christie
9406e45b2c Pass through strings as-in with DateTimeField (#4196) 2016-06-14 12:23:39 +01:00
Tom Christie
1633a0a2b1 Add test confirming that required=False is valid on a relational field (#4195) 2016-06-13 16:52:45 +01:00
Tom Christie
2e7fae7698 limit=0 should revert to default limit (#4194) 2016-06-13 16:32:43 +01:00
Tom Christie
c3b7fba918 Exclude read_only=True fields from unique_together validation & add docs. (#4192)
* Exclude read_only=True fields from unique_together validation
* Test to ensure that unique_together validators can be removed
* Do not add uniquness_extra_kwargs when validators are explicitly declared.
* Add docs on validation in complex cases
2016-06-13 13:31:12 +01:00
Tom Christie
9bffd35432 Handle bytestrings in JSON. Closes #4185. (#4191) 2016-06-13 10:41:50 +01:00
Tom Christie
bb22ab8ee7 More robust form rendering in the browsable API (#4181) 2016-06-08 17:13:20 +01:00
Tom Christie
a5f822d067 Empty cases of .validated_data and .errors as lists not dicts for ListSerializer (#4180) 2016-06-08 15:55:09 +01:00
Asif Saifuddin Auvi
04e5b5b20a removed AUTH_USER_MODEL compat property (#4176)
Removed unnecessary `AUTH_USER_MODEL` compat variable.

(No longer required)
2016-06-07 12:13:35 +01:00
Tom Christie
b1035b2a87 Minor docs tweaks. [ci skip] (#4174) 2016-06-06 12:03:37 +01:00
Tom Christie
2712d4e5fe Note on obtain_auth_token and throttles/permissions. Closes #4128. [ci skip] (#4173) 2016-06-06 11:03:56 +01:00
José Padilla
064e8e264b Merge pull request #4171 from auvipy/up
upgraded django to 1.9.7 release
2016-06-05 08:33:28 -04:00
Asif Saifuddin Auvi
d54082c4a7 upgraded django to 1.9.7 release 2016-06-05 12:12:38 +06:00
Tom Christie
d404597e0b Update FileUploadParser docs. Closes #4167. [ci skip] (#4169) 2016-06-03 09:37:09 +01:00
Sergei Sinitsyn
94863ee6d0 Change serializer field help_text rendering in browsable api (#3812) 2016-06-02 15:21:57 +01:00
Tom Christie
75751cc64e Allow relative style hyperlinked URLs 2016-06-02 15:03:17 +01:00
Tom Christie
9c996d7d2a Clean up existing deprecation warnings. (#4166)
* Add Meta.fields = '__all__' to serializer classes where required.
* Add explicit on_delete=models.CASCADE to ForeignKey fields.
* Use '.remote_field' and '.model' in preference to '.rel' and '.to' when inspecting model fields.
* Use new value_from_object in preference to internal _get_val_from_obj
2016-06-02 14:39:10 +01:00
Tom Christie
53a356a380 Fix docs link [ci skip] (#4165) 2016-06-02 10:35:18 +01:00
Xavier Ordoquy
cd5772174e Merge pull request #4162 from sohopro/patch-1
Update filtering.md
2016-06-02 09:19:48 +02:00
sohopro
20e3a9a006 Update filtering.md 2016-06-02 16:12:35 +09:00
Carlton Gibson
4ac8cdb95e Updated Guardians and Filter Versions (#4161)
* updated guardians and filter versions
* Remove Django 1.10 from allow_failures
2016-06-01 22:49:50 +01:00
Tom Christie
05b0c2adff Don't list M2M choices in OPTIONS requests. Refs #3751. (#4160) 2016-06-01 17:28:32 +01:00
Simon Charette
014e24b024 Do not list related field choices in OPTIONS requests.
Do not list related field choices in OPTIONS requests.
2016-06-01 16:33:03 +01:00
Tom Christie
9d5773772b Reformat travis.yml and turn off email notifications (#4159) 2016-06-01 15:53:58 +01:00
Asif Saifuddin Auvi
b92901e591 updated jquery version to 1.12.4 (#4157)
Updated jquery version to 1.12.4
2016-06-01 15:33:36 +01:00
Tom Christie
994e1ba927 Django 1.10 support. (#4158)
* Added TEMPLATES setting to tests
* Remove deprecated view-string in URL conf
* Replace 'urls = ...' in test classes with override_settings('ROOT_URLCONF=...')
* Refactor UsingURLPatterns to use override_settings(ROOT_URLCONF=...) style
* Get model managers and names in a version-compatible manner.
* Apply override_settings to a TestCase, not a mixin class
* Use '.callback' property instead of private attributes when inspecting urlpatterns
* Pass 'user' to template explicitly
* Correct sorting of import statements.
* Remove unused TEMPLATE_LOADERS setting, in favor of TEMPLATES.
* Remove code style issue
* BaseFilter test requires a concrete model
* Resolve tox.ini issues
* Resolve isort differences between local and tox environments
2016-06-01 15:31:00 +01:00
Tom Christie
fe2aede18d More robust default behavior on OrderingFilter (#4156) 2016-06-01 11:08:04 +01:00
Asif Saifuddin Auvi
dc09eef24a Style fix of tests (#4154)
Clean up code style.
2016-06-01 10:40:54 +01:00
Xavier Ordoquy
8e2787fd4b Merge pull request #4153 from auvipy/des
description.py codes and tests removal
2016-06-01 10:32:20 +02:00
Asif Saifuddin Auvi
eef94856d8 deleted description.py as unneeded 2016-06-01 10:24:29 +06:00
Asif Saifuddin Auvi
4fabdee4a3 fix lint error 2016-06-01 02:04:38 +06:00
Asif Saifuddin Auvi
91bb17770e removed description tests unicode related functions 2016-06-01 00:43:37 +06:00
Asif Saifuddin Auvi
3db45cb94d removed description codes as it seems to be python 2.6 issue 2016-06-01 00:39:01 +06:00
José Padilla
0777cb7577 Merge pull request #4151 from adamchainz/readthedocs.io
Convert readthedocs link for their .org -> .io migration for hosted projects
2016-05-29 21:53:04 -04:00
Adam Chainz
e3337ab4aa Convert readthedocs link for their .org -> .io migration for hosted projects
As per [their blog post of the 27th April](https://blog.readthedocs.com/securing-subdomains/) ‘Securing subdomains’:

> Starting today, Read the Docs will start hosting projects from subdomains on the domain readthedocs.io, instead of on readthedocs.org. This change addresses some security concerns around site cookies while hosting user generated data on the same domain as our dashboard.

Test Plan: Manually visited all the links I’ve modified.
2016-05-29 23:26:56 +01:00
Tom Christie
8e082770b0 Premium sponsor link 2016-05-28 10:55:38 +01:00
Tom Christie
9895de990d Fix signup URLs 2016-05-28 10:23:59 +01:00
KhasanovBI
92bf8b9197 Wrap guardian.VERSION in tuple, in django-guardian 1.4.2 version has list type and comparison fails. (#4149) 2016-05-26 20:22:38 +01:00
Tom Christie
9d2f6fea11 Update README 2016-05-26 13:24:59 +01:00
Tom Christie
3a173547ad Funding announcement (#4147) 2016-05-26 11:48:15 +01:00
Kennedy Mwenja
592eea9b9e * Use get_serializer_class in ordering filter* Test improper configuration of ordering* Raise ImproperlyConfigured when missing get_serializer_class
* Use get_serializer_class in ordering filter
* Test improper configuration of ordering
* Raise ImproperlyConfigured when missing get_serializer_class
2016-05-26 09:59:13 +01:00
Xavier Ordoquy
2d20f09c0c Merge pull request #4146 from xiaohanyu/bug-fix-unique-validator-error-with-related-field
Fix #3844, refine validator for fields with <source=> kwargs
2016-05-26 07:56:03 +02:00
Xiao Hanyu
19bdfda49a Fix #3844, refine validator for fields with <source=> kwargs
When serializers has fields with something like `source=user.email`, the
uniqueness validator should check `email` field instead of `user`, cause
`user` is a model object.
2016-05-26 10:58:37 +08:00
Asif Saifuddin Auvi
35ace2e9ec django 1.10 support initials (#4144)
* added django 1.10 alpha on tox
* added django 1.10 alpha on travis
* added allow_failure on travis matrix
2016-05-25 20:07:21 +01:00
Carlton Gibson
9d87dbc016 Remove Py2/Py3 difference from Example (#4145)
`print` is available as a function on every supported version of Python (2.7+)
2016-05-25 14:38:44 +01:00
Tom Christie
9b56dda918 Update requests.md
Drop out-of-date paragraph on `request.content`
2016-05-18 08:38:18 +01:00
Joe Simpson
5cf7d4a90d Add LaTeX renderer to documentation (#4131) 2016-05-17 12:09:25 +01:00
José Padilla
b58e28b99c Merge pull request #4130 from BenBrostoff/fix_doc_string_typos
Fix typos in ReturnDict and ReturnList docstrings
2016-05-16 23:18:52 -04:00
Ben Brostoff
400078311b Fix typos in ReturnDict and ReturnList docstrings 2016-05-16 20:39:13 -04:00
José Padilla
d721021429 Update requirements (#4125) 2016-05-16 13:24:09 +01:00
KhasanovBI
768ae26aa4 Fix None values representation in childs of ListField, DictField. (#4118) 2016-05-16 09:30:23 +01:00
José Padilla
daccc2b8f3 Clean up js style and remove extra getCookie function (#4123) 2016-05-16 09:27:38 +01:00
José Padilla
5392be4ddb Spring cleaning template styles (#4124) 2016-05-16 09:27:10 +01:00
Alexander Gaevsky
1328982de3 Set proper status code in AdminRenderer for the redirection after POST/DELETE requests. (#4106) 2016-05-16 09:22:28 +01:00
Petros Moisiadis
788603e153 Document allow_empty argument (#4117)
ListSerializer fields or serializers that are passed many=True may also take an allow_empty=False argument to disallow empty lists as valid input.

Information about this was part of the 3.2 release announcement, but had not been part of the API docs until now.
2016-05-13 15:55:31 +01:00
Tom Christie
ebb4070467 Resolve TimeField representation for midnight value. (#4107) 2016-05-10 11:56:36 +01:00
José Padilla
0795f7394c Prevent raising exception when limit is 0 (#4098) 2016-05-10 10:58:24 +01:00
Xavier Ordoquy
5ac9685139 Merge pull request #4103 from Hongxia/i18n
Fix incorrectly named zh-hans and zh-hant locale path
2016-05-09 09:51:31 +02:00
Hongxia Zhong
f912faec3f Merge branch 'master' into i18n 2016-05-06 23:41:58 -07:00
Graham R. Jeffries
dbbf79be64 minor docs indentation fix (#4101)
Fixes a minor indentation typo.
2016-05-06 11:58:58 +01:00
Hongxia Zhong
d39af5335c Fix incorrect zh-hans and zh-hant locale directory path 2016-05-06 01:22:33 -07:00
Miro Hrončok
ffdac0d936 TokenAuthentication: Allow custom keyword in the header (#4097)
This allows subclassing TokenAuthentication and setting custom keyword,
thus allowing the Authorization header to be for example:

    Bearer 956e252a-513c-48c5-92dd-bfddc364e812

It doesn't change the behavior of TokenAuthentication itself,
it simply allows to reuse the logic of TokenAuthentication without
the need of copy pasting the class and changing one hardcoded string.

Related: #4080
2016-05-04 10:53:34 +01:00
Xavier Ordoquy
37b1ce5d86 Merge pull request #4096 from tedmiston/master
Fix typo in permissions docs
2016-05-04 10:17:45 +02:00
Taylor Edmiston
c355cdc585 Fix typo in permissions docs 2016-05-03 14:20:45 -04:00
Kyle Hornberg
399e1c1dcf Typo fix (#4094) 2016-05-03 15:53:55 +01:00
Xavier Ordoquy
6c6e5c7fba Merge pull request #4093 from auvipy/up
added python 3.5 checks for django 1.8
2016-05-03 12:23:04 +02:00
Asif Saifuddin Auvi
37ad407e64 Merge branch 'master' of https://github.com/tomchristie/django-rest-framework into up 2016-05-03 16:01:40 +06:00
Asif Saifuddin Auvi
5f52c4ff3e added python3.5 for django 1.8 checks 2016-05-03 15:52:05 +06:00
Asif Saifuddin Auvi
28c6d96af8 upgraded minor django version n tox (#4091) 2016-05-03 09:25:27 +01:00
Germán Larraín
e19b21ecc5 Handle incorrectly padded HTTP basic auth header (#4090) 2016-05-03 09:24:55 +01:00
Asif Saifuddin Auvi
04ebb1ef04 upgraded minor django version n tox 2016-05-03 09:50:52 +06:00
Xavier Ordoquy
a9bbb502cb Remove references to South as we don't need it any longer. (#4085)
* Remove references to South as we don't need it any longer.
* Add a note about auth_token including Django migrations.
2016-04-29 14:16:03 +01:00
Daniele Varrazzo
88c80fe2e9 Fixed DecimalField arbitrary precision support (#4075) 2016-04-27 17:04:01 +01:00
José Padilla
4f16c54428 Merge pull request #4049 from clintonb/csrf-cookie-fix
Added support for custom CSRF cookie names
2016-04-26 11:43:23 -03:00
Xavier Ordoquy
1823662e1e Merge pull request #4044 from linovia/merge/3.3.x_to_master
Merge the changes in 3.3.x back to master.
2016-04-21 11:31:15 +02:00
Puneet Aggarwal
888e5c78bd Update README.md (#4055) 2016-04-19 15:09:16 +01:00
Clinton Blackburn
9d9658f128 Added support for custom CSRF cookie names
Instead of hardcoding the CSRF cookie name, the value is passed to the template as a context variable, rendered as a JavaScript variable, and read by csrf.js.

Fixes #4048
2016-04-11 23:58:55 -04:00
Phivos Stylianides
08dad04b19 Fix warnings when running tests (#4047) 2016-04-11 14:13:11 +01:00
Simon Charette
d87f2bc7b6 OrderingFilter adjustements (#3983)
* Made sure the OrderingFilter relies on Field.verbose_name.

* Marked OrderingFilter's order labels for translation.
2016-04-08 15:37:23 +01:00
Xavier Ordoquy
bff3bebdbe Merge remote-tracking branch 'reference/stable/3.3.x' into merge_test
# Conflicts:
#	docs/topics/release-notes.md
2016-04-08 15:46:17 +02:00
Xavier Ordoquy
95418eb8ac Add the medium collection related to Django REST framework. (#4043) 2016-04-08 14:43:10 +01:00
Xavier Ordoquy
10a080d395 Merge pull request #4041 from linovia/bug/fix_correct_string_type
Fix regression introduced by #4035
2016-04-07 20:16:25 +02:00
Xavier Ordoquy
29a2e549c1 Merge remote-tracking branch 'reference/master' into bug/fix_correct_string_type 2016-04-07 18:03:12 +02:00
Xavier Ordoquy
2622588b30 Typo correction. 2016-04-07 18:00:17 +02:00
Xavier Ordoquy
019c6db759 Fix the string_types / text_types confusion introduced in #4025 (#4035) 2016-04-07 16:34:27 +01:00
Jonathan Liuti
78e4ea0d6e No auth view failing permission should raise 403
A view with no `authentication_classes` set and that fails a

permission check should raise a 403 with the message from the

failing permission.
2016-04-07 16:24:26 +01:00
Xavier Ordoquy
6a29196712 Merge pull request #4038 from raphaelgyory/master
Add Django Rest Messaging to Third Party Packages
2016-04-06 17:26:16 +02:00
Raphael Gyory
b870101581 Update third-party-resources.md 2016-04-06 17:00:26 +02:00
Raphael Gyory
f1a384b61b Add Django Rest Messaging in Third party packages 2016-04-06 16:58:15 +02:00
Xavier Ordoquy
763aab6b45 Fix the string_types / text_types confusion introduced in #4025 2016-04-05 16:29:16 +02:00
José Padilla
dd3b47ccbd Merge pull request #4025 from dnit/master
type('') to str
2016-04-03 14:03:13 -04:00
Nitesh Lohchab
09aa8f76c4 python2.x and 3.x compatible 2016-04-03 18:39:32 +05:30
Nitesh Lohchab
c22b92a66c type('') to str 2016-04-03 00:07:45 +05:30
José Padilla
3d3b06447f Merge pull request #4024 from auvipy/dev
updated minor django versions on tox
2016-04-02 13:11:21 -04:00
auvipy
5cc6c254d5 updated minor django versions on tox 2016-04-02 23:02:44 +06:00
Xavier Ordoquy
67ac0486f5 Merge pull request #4006 from mochawich/patch-1
Reorder initializing the view
2016-03-31 13:53:14 +02:00
Xavier Ordoquy
6b1125a2b6 Merge pull request #4020 from alukach/patch-1
Add .partial_update to ModelViewSet documentation
2016-03-29 18:57:16 +02:00
Anthony Lukach
3fdd6e1db5 Add .partial_update to ModelViewSet documentation
The ModelViewSet inherits from the UpdateModelMixin, which provides the `.partial_update` method. This should be reflected in the documentation.
2016-03-29 10:50:12 -06:00
Xavier Ordoquy
c1802db1eb Merge pull request #4018 from tomviner/bugfix-cramer-cursors-link
remove trailing slash from cramer cursor link
2016-03-24 21:45:40 +01:00
Tom Viner
3e5a1397d7 remove trailing slash from cramer cursor link 2016-03-24 20:37:38 +00:00
Xavier Ordoquy
f9304b6f34 Merge pull request #4016 from sheppard/html-json-forms
links to html-json-forms package
2016-03-24 18:02:58 +01:00
S. Andrew Sheppard
101c178b8c links to html-json-forms package 2016-03-24 11:55:19 -05:00
Xavier Ordoquy
cfb77ae6fa Merge pull request #3273 from olliewalsh/breadcrumbs_view_name
Do not ignore overridden View.get_view_name() in breadcrumbs
2016-03-23 01:10:13 +01:00
Xavier Ordoquy
0e8306341d Merge pull request #3936 from carltongibson/null-uuid-fk-take2
Fix None UUID ForeignKey serialization
2016-03-22 22:46:33 +01:00
Xavier Ordoquy
85e57afc20 Merge pull request #4008 from minddust/hotfix/typo
Fix typo
2016-03-21 11:52:11 +01:00
Stephan Groß
0056703fe8 Fix code sample indention 2016-03-21 10:23:34 +00:00
Stephan Groß
3785281d4c Add missing paginator in docs 2016-03-21 10:07:47 +00:00
Stephan Groß
91e869750e Fix typo 2016-03-21 08:57:43 +00:00
Mohamad Nour Chawich
03270431ed Reorder initializing the view
Determining the version and performing content negotiation should be done before ensuring the permission of the request. The reason is that these information can be used in handling the exceptions. For example different versions may return different error scheme. Also, the rendering class can be used to determine how to exception handler response should be rendered.
2016-03-20 21:46:37 +01:00
José Padilla
e946a496dc Merge pull request #4003 from blaze33/patch-1
Fixed use of deprecated Query.aggregates
2016-03-19 11:39:53 -04:00
Maxime R
24694ddcb4 Fixed use of deprecated Query.aggregates
In Django 1.8 [`Query.aggregates` is replaced by `annotations`](https://docs.djangoproject.com/es/1.9/releases/1.8/#aggregate-methods-and-modules).

Using aggregates currently raises a `RemovedInDjango20Warning`. [Django's source](https://github.com/django/django/blob/1.8/django/db/models/sql/query.py#L192)
2016-03-18 16:16:13 +01:00
José Padilla
3645388547 Merge pull request #4002 from minddust/minor_tweaks
Fix blank lines around docstrings
2016-03-17 11:40:15 -04:00
Stephan Groß
a101251a2a Fix blank lines around docstrings 2016-03-17 11:06:47 +00:00
José Padilla
1339fba117 Merge pull request #3989 from wlanslovenija/delay-javascript
Run JavaScript only when DOM is ready
2016-03-16 22:53:27 -04:00
José Padilla
f1a4e9a846 Merge pull request #3986 from AltSchool/docs/dynamic-rest
Add a reference to the dynamic-rest addon
2016-03-16 17:39:14 -04:00
Xavier Ordoquy
bb56ca46ed Merge pull request #3998 from AlexRiina/patch-1
Remove django1.7 from README.md
2016-03-16 08:40:28 +01:00
Alex Riina
1725e5e5b8 Remove django1.7 from README.md
Remove django1.7 since #296c56764574b178be2d0ac96b38d7879e0b3947 took django1.7 off the build.
2016-03-15 23:23:06 -04:00
Xavier Ordoquy
0c42c74229 Merge pull request #3924 from linovia/stable/3.3.3
Version 3.3.3
2016-03-14 08:46:03 +01:00
Xavier Ordoquy
f0fc339278 Release date update. 2016-03-14 08:40:00 +01:00
Xavier Ordoquy
265db86590 Translation update. 2016-03-14 08:31:27 +01:00
Carlton Gibson
2ef74cfa61 Bring check for null fk to BaseSerializer.to_representation 2016-03-13 20:39:19 +01:00
Mitar
2f49df8242 Run JavaScript only when DOM is ready. 2016-03-12 16:52:31 -08:00
aleontiev
3a3fd66852 documentation: add a reference to the dynamic-rest addons under the serializers guide 2016-03-11 12:43:17 -05:00
Xavier Ordoquy
c91229aaab PAGINATE_BY_PARAM and MAX_PAGINATE_BY removed in 3.3 2016-03-08 06:41:08 +01:00
Xavier Ordoquy
c90cf828ae PAGE_SIZE addition in 3.1 2016-03-08 06:40:33 +01:00
Xavier Ordoquy
180137300f PAGINATE_BY removed in 3.3 2016-03-08 06:39:58 +01:00
Xavier Ordoquy
a0aac166bc DEFAULT_PAGINATION_SERIALIZER_CLASS removed in 3.1 2016-03-08 06:39:08 +01:00
Xavier Ordoquy
9208619362 Those are now fully removed. 2016-03-08 06:38:03 +01:00
Xavier Ordoquy
cac1ecb250 paginate_by removed in 3.3 2016-03-08 06:37:46 +01:00
Krzysztof Szularz
cfd681dc73 Add /en to Heroku guidelines link 2016-03-07 21:01:04 +01:00
ildoc
2e2abbc811 updated tutorial for django 1.9 2016-03-07 20:59:58 +01:00
meoooh
0a2a01d05a fix typo
fix typo
2016-03-07 20:58:47 +01:00
Wes
0e1dcb7323 fix typo 2016-03-07 20:58:24 +01:00
Kin
b572cdb068 fix typo 2016-03-07 20:58:12 +01:00
Xavier Ordoquy
6ea9a41408 Add #3962 in the last minute fixes. 2016-03-07 20:39:34 +01:00
Xavier Ordoquy
4399d601c5 Translation updates. 2016-03-07 20:25:10 +01:00
Xavier Ordoquy
173c2f1e53 Release date update. 2016-03-07 20:22:47 +01:00
Jared Lang
e34a34e90b Fix empty pk detection in HyperlinkRelatedField.get_url
This implementation allows detection of empty values that are non-nullable, allowing the field to return None values for such cases
2016-03-07 19:37:48 +01:00
Luke Murphy
ef8e7f168f add rest-framework-generic-relations link to docs 2016-03-07 19:37:30 +01:00
Xavier Ordoquy
22695ec8a7 Merge pull request #3978 from jpadilla/master
Update Django versions after bugfix release
2016-03-07 10:43:40 +01:00
José Padilla
c811a51be7 Update Django versions after bugfix release 2016-03-05 11:28:28 -04:00
Tom Christie
82ec6e859c Merge pull request #3962 from jslang/fix_null_check_in_hyperlinkrelation
Fix empty pk detection in HyperlinkRelatedField.get_url
2016-03-04 16:19:48 +00:00
Xavier Ordoquy
5f3868a3bf Merge pull request #3974 from jpadilla/master
Update Django security releases 1.9.3 and 1.8.10
2016-03-02 16:13:51 +01:00
José Padilla
03c95c0e71 Update Django security releases 1.9.3 and 1.8.10 2016-03-02 11:04:53 -04:00
José Padilla
b3582cd36b Merge pull request #3973 from lwm/docs-generic-relations
add rest-framework-generic-relations link to docs
2016-03-01 13:54:44 -04:00
Luke Murphy
66e86dc483 add rest-framework-generic-relations link to docs 2016-03-01 18:44:17 +01:00
Tom Christie
6b01c5f094 Merge pull request #3972 from szuliq/patch-1
Add `/en` to Heroku guidelines link
2016-03-01 13:59:31 +00:00
Krzysztof Szularz
2ddd30be90 Add /en to Heroku guidelines link 2016-03-01 14:52:07 +01:00
Xavier Ordoquy
97cc83483f Merge remote-tracking branch 'reference/stable/3.3.x' into stable/3.3.3 2016-03-01 10:39:34 +01:00
Xavier Ordoquy
0324429107 Add #3968 to the release notes. 2016-03-01 10:39:13 +01:00
Rex Kerr
f3b4cb5951 Fixes incorrect references to URLPathVersioning 2016-03-01 10:36:05 +01:00
Liping Wang
239815887d remove comma
remove comma
2016-03-01 10:35:41 +01:00
Liping Wang
05204333a5 [FIX] "@api_view" calling error.
"@api_view" usage error.
2016-03-01 10:35:41 +01:00
Xavier Ordoquy
c2cfb84308 Merge pull request #3971 from lynndotconfig/master
[change] using safer calling way of  "@api_view" in docs/tutorial/5-relationships-and-hyperlinked-apis.md
2016-03-01 10:20:21 +01:00
Liping Wang
c3cea1499f remove comma
remove comma
2016-03-01 15:46:20 +08:00
Jared Lang
7ac8cc760c Fix empty pk detection in HyperlinkRelatedField.get_url
This implementation allows detection of empty values that are non-nullable, allowing the field to return None values for such cases
2016-02-29 12:56:56 -08:00
Liping Wang
d372ccca02 [FIX] "@api_view" calling error.
"@api_view" usage error.
2016-02-29 19:51:33 +08:00
José Padilla
eec7c1754e Merge pull request #3969 from rexkerr/fix-versioning-docs
Fixes incorrect references to URLPathVersioning
2016-02-27 17:11:15 -04:00
Rex Kerr
88320b8a61 Fixes incorrect references to URLPathVersioning 2016-02-27 12:41:56 -08:00
Xavier Ordoquy
d85162c83d Merge pull request #3968 from linovia/bug/missing_auth_token_migration
Add missing migration file for #3887
2016-02-27 01:53:07 +01:00
Xavier Ordoquy
753f4dc477 Fix sorting order. 2016-02-27 01:46:59 +01:00
Xavier Ordoquy
6ea6e37ac9 Add missing migration file for #3887 2016-02-27 00:51:35 +01:00
Xavier Ordoquy
24a2ec0501 Merge remote-tracking branch 'reference/stable/3.3.x' into stable/3.3.3 2016-02-27 00:36:23 +01:00
Taranjeet
a609e4e1ca Docs: Fix repetitive word in the tutorial 2016-02-27 00:28:15 +01:00
Luke Murphy
c03c6c6e78 fix typo in relations docs 2016-02-27 00:27:41 +01:00
Tom Christie
a15e46af88 Merge pull request #3965 from ildoc/master
updated tutorial for django 1.9
2016-02-25 21:37:27 +00:00
José Padilla
82245be8f9 Merge pull request #3966 from staranjeet/typo-fix
Docs: Fix repetitive word in the tutorial
2016-02-25 14:59:22 -04:00
Taranjeet
3fd6db1445 Docs: Fix repetitive word in the tutorial 2016-02-26 00:02:45 +05:30
ildoc
35036aee15 updated tutorial for django 1.9 2016-02-25 14:27:57 +01:00
Xavier Ordoquy
450c76472b Merge pull request #3960 from lwm/fix-typo-relations
Fix typo in relations docs
2016-02-24 15:45:23 +01:00
Luke Murphy
f3c5802872 fix typo in relations docs 2016-02-24 14:22:24 +01:00
Tom Christie
a568d16ae4 Merge pull request #3950 from jpadilla/templates
Create issue and pull request templates
2016-02-22 16:03:06 +00:00
José Padilla
9c2899f6c8 Create issue and pull request templates 2016-02-22 11:17:02 -04:00
José Padilla
69c0de4faa Merge pull request #3953 from akarambir/remove-old-django-checks
Closes #3952: Remove old django checks from tests and compat
2016-02-19 11:08:45 -04:00
José Padilla
0b6f53eb98 Merge pull request #3943 from erickwilder/3937-accept-callable-as-initial-value
Closes #3937. Support callable as the value of `initial` for any `serializer.Field`
2016-02-19 10:41:23 -04:00
Erick Wilder
a32baeab0c Use datetime example for the Field.initial attribute
Just like regular Django fields, the example adopted uses a `datetiume.date.today` to
illustrate the functionality.
2016-02-19 09:53:50 +01:00
Karambir Singh Nain
69f1e3a9fd Remove old django checks from tests and compat
Remove skipping of tests for Django<1.8. Remove several functions from compat.py not needed for Django>=1.8
2016-02-19 01:47:45 +05:30
Xavier Ordoquy
5ace7174d4 Merge pull request #3949 from meoooh/patch-2
fix typo
2016-02-18 09:15:39 +01:00
meoooh
5cda3a04dd fix typo
fix typo
2016-02-18 14:43:41 +09:00
José Padilla
c6dadc062d Merge pull request #3946 from linovia/feature/remove_page_info_in_pagination_error_msg
Remove page information in pagination error messages
2016-02-17 22:48:30 -04:00
Xavier Ordoquy
5e08231453 Remove informations about why the pagination didn't work.
We remove a couple of informations to lower the exposition of our internals.
2016-02-17 18:18:19 +01:00
José Padilla
bec5f3db83 Merge pull request #3941 from wesgt/master
fix typo
2016-02-17 07:11:36 -04:00
José Padilla
0e1c1f6b91 Merge pull request #3940 from jianlin/typo-fix
fix typo
2016-02-17 07:11:04 -04:00
Erick Wilder
908efd6656 #3937 Update docs for the Field.initial attribute.
Add an usage example on how to pass a callable to the `Field.initial` in the docs.
2016-02-17 11:01:09 +01:00
Erick Wilder
8109752061 Closes #3937. Support callable as the value of initial for any serializer.Field 2016-02-17 10:52:21 +01:00
Wes
b773f03bd0 fix typo 2016-02-17 16:35:53 +08:00
Kin
96644bd6c1 fix typo 2016-02-16 23:08:45 -08:00
Carlton Gibson
cbb8d8d254 Test deserialising data including None fk 2016-02-16 09:38:42 +01:00
Carlton Gibson
20d1fdba69 Fix None UUID ForeignKey serialization 2016-02-16 09:29:48 +01:00
Xavier Ordoquy
79dad012b0 Merge pull request #3933 from carltongibson/drop-django-17
Drop EOL Django 1.7
2016-02-15 19:59:00 +01:00
Carlton Gibson
296c567645 Drop EOL Django 1.7 2016-02-15 16:07:42 +01:00
Xavier Ordoquy
2fc44402f9 Merge pull request #3928 from linovia/feature/pandoc_for_setup
Use pandoc to generate a nice PyPI information page.
2016-02-12 14:52:17 +01:00
Xavier Ordoquy
f48ccad581 Fail hard during publish if pandoc isn't available. 2016-02-12 13:43:18 +01:00
Xavier Ordoquy
f5822e7b71 Bump version to 3.3.3 2016-02-12 13:23:08 +01:00
Xavier Ordoquy
72ecd32c6b Use pandoc to generate a nice PyPI information page. 2016-02-12 13:15:20 +01:00
Xavier Ordoquy
3693e938a4 Merge pull request #3908 from kostya0shift/fix_exceptions_force_text
Fixed _force_text_recursive typo
2016-02-12 08:24:13 +01:00
José Padilla
8c1365e315 Merge pull request #3926 from federicobond/patch-1
Add missing space in serializer error message
2016-02-11 15:23:16 -04:00
Federico Bond
03b5438d07 Add missing space in serializer error message 2016-02-11 15:09:21 -03:00
Xavier Ordoquy
c8ca3a1c05 Release notes for 3.3.3 2016-02-11 07:14:45 +01:00
Xavier Ordoquy
aeda2adeea Merge pull request #3913 from blag/patch-2
Remove version string from admin template
2016-02-09 14:03:28 +01:00
blag
89d575a52a Remove version string from admin template 2016-02-09 05:56:47 -07:00
Xavier Ordoquy
582928da3e Merge pull request #3912 from blag/patch-1
Remove version string from base template
2016-02-09 08:09:11 +01:00
blag
d2ca8872c0 Remove version string from base template 2016-02-08 22:36:39 -07:00
Tom Christie
df9b3fbde4 Merge pull request #3910 from m1kola/patch-1
Fixes vertical html layout for BooleanField
2016-02-08 15:12:51 +00:00
Mikalai Radchuk
59ab3a291c Fixes vertical html layout for BooleanField
`HTMLFormRenderer` renders `BooleanField` field as not checked if vertical layout are used.
2016-02-08 17:07:16 +03:00
Kostya Esmukov
b6adfab9b2 Added test case for #3908 2016-02-07 19:26:37 +03:00
Kostya Esmukov
3ea1fe61a0 Fixed _force_text_recursive typo 2016-02-07 18:58:19 +03:00
Xavier Ordoquy
a3f513c83c Merge pull request #3904 from charettes/tox-warnings
Displayed warnings during test suite.
2016-02-04 20:14:27 +01:00
Simon Charette
57608b937e Displayed warnings during test suite. 2016-02-04 13:58:50 -05:00
Xavier Ordoquy
61f3ccf385 Merge pull request #3903 from charettes/deprecation-warnings-1.8
Silenced deprecation warnings on Django 1.8.
2016-02-04 19:57:32 +01:00
Simon Charette
1a052d6ee3 Silenced deprecation warnings on Django 1.8. 2016-02-04 13:49:55 -05:00
Tom Christie
24c4850019 Merge pull request #3902 from betacloud-solutions/tutorial_createsuperuser_password
Use 'password123' as password for new users in the tutorial
2016-02-04 11:11:02 +00:00
Christian Berendt
ff4d7c7e07 Use 'password123' as password for new users in the tutorial
Trying to create a new user on Django 1.9.x with the password 'password'
will fail with the error message 'This password is too common.'. Because
of that it is necessary to change the used password from 'password' to
'password123'.
2016-02-04 07:26:15 +01:00
Xavier Ordoquy
564b1c8268 Merge pull request #3896 from m1kola/patch-1
Fixes docstrings in fields.py
2016-02-03 11:10:12 +01:00
Xavier Ordoquy
d4fbd6e531 Merge pull request #3898 from auvipy/dev
updated readme with commands from recent versions of django
2016-02-03 11:05:29 +01:00
Xavier Ordoquy
ea796fa071 Merge pull request #3897 from zvovov/master
typo in docs - tutorial part 1
2016-02-03 11:04:20 +01:00
auvipy
0d4db85e8c updated readme with commands from recent versions of django 2016-02-03 16:01:37 +06:00
Chirag Khatri
62551bc80f typo in tutorial part 1 2016-02-03 15:25:31 +05:30
Mikalai Radchuk
1f2a32d506 Fixes docstrings in fields.py
Fixes docstrings for `to_choices_dict` and `flatten_choices_dict` functions in fields.py.

Mistakes were introduced in #4d69286
2016-02-03 12:36:00 +03:00
José Padilla
0512c394a3 Merge pull request #3875 from m1kola/bugfix/HTMLFormRenderer-render-renderer_context-default
Fixes AttributeError in HTMLFormRenderer.render
2016-02-01 16:28:11 -04:00
Xavier Ordoquy
ee23ef9907 Merge pull request #3889 from jpadilla/update-django
Update Django versions
2016-02-01 20:43:24 +01:00
José Padilla
37d1d3e738 Update Django versions 2016-02-01 15:36:11 -04:00
Xavier Ordoquy
dce544ec59 Merge pull request #3887 from mnach/enhancement-3886
enhancement #3886 Internationalization in admin interface for authtoken
2016-02-01 10:10:48 +01:00
Mikhail Nacharov
d0f7b04805 enhancement #3886 Internationalization in admin interface rest_framework.authtoken
+ verbose_name in models.Token fields
+ Meta-options verbose_name & verbose_name_plural
+ Labels in AuthTokenSerializer fields in case of usages in Brousable API
+ provide AppConfig class as described in django documentation with verbose_name came through ugettext_lazy
2016-02-01 13:20:16 +05:00
Xavier Ordoquy
d738ad7ae6 Update to serialization results (closes #3881). 2016-01-27 22:23:20 +01:00
Mikalay Radchuk
714607307e Fixes AttributeError in HTMLFormRenderer.render
If `HTMLFormRenderer.render` will be called with default arguments,
`AttributeError: 'NoneType' object has no attribute 'get'` will be raised.
2016-01-26 21:26:30 +03:00
Xavier Ordoquy
72372efdb6 Merge pull request #3867 from jamesbeith/docs-example-fixes
Fix syntax errors in docs example
2016-01-24 18:16:02 +01:00
James Beith
34901a5ffa Fix syntax errors in docs example
- Add missing comma in kwargs
- Remove spaces around keyword / parameter equals
- Replace incorrect curly brace with parenthesis
2016-01-24 13:33:18 +00:00
Xavier Ordoquy
f2d6013134 Merge pull request #3866 from ekonstantinidis/more-drf-docs-info
Mention Live API Endpoints for DRF Docs
2016-01-24 00:14:49 +01:00
Emmanouil Konstantinidis
ee2861887e Mention DRF Docs - Live API Endpoints 2016-01-23 23:08:19 +00:00
Xavier Ordoquy
909a3e80a1 Merge pull request #3861 from linovia/feature/relation_get_queryset_override
Refactor the `get_queryset` overriding test
2016-01-21 18:10:32 +01:00
Xavier Ordoquy
5068ecf64b Rename the get_queryset overriding test. 2016-01-21 16:50:07 +01:00
Xavier Ordoquy
6d95da7b2d Improve the get_queryset overriding test readability. 2016-01-21 16:48:32 +01:00
Xavier Ordoquy
98fc7caad8 Merge pull request #3860 from linovia/bug/leave_token_abstract
Restore the abstract on Token model when the app isn't declared
2016-01-21 13:44:08 +01:00
Xavier Ordoquy
9e8ddb88fc Restore the abstract on Token model when the app isn't declared
The fact that we don't import Token from authentication doesn't invalidate
the need for the model to be abstract whenever the authtoken isn't listed
in the INSTALLED_APPS.
2016-01-21 13:28:32 +01:00
José Padilla
06dd55ac1c Merge pull request #3853 from jpadilla/issue/3850
Fix broken link format
2016-01-20 15:23:25 -04:00
José Padilla
99a61d72a7 Fix broken link format 2016-01-20 14:04:04 -04:00
Xavier Ordoquy
328000fb34 Merge pull request #3624 from d6bels/master
Login form autofocus
2016-01-20 18:21:03 +01:00
Xavier Ordoquy
f1b28b4d63 Merge pull request #3605 from ryanhiebert/slug-related-field-queryset
RelatedField get_queryset and context
2016-01-20 18:17:29 +01:00
Xavier Ordoquy
f1522d3e35 Merge pull request #3851 from szuliq/patch-1
Update link to Heroku guidelines
2016-01-20 16:37:27 +01:00
Krzysztof Szularz
2d40be5bd8 Update link to Heroku guidelines
They seem to have changed the structure of the document.
2016-01-20 16:28:30 +01:00
Xavier Ordoquy
5ed8a53929 Merge pull request #3849 from linovia/feature/py35_build
Activate the Python 3.5 build.
2016-01-20 14:18:06 +01:00
Xavier Ordoquy
7fa18ba939 Merge remote-tracking branch 'reference/master' into feature/py35_build 2016-01-20 14:12:05 +01:00
Xavier Ordoquy
ed40b319be Removing Python 3.5 build from the expected failure. 2016-01-20 14:11:58 +01:00
Xavier Ordoquy
fb302d6010 Use the Python 3.5 env. 2016-01-20 13:53:53 +01:00
Xavier Ordoquy
9cfac9193d Merge pull request #3846 from linovia/feature/workaround-pip-8
Maintain py32 test builds
2016-01-20 12:43:28 +01:00
Xavier Ordoquy
e6d1eb375c Add a comment about virtualenv < 14 2016-01-20 11:53:32 +01:00
Xavier Ordoquy
b53f6691f4 Preserve the former indentation. 2016-01-20 11:45:23 +01:00
Xavier Ordoquy
ebec88ccab Remove the no-pip option. 2016-01-20 11:06:51 +01:00
Xavier Ordoquy
64e1fe7518 Try downgrading virtualenv. 2016-01-20 10:59:57 +01:00
Xavier Ordoquy
1a7e81b00b Workaround to avoid pip-8 installation. 2016-01-20 10:44:50 +01:00
Xavier Ordoquy
e7fbd264ca Merge pull request #3703 from sniegu/master
Add missing csrf_token in AdminRenderer post form.
2016-01-19 16:58:39 +01:00
Xavier Ordoquy
c2e94709a0 Merge pull request #3842 from linovia/markdown-compat
Markdown compat (overtakes #3604)
2016-01-19 16:47:01 +01:00
Xavier Ordoquy
8ea7d6b5c6 Merge remote-tracking branch 'origin/master' into markdown-compat
Conflicts:
	requirements/requirements-optionals.txt
2016-01-19 15:34:56 +01:00
José Padilla
50749c4730 Merge pull request #3841 from linovia/feature/3776
Fix update model example in html-and-forms.md
2016-01-18 14:16:13 -04:00
Xavier Ordoquy
221d6979c6 Fix the request data source. 2016-01-18 18:54:00 +01:00
Xavier Ordoquy
0051492963 Merge remote-tracking branch 'shvechikov/master' into feature/3776 2016-01-18 18:51:53 +01:00
Xavier Ordoquy
6f8e0c3c07 Merge pull request #3289 from koliber/update-docs-serilaizers-multi-update
Added explicit id field in multi update example
2016-01-18 18:44:03 +01:00
Tom Christie
69e1489a6f Merge pull request #3839 from pra85/patch-1
Update license year range to 2016
2016-01-18 09:29:36 +00:00
Prayag Verma
b24fb53d98 Update license year range to 2016 2016-01-18 12:28:24 +05:30
Xavier Ordoquy
db73833d13 Merge pull request #3835 from vyscond/patch-1
Update permissions.md
2016-01-15 15:48:24 +01:00
Ramon Moraes
a37a8748cc Update permissions.md
Adding additional note about the behavior of set permission classes per view as suggest on #3834
2016-01-15 11:44:25 -03:00
Xavier Ordoquy
30ef38c861 Merge pull request #3833 from bradmontgomery/patch-1
QueryParameterVersioning does not use default version
2016-01-14 20:33:05 +01:00
Brad Montgomery
40b5774a33 QueryParameterVersioning does not use default version
QueryParameterVersioning does not fall back to the value used in the `DEFAULT_VERSION` setting, while other versioning schemes do. This looks like a minor change, and incorporates the `self.default_version` set in the superclass.

I'll sheepishly admit that I edited this inline without running any tests or anything, so please let me know if this needs more work.
2016-01-14 12:00:30 -06:00
Tom Christie
2ce3ab59a6 Merge pull request #3746 from linovia/feature/display_internal_pytest_warnings
Display py.test internal warnings
2016-01-14 15:25:41 +00:00
Xavier Ordoquy
b76bf3d6d2 Merge pull request #3832 from atombrella/warnings_20_fkeys
Regarding #3729
2016-01-14 15:31:31 +01:00
Tom Christie
29f84aa4a3 Merge pull request #3831 from ticosax/doc-tweak-admin-authtoken
Document how to tweak authtoken.admin.TokenAdmin
2016-01-14 14:16:41 +00:00
Mads Jensen
215e1b6c6b Regarding #3729
python -Werror generates warnings informing that on_delete is a required keyword in Django 2.0
2016-01-14 15:14:33 +01:00
Nicolas Delaby
717e27c866 Document how to tweak authtoken.admin.TokenAdmin
With focus on large user base, but can be extended.
2016-01-14 14:59:31 +01:00
Tom Christie
01b1d100c5 Merge pull request #3826 from atombrella/copyright_update
2015 update in __init__.py file
2016-01-13 12:15:37 +00:00
Mads Jensen
a9c394f5b7 2015 update in __init__.py file 2016-01-13 12:54:56 +01:00
Tom Christie
1c5dfc9c8d Merge pull request #3821 from zwernberg/master
update copyright 2016
2016-01-11 16:25:11 +00:00
Zach Wernberg
04b2f021a6 update copyright 2016 2016-01-11 08:13:07 -06:00
Xavier Ordoquy
efe2c3739d Merge pull request #3809 from areski/fix-timefield
Fixed TimeField not handling empty values
2016-01-11 12:28:28 +01:00
areski
4e01796303 Test for TimeField not handling empty values 2016-01-11 12:16:26 +01:00
areski
a76c3ed051 Fixed TimeField not handling empty values 2016-01-11 12:14:40 +01:00
Xavier Ordoquy
edd9c7de02 Merge pull request #3819 from m1kola/bug/DateField-to_representation-unicode-compatibility
PY2: DateField.to_representation can't work with unicode value
2016-01-11 11:29:50 +01:00
Mikalai Radchuk
6b207d93d6 DateField.to_representation unicode compatibility 2016-01-11 13:11:01 +03:00
José Padilla
057cf13578 Merge pull request #3815 from atombrella/keys_dict_3786
Fixes #3786
2016-01-09 22:47:53 -04:00
Xavier Ordoquy
69fb34b0db Merge pull request #3810 from jerel/patch-1
Added documentation for the third party jsonapi.org package
2016-01-07 21:11:59 +01:00
Jerel Unruh
f71d8afdb0 Added documentation for the Third Party jsonapi.org package 2016-01-07 13:42:02 -06:00
Tom Christie
f01a3d9c36 Merge pull request #3801 from koordinates/fix-nested-validation-error
Fix nested validation error being rendered incorrectly.
2016-01-07 09:22:23 +00:00
Mads Jensen
d4cdb21de9 Fixes #3786
Minor fix for dictionary key lookup in settings file
2016-01-06 22:51:11 +01:00
Tom Christie
f7025cf5e5 Merge pull request #3805 from kewama/issue-3804
Fixes #3804, avoiding update of Meta.extra_kwargs
2016-01-06 20:25:00 +00:00
Kevin Massey
7cd3933144 Fixes #3804, avoiding update of Meta.extra_kwargs
Added unit test to cover.
2016-01-06 15:04:51 -05:00
Xavier Ordoquy
c46ed66d0a Merge pull request #3803 from m1kola/patch-1
Typo fix in docs/api-guide/relations.md
2016-01-06 16:02:16 +01:00
m1kola
5fa8a31855 Typo fix in docs/api-guide/relations.md
`slug field` in code snippet was replaced to `slug_field`
2016-01-06 17:58:45 +03:00
Craig de Stigter
651319e2da Fix nested validation error being rendered incorrectly.
Previously an extra list wrapped nested validation errors raised from serializer's validate() methods.
That was inconsistent with the format of validation errors raised by validate_<fieldname> methods.
i.e. these two resulted in *different* behaviour:

    def validate_foo(self):
        raise ValidationError(['bar'])

    def validate(self):
        raise ValidationError({'foo': ['bar']})
2016-01-06 16:05:43 +13:00
Tom Christie
37f7b76f72 Merge pull request #3785 from sheppard/authtoken-import
don't import authtoken model until needed
2016-01-05 17:28:48 +00:00
S. Andrew Sheppard
4f40714169 fix import order 2016-01-05 10:20:22 -06:00
S. Andrew Sheppard
2b8c036b48 test custom token model 2016-01-05 09:58:16 -06:00
S. Andrew Sheppard
1712c00001 update invalid token case 2016-01-05 09:42:22 -06:00
Xavier Ordoquy
dceb686700 Merge pull request #3774 from tomchristie/decimalfield_validators
Min/MaxValueValidator is no longer transferred from a model's DecimalField
2016-01-04 16:36:44 +01:00
Kevin Brown
a772326112 Merged two DecimalValidator tests together
These two tests were previously added in
7d79cf35b7
but we have now discovered that there are not actually two separate
cases, there was just a  bug in the code that made it look that way.

This also removes a redundant check to see if `DecimalValidator` was
defined.
2016-01-04 10:22:17 -05:00
Xavier Ordoquy
060444d89f Merge pull request #3791 from craigglennie/patch-1
Make code block consistent in serialization tutorial
2016-01-04 08:00:13 +01:00
craigglennie
2d7d3b79a0 Make code block consistent in serialization tutorial
All the other code blocks in the Serialization tutorial can be copied and pasted, but there is one that includes the >>> shell prompt characters. This commit removes those characters, and also makes the output consistent with other code blocks by making it a comment.
2016-01-02 13:15:25 -08:00
Xavier Ordoquy
dafbe65ff6 Merge pull request #3787 from Cheglader/issue_3636
Initial fixes #3636 and fixes #3637
2016-01-01 11:11:42 +01:00
Luis San Pablo
183f8fad44 Class formatting 2015-12-31 21:18:41 -06:00
Luis San Pablo
ef491685a0 Initial fixes #3636 and fixes #3637 2015-12-31 21:14:57 -06:00
S. Andrew Sheppard
ff29fdd875 don't import authtoken model until needed 2015-12-30 15:44:19 -06:00
Tom Christie
af0ea8ef51 Merge pull request #3771 from robromano/master
Add HTTP status code 451 to status.py
2015-12-29 09:59:48 +00:00
Leonid Shvechikov
ff0292a757 Fix update model example in html-and-forms.md 2015-12-27 17:14:33 +03:00
Kevin Brown
d797389cf7 Fixed broken test for Django < 1.9
This test was incorrectly checking that there were no validators set in
older versions of Django, even though it should have been checking for
the two validators that were set up on the model field level.

The originally regression test that this fixes was added in
7d79cf35b7
when fixing an issue with the `DecimalValidator`.
2015-12-24 18:17:58 -05:00
Kevin Brown
87605e1e39 Don't filter out the DecimalValidator if it is not supported
Previously, all validators set on a DecimalField in Django would be
stripped when converted to a Django REST framework field. This was
because any validator that was an instance of `DecimalValidator` would
be removed, and when `DecimalValidator` wasn't supported (so it was
`None`), all validators would be removed.

This fixes the issue by only removing the `DecimalValidator` instances
if the `DecimalValidator` is supported.
2015-12-24 14:10:48 -05:00
Kevin Brown
9bab640b0a Added tests for min_value and max_value on a DecimalField
This adds tests for a regression where the `min_value` and `max_value`
arguments are not being set for a DRF `DecimalField` even though the
corresponding `MinValueValidator` and `MaxValueValidator` is being set
on the model fields.

Note that this only appears to be a regression for Django < 1.9, as
these regression tests pass on newer versions of Django.
2015-12-24 14:00:49 -05:00
Robert Romano
c8915c0716 Change tab to spaces 2015-12-23 12:58:14 -08:00
Robert Romano
5fc938cbd1 The Internet Engineering Task Force approved the new HTTP status code 451. Adding to status.py and docs appropriately. 2015-12-23 12:54:17 -08:00
Tom Christie
2d27d9a10a Merge pull request #3769 from mlissner/master
Fixes #3756, adding the name to the HTML title, if it exists.
2015-12-23 16:58:29 +00:00
Michael Lissner
f15026be10 Fixes #3756, adding the name to the HTML title, if it exists. 2015-12-22 10:31:18 -08:00
José Padilla
503687d868 Merge pull request #3765 from linovia/feature/fix_guardian_for_dj_19
Update the Django-guardian version for Django 1.9
2015-12-21 16:59:03 -04:00
Xavier Ordoquy
c5003e8dc1 Update the Django-guardian version for Django 1.9 2015-12-21 18:02:24 +01:00
Tom Christie
ce77ed81df Merge pull request #3762 from ekonstantinidis/add-drf-docs
Add DRF docs to "Documenting your API"
2015-12-21 16:47:44 +00:00
Emmanouil Konstantinidis
1925ec7d33 Both are highly recommended 2015-12-21 13:59:05 +00:00
Emmanouil Konstantinidis
4204557bc5 Remove title and hr 2015-12-21 13:55:11 +00:00
Emmanouil Konstantinidis
958290724c Rest is "REST" 2015-12-21 13:47:04 +00:00
Emmanouil Konstantinidis
a83cb1d2f3 Minor changes 2015-12-21 13:45:11 +00:00
Emmanouil Konstantinidis
1aedaafba4 Add DRF docs to the list 2015-12-21 13:40:23 +00:00
Xavier Ordoquy
5ddfb25fbc Merge pull request #3758 from toolness/patch-1
Update bootstrap version in browsable-api.md
2015-12-19 17:17:06 +01:00
Atul Varma
66de876dee Update bootstrap version in browsable-api.md 2015-12-19 10:34:39 -05:00
Tom Christie
18cdfcd712 Merge pull request #3731 from mjparker777/master
Issue 3726 DateTimeField not handling empty values
2015-12-18 11:27:12 +00:00
Tom Christie
61e7f7b0cc Merge pull request #3715 from Cheglader/settings_errors
Raise error when setting a removed rest_framework setting for #3644
2015-12-18 11:19:06 +00:00
mjparker777
d9c360845d changed datefield to match code layout of datetime and time changes 2015-12-17 12:21:44 -07:00
mjparker777
f3d5e1482b Merge remote-tracking branch 'upstream/master' 2015-12-17 12:20:47 -07:00
Tom Christie
6eb3a42993 Merge pull request #3753 from tomlinford/master
Subclass AutoFilterSet from self.default_filter_set
2015-12-17 14:10:13 +00:00
Luis San Pablo
c389aeb051 Lint import ordring 2015-12-16 18:46:23 -06:00
Luis San Pablo
62e2a9706f Fixed import order settings 2015-12-16 18:37:50 -06:00
Luis San Pablo
dab6bf4b1a Changed error to warning message 2015-12-16 18:35:02 -06:00
Tom Linford
c78980771d AutoFilterSet should subclass from self.default_filter_set 2015-12-16 15:36:07 -08:00
José Padilla
034e26ea31 Merge pull request #3748 from DanLipsitt/patch-1
docstring typo fix: DateAndFiles -> DataAndFiles
2015-12-16 15:05:59 -04:00
Dan Lipsitt
fb94be18be docstring typo fix: DateAndFiles -> DataAndFiles 2015-12-16 10:42:10 -08:00
Xavier Ordoquy
00ead782d4 Merge pull request #3747 from pbaehr/master
Move urls.py changes down and add necessary import
2015-12-16 18:22:26 +01:00
Tom Christie
26f948c836 Merge pull request #3745 from linovia/feature/py35_support
Fix tox build against python 3.5 by upgrading pytest.
2015-12-16 12:48:12 +00:00
Xavier Ordoquy
a4ce897d28 Display py.test internal warnings 2015-12-16 13:27:40 +01:00
Xavier Ordoquy
aab7da4891 Updated py.test and pytest-django to test against python 3.5. 2015-12-16 13:08:37 +01:00
Peter Baehr
44ae037e81 Move urls.py changes down and add necessary import
The previous location of editting urls.py did not allow migrations to be created and the default import needs to be modified
2015-12-15 21:17:52 -05:00
Xavier Ordoquy
e3274af0ef Merge pull request #3741 from tyrelsouza/master
Some minor typos and grammar changes.
2015-12-15 18:29:12 +01:00
Tyrel Souza
8c0d736f23 Also fix usecases to use cases 2015-12-15 10:28:23 -05:00
Tyrel Souza
ffc10edd7e Fix minor typo on Pagination documentation 2015-12-15 10:24:49 -05:00
Xavier Ordoquy
3a950f53b0 Merge pull request #3739 from nypisces/master
Fix transifex config for Django
2015-12-15 09:22:42 +01:00
NY
613e0d41ac Update config 2015-12-15 15:22:19 +08:00
NY
c45fdee2ab Fix transfix config for Django 2015-12-15 15:22:03 +08:00
Xavier Ordoquy
552707381e Merge pull request #3733 from linovia/version/3.3.2
Version 3.3.2
2015-12-14 13:47:31 +01:00
Xavier Ordoquy
ef8bde2d42 Bump version to 3.3.2 2015-12-14 07:33:17 +01:00
Xavier Ordoquy
5224feded4 Update the release date. 2015-12-14 07:32:50 +01:00
Xavier Ordoquy
485c297a04 Translations update. 2015-12-14 07:31:38 +01:00
Xavier Ordoquy
bf18c9f6e3 3.3.2 release notes. 2015-12-14 07:22:30 +01:00
mjparker777
decc5fa901 Merge remote-tracking branch 'upstream/master' 2015-12-13 17:51:06 -07:00
mjparker777
fc08236ab8 updated timefield also 2015-12-13 16:09:56 -07:00
mjparker777
81775dfbae added missing comma 2015-12-13 12:27:08 -07:00
mjparker777
bf60c08010 Issue 3726 DateTimeField not handling empty values 2015-12-13 12:21:13 -07:00
José Padilla
df071d5555 Merge pull request #3723 from linovia/bug/authtoken_versionning_compat
Add extra args/kwargs to authtoken's views (#3718)
2015-12-13 14:53:13 -04:00
Xavier Ordoquy
dcaff71217 Merge pull request #3728 from karthik-suresh/Fixes-Issue3727
Import parser added to docs in API guide
2015-12-12 22:19:13 +01:00
Karthik Suresh
82973cfa32 Import parser added to docs in API guide
Added missing import statements in code snippet of API guide.

Closes-Issue: #3727
2015-12-12 21:59:08 +05:30
Luis San Pablo
fbd89d6b7e Moved SETTINGS_DOC 2015-12-12 02:02:53 -06:00
Tom Christie
ff4bc43a2f Merge pull request #3721 from raphaelmerx/rm-format
Fixed suggestion for format in test renderer
2015-12-11 09:13:48 +00:00
Xavier Ordoquy
7a5d81c0b4 Add extra args/kwargs to authtoken's views (#3718) 2015-12-11 07:16:04 +01:00
Raphael Merx
fcc0a70f7c Fixed suggestion for format in test renderer
Rendered would suggest using format='JSON' when the right argument is
format='json'.
2015-12-10 15:19:03 -08:00
Xavier Ordoquy
e83175323b Merge pull request #3714 from knbk/set_app_name
Add app_name to rest_framework.urls.
2015-12-08 09:59:11 +01:00
Luis San Pablo
a615e37277 Removed depreceated constant 2015-12-07 23:30:45 -06:00
Luis San Pablo
b6e59c33a7 Merge branch 'settings_errors' of github.com:Cheglader/django-rest-framework into settings_errors 2015-12-07 23:25:49 -06:00
Luis San Pablo
5802dc0f98 Initial, fixes #3644 2015-12-07 23:25:40 -06:00
Luis San Pablo
60c4fe10b1 Refactor Constants 2015-12-07 23:19:24 -06:00
Luis San Pablo
0f85165b69 Fixed num args for % 2015-12-07 22:36:02 -06:00
Luis San Pablo
5117dad2ca removed setting typo 2015-12-07 22:32:23 -06:00
Luis San Pablo
4be3535b04 Merge branch 'settings_errors' of github.com:Cheglader/django-rest-framework into settings_errors 2015-12-07 22:31:58 -06:00
Luis San Pablo
9db4c2ae8a --ammend 2015-12-07 22:31:09 -06:00
Luis San Pablo
1b3e4332e8 --ammend 2015-12-07 22:24:22 -06:00
Luis San Pablo
4e5c57ab46 type on test case 2015-12-07 22:19:58 -06:00
Luis San Pablo
03c7f149ac Test case for settings check 2015-12-07 22:17:33 -06:00
Luis San Pablo
13c66b9dfe Return error 2015-12-07 21:53:33 -06:00
Luis San Pablo
d86a901aff Removed Settings raise attribute error 2015-12-07 21:45:44 -06:00
knbk
e203967e09 Add app_name to rest_framework.urls.
This allows users in Django 1.9+ to include the authentication urls
without specifying the namespace, as in:

    urlpatterns = [
        ...
        url(r'^auth/', include('rest_framework.urls'))
    ]
2015-12-08 02:25:00 +01:00
Xavier Ordoquy
f3949e994d Update base translation file. 2015-12-07 18:56:47 +01:00
Tom Christie
c227b8188e Merge pull request #3705 from mcastle/patch-2
Admin and API browser fails for views without a filter_class
2015-12-07 10:10:24 +00:00
Xavier Ordoquy
6bbb2890cb Merge pull request #3701 from Cheglader/master
Fix #3628 by implementing __getnewargs__()
2015-12-07 10:45:06 +01:00
Xavier Ordoquy
b8d109f2cf Merge pull request #3709 from qrilka/patch-1
Fixed versioning regexp
2015-12-07 10:22:59 +01:00
Kirill Zaborsky
85db6a681b Fixed versioning regexp
booking list regexp was fixed in 8b97bb8f68 but single booking wasn't for some reason, and `v1v2/bookings/123/` shouldn't be allowed here
2015-12-07 10:59:57 +03:00
Marlon
c1b70538a2 Resolve #3596
Uses #3597, but without using `Context`.
2015-12-05 11:10:39 -06:00
Piotr Śniegowski
2faa7bc288 Add missing csrf_token in AdminRenderer post form. 2015-12-04 23:23:56 +01:00
Luis San Pablo
4b59681c60 Fixed Class Newlines 2015-12-04 05:57:09 +00:00
Luis San Pablo
84b5e41af8 Fixes #3628 2015-12-04 05:48:56 +00:00
Luis San Pablo
4092cef392 Fixed Test Case for Hyperlink 2015-12-04 05:42:46 +00:00
Luis San Pablo
8501f59216 Hyperlink Test Case 2015-12-04 05:30:39 +00:00
Luis San Pablo
dfc84d9818 Force Build 2015-12-03 21:17:21 +00:00
Luis San Pablo
44a3d41ce9 Implement __getnewargs__ for #3628 2015-12-03 21:12:03 +00:00
Tom Christie
9f74b8860e Merge pull request #3687 from benred42/3679-UUIDField-validation
Fixed #3679 -- UUID Validation
2015-12-02 10:04:54 +00:00
Xavier Ordoquy
17267bfc32 Merge pull request #3689 from jpadilla/django19
Use latest release of Django 1.9
2015-12-02 08:15:53 +01:00
José Padilla
eba6229b24 Use latest release of Django 1.9 2015-12-01 21:44:22 -04:00
bphillips
c153bcb479 Added validation to UUIDField to properly catch invalid input types (lists, tuples, etc). 2015-12-01 14:09:10 -05:00
José Padilla
d2f90fd6af Merge pull request #3662 from awwester/ticket_3228
#3228 - add confirm modal for delete
2015-12-01 10:50:34 -04:00
Adam Wester
6d1ed851b5 #3228 - add confirm modal for delete 2015-12-01 07:51:29 -05:00
Tom Christie
832d6322a7 Merge pull request #3631 from syphar/paginat
allow setting a custom Django Paginator class
2015-11-30 20:58:32 +00:00
Tom Christie
bd8098e31f Fix template typo.
Closes #3682.
Thanks for the report!
2015-11-30 17:21:41 +00:00
José Padilla
68285a9bc2 Merge pull request #3683 from nikolas/patch-2
Add missing link to django-crispy-forms
2015-11-30 12:18:04 -04:00
Nik Nyby
e3f62e230c Add missing link to django-crispy-forms 2015-11-30 10:48:56 -05:00
Tom Christie
8dea1aeed0 Merge pull request #3677 from Ernest0x/patch-4
Updated NestedBoundField to also handle empty string when rendering its form
2015-11-27 13:21:58 +00:00
Petros Moisiadis
3594c976b7 Added test case for rendering nested fields with none value 2015-11-27 15:07:29 +02:00
Tom Christie
0d0aff44ac Merge pull request #3668 from akx/exc-hiding
Reveal previously hidden AttributeErrors and TypeErrors
2015-11-27 11:51:25 +00:00
Aarni Koskela
69688289ce Ensure Django{Model,Object}Permissions don't hide exceptions.
Quietly catching `AttributeError` and `TypeError` when calling
`get_queryset()` is rather insidious, as those exceptions get caught no
matter where they might happen in the call stack.
2015-11-27 12:46:30 +02:00
Tom Christie
0e4ea2a591 Merge pull request #3676 from akx/tests-on-windows
Make tests pass on Windows too
2015-11-26 15:08:24 +00:00
Petros Moisiadis
570187b959 Updated NestedBoundField to also handle empty string when rendering its form
If a NestedBoundField field has a value of `None` and is inside another NestedBoundField field, it will have its value converted to an empty string while the form of its enclosing field is being rendered. So, NestedBoundField fields with an empty string value must be handled the same way as NestedBoundField fields with a `None` value.
2015-11-26 17:07:57 +02:00
Aarni Koskela
47c9bb143c Fix smart_repr() to also clean upper-case hex addresses.
Windows Pythons seem to like printing addresses in upper-case, while Linux
Pythons like lower-case hexes.

This led to an amusing (for a given value of "amusing", anyway) situation
where some repr tests would fail if the objects they were testing happened
to be allocated at an address with a hex digit in the range A..F.
2015-11-26 15:48:04 +02:00
Aarni Koskela
bdf9c4997d Add types to isort's standard library list.
This re-stabilizes sorting after upgrading to 4.2.2.
2015-11-26 15:42:49 +02:00
Aarni Koskela
45c66dae42 Upgrade isort to 4.2.2.
This gets rid of a file encoding bug that occurs on Windows boxes where
the default implied encoding is cp1252, but the files themselves aren't.

The actual patch that seems to fix this is
1057d5e12e
but it seems like a good idea to upgrade to the latest and greatest.
2015-11-26 15:40:22 +02:00
Aarni Koskela
6dcb994c98 Upgrade transifex-client dependency to 0.11
Version 0.11b3's setup.py had an undeclared dependency on `py2exe` when
running on Windows (see
https://github.com/transifex/transifex-client/blob/0.11b3/setup.py#L23),
which made it impossible to install without having a working `py2exe` to
begin with.

This has been fixed in 0.11 proper.
2015-11-26 15:29:19 +02:00
José Padilla
200dda91ac Merge pull request #3675 from pt247/master
Fix for Incorrect regex in URLPathVersioning documentation #3638
2015-11-26 07:14:58 -04:00
Prashant Tiwari
8b97bb8f68 Fix for Incorrect regex in URLPathVersioning documentation #3638 2015-11-26 06:23:59 +00:00
Xavier Ordoquy
d0352ae6fc Merge pull request #3621 from linovia/feature/how_to_turn_pagination_off
Document how to turn pagination off
2015-11-25 12:57:25 +01:00
Tom Christie
6fd9813882 Merge pull request #3672 from linovia/feature/multitemplate
Make DRF compatible with multi template engine in Django 1.8
2015-11-25 11:45:50 +00:00
Xavier Ordoquy
d6c326623f Make DRF compatible with multi template engine in Django 1.8 2015-11-25 07:37:01 +01:00
Xavier Ordoquy
ff0eeaf77a Merge pull request #3670 from jpadilla/django-versions
Update Django versions
2015-11-24 19:42:17 +01:00
José Padilla
3bcb7dba8c Update Django versions 2015-11-24 14:23:14 -04:00
José Padilla
c7bf99330e Merge pull request #3663 from blueyed/doc-crispy-installed
doc: clarify that crispy-forms needs to be in INSTALLED_APPS
2015-11-23 10:21:53 -04:00
Daniel Hahler
e786e4c4a1 doc: clarify that crispy-forms needs to be in INSTALLED_APPS 2015-11-23 15:05:38 +01:00
Tom Christie
a8deb380ff Merge pull request #3660 from sloria/patch-1
Fix typo in docstring for ReadOnlyField
2015-11-21 10:09:26 +00:00
Steven Loria
b209fe04fc Fix typo in docstring for ReadOnlyField 2015-11-20 13:51:21 -05:00
Tom Christie
f30f25facc Merge pull request #3656 from andreif/fix/deprecated-related
Fix #3252 -- Use related_objects api for Django 1.9+
2015-11-19 12:22:23 +00:00
Andrei Fokau
2acc6a756c Use related_objects api for Django 1.9+ 2015-11-19 13:04:37 +01:00
Xavier Ordoquy
f3de2146ea Merge pull request #3650 from silviogutierrez/master
Documentation fix for list serializers.
2015-11-19 07:46:01 +01:00
Silvio J. Gutierrez
ece7973479 Updated comment. 2015-11-18 21:52:20 -05:00
Tom Christie
378b7b8963 Merge pull request #3655 from andreif/fix/headers-order
Sort response headers in api renderer
2015-11-18 17:25:54 +00:00
Xavier Ordoquy
edc5a79b85 Merge pull request #3497 from Ins1ne/feature/3340
update docs about detail page link for AdminRenderer
2015-11-18 17:38:07 +01:00
Andrei Fokau
8692816401 Sort response headers in api renderer to keep the same order 2015-11-18 17:33:12 +01:00
Ryan Hiebert
a19f152065 Note possibility of overriding get_queryset 2015-11-18 10:26:00 -06:00
Tom Christie
43c45cc939 Merge pull request #3654 from andreif/fix/deprecation-warning-1.9
Fix template.render deprecation warnings for Django 1.9
2015-11-18 16:19:09 +00:00
Andrei Fokau
802ee5d0ea Fix template.render deprecation warnings for 1.9+ 2015-11-18 17:06:35 +01:00
Ryan Hiebert
389b48e394 Avoid making a new module for this function 2015-11-18 08:19:27 -06:00
Tom Christie
04158e187e Merge pull request #3513 from pattisdr/feature/ListField_needs_to_enforce_list
ListField does not enforce that input is a list
2015-11-18 12:19:40 +00:00
Silvio J. Gutierrez
f7646627f1 Documentation fix for list serializers. 2015-11-17 19:09:49 -05:00
Tom Christie
75a63c2c2e Merge pull request #3643 from jpadilla/django19-rc
Test against Django 1.9rc1
2015-11-17 14:03:42 +00:00
José Padilla
e2ac148367 Test against Django 1.9rc1 2015-11-17 09:58:55 -04:00
José Padilla
5cde5c6adf Merge pull request #3642 from willdady/master
Removing references to get_paginate_by() as it no longer exists.
2015-11-17 09:44:50 -04:00
Will Dady
ca0841576f Removing references to get_paginate_by() as it no longer exists. 2015-11-17 15:00:00 +11:00
Ryan Hiebert
dca2de3a5c Make the override check a utility function 2015-11-16 12:21:58 -06:00
Tom Christie
316c374b02 Merge pull request #3635 from martinhill/issue_3634
Relation fields no to_fields attribute attribute break serializer
2015-11-16 16:20:38 +00:00
Martin Hill
ff36cbe4ba same logic, more pythonic 2015-11-14 23:04:32 -05:00
Martin Hill
bac6f1fcf4 check if field.to_fields is None 2015-11-14 18:26:29 -05:00
Martin Hill
e475464945 fix for issue #3634 2015-11-14 17:00:07 -05:00
Ryan Hiebert
fe12816b82 Move default validation back into init method 2015-11-13 15:16:27 -06:00
Dawn Pattison
3ddbf92bf9 Remove unicode from exception value. 2015-11-13 10:41:57 -05:00
Dawn Pattison
5fdc4f22cf Add tests to ensure ListField does not except dictionary as input. 2015-11-13 10:17:09 -05:00
Denis Cornehl
3806af3d15 allow setting a custom Django Paginator in pagination.PageNumberPagination 2015-11-13 16:04:12 +01:00
Xavier Ordoquy
4eef2ea21e Merge pull request #3600 from nfletton/fix/browser/single-tab-render
Fix regression causing raw data form to not display
2015-11-13 13:24:47 +01:00
Tom Christie
5899b00dac Merge pull request #3626 from linovia/bug/fix_failing_py35_test_case
Fix module name with Python 3.5 (#3534)
2015-11-12 10:01:36 +00:00
Xavier Ordoquy
795cf4716d Fix module name with Python 3.5 2015-11-11 17:44:46 +01:00
d6bels
82eb4c8d71 Login form autofocus 2015-11-11 10:51:20 +01:00
Xavier Ordoquy
23460bfa41 Add a note about how to turn pagination off 2015-11-10 11:33:54 +01:00
Michael J. Schultz
f308900a5f Bump the markdown optional requirement as well 2015-11-09 11:48:17 -06:00
Michael J. Schultz
abc6fa05e6 Markdown 2.1 compatible 2015-11-09 11:47:00 -06:00
Tom Christie
944a1711ec Merge pull request #3606 from ryanhiebert/tox-no-basepython
Don't specify unnecessary basepython
2015-11-06 08:14:08 +01:00
Ryan Hiebert
f2452936e9 Allow no queryset when get_queryset overridden
The user may wish to provide a dynamic queryset on a `RelatedField`
based on the `context`. The way to do that is to create a subclass of
`RelatedField` (or a child) and override the `get_queryset` method.
However, this is undocumented, and instantiating that field without a
`queryset` argument (because it's not needed) will raise an assertion
error.

Document `.get_queryset(self)` as an official part of the API of
`RelatedField`, and don't enforce the use of `queryset` when
`get_queryset` is overridden.
2015-11-05 17:34:02 -06:00
Ryan Hiebert
240eb672af Don't specify basepython
tox automatically includes basepython definitions for all the common
python versions, and will recognize it in factors of envs in the
envlist.
2015-11-05 12:12:29 -06:00
Michael J. Schultz
b2e74fb523 Use markdown 2.6 extension_configs to configure extension 2015-11-05 10:52:31 -06:00
Michael J. Schultz
d9d34e4886 Use full python dot path to extension 2015-11-05 10:48:19 -06:00
Michael J. Schultz
276bc3bc2b Remove safe_mode since it is not safe. 2015-11-05 10:47:56 -06:00
Xavier Ordoquy
2704036ad5 Merge pull request #3602 from vkaracic/patch-1
Typo
2015-11-05 11:52:52 +01:00
Vedran Karačić
ede15645e0 Typo 2015-11-05 11:51:29 +01:00
nfletton
f85ad301eb Fix regression causing raw data form to not display 2015-11-04 15:43:25 -07:00
Tom Christie
7d59991636 Merge pull request #3595 from jpadilla/update-version
Test against Django 1.8.6
2015-11-04 22:14:13 +00:00
José Padilla
08a00ce46d Test against Django 1.8.6 2015-11-04 13:27:19 -04:00
Tom Christie
d959c6337a Release notes 2015-11-04 14:59:09 +00:00
Tom Christie
33b512b1f2 Version 3.3.1 2015-11-04 14:49:57 +00:00
Tom Christie
544c24e7cb Merge pull request #3593 from tomchristie/primary-key-check-for-to-field
Proper 'primary key' checking on to_fields.
2015-11-04 14:49:11 +00:00
Tom Christie
54b79db214 Proper 'is primary key' checking 2015-11-04 14:37:32 +00:00
Tom Christie
95f92e995c Merge pull request #3560 from ericholscher/fix-empty-filter
Allow HTML to render when no filter_class is defined.
2015-11-04 14:20:03 +00:00
Tom Christie
bfdf795843 Merge pull request #3592 from tomchristie/request-parsing-when-post-accessed
Request parsing when .POST accessed
2015-11-04 14:17:55 +00:00
Tom Christie
d587ad1021 Use REST framework request parsing when accessing old-style .POST 2015-11-04 14:10:51 +00:00
Xavier Ordoquy
950e5e0fec Merge pull request #3589 from ryanhiebert/docs-custom-hyperlinks
docs - reverse needs kwargs keyword
2015-11-04 08:05:41 +01:00
Ryan Hiebert
b86e5af878 reverse needs kwargs keyword
Since we aren't passing in any args, we must specify kwargs as a keyword
argument.
2015-11-03 21:45:21 -06:00
Tom Christie
ae008316fa Merge pull request #3585 from TravisJMorton/patch-1
typo
2015-11-02 21:30:47 +00:00
Travis J Morton
03cb959416 typo 2015-11-02 12:58:21 -08:00
Tom Christie
63ac8ac4ab Merge pull request #3553 from adamzap/doc-section-permalinks
Add section permalinks to docs
2015-11-02 16:18:22 +00:00
Tom Christie
d6b9cf6b6b Merge pull request #3583 from davidszotten/filtering-docs-images
fix image paths
2015-11-02 15:34:13 +00:00
David Szotten
9a14613f41 fix image paths 2015-11-02 15:28:02 +00:00
José Padilla
119a073299 Merge pull request #3576 from michael-k/readme
Updated readme to reflect 3.3 release
2015-10-30 08:15:54 -04:00
Michael K
aa5331de8e Updated readme to reflect 3.3 release 2015-10-30 13:04:44 +01:00
Xavier Ordoquy
ce491b3424 Merge pull request #3568 from jpadilla/decimal-validator
Add compat util for DecimalValidator
2015-10-30 12:54:08 +01:00
José Padilla
7d79cf35b7 Add regression test for DecimalField mapping 2015-10-30 07:47:11 -04:00
José Padilla
08e4a98822 Merge pull request #3564 from mcastle/patch-1
Fix trans template tag error on admin
2015-10-30 06:29:25 -04:00
Xavier Ordoquy
48b0efbe2f Merge pull request #3572 from jamesbeith/docs-missing-import-for-example
Adds import for `Response`
2015-10-29 16:55:35 +01:00
James Beith
0143586541 Adds import for Response 2015-10-29 15:48:45 +00:00
Xavier Ordoquy
eeafd40ccd Merge pull request #3571 from JocelynDelalande/patch-2
typo on relations docstring
2015-10-29 16:23:55 +01:00
JocelynDelalande
3b25207099 typo 2015-10-29 16:20:44 +01:00
Xavier Ordoquy
dd512a8ec0 Merge pull request #3570 from mrhwick/third-party-docs
Added django-rest-framework-version-transforms.
2015-10-29 15:49:49 +01:00
Matthew Hardwick
86e1d2a1e5 Actually add the link. 2015-10-29 10:43:57 -04:00
Matthew Hardwick
f7289e6392 Added django-rest-framework-version-transforms. 2015-10-29 10:37:46 -04:00
José Padilla
41d1e42e9c Add compat util for DecimalValidator 2015-10-29 06:42:16 -04:00
José Padilla
6f6f794be5 Merge pull request #3566 from jcugat/announcement-typo
Fix announcement link typo
2015-10-29 06:13:58 -04:00
Josep Cugat
5b7de4f537 Fix announcement link typo 2015-10-29 10:21:46 +01:00
Marlon
3c6ce9dfc0 Fix trans template tag error
Trans template tag requires `{% load i18n %}` at top of template.
2015-10-28 22:47:52 -05:00
Eric Holscher
32bd1a2f0b Use better names for filter variable 2015-10-28 14:36:24 -07:00
José Padilla
a67d23139c Merge pull request #3556 from rense/master
format_html was missing in optional_logout template-tag
2015-10-28 17:16:36 -04:00
Eric Holscher
378d6a1a19 Allow HTML to render when no filter_class is defined.
Previously it required a filter_class,
or else it would error when calling `cls()`.
This now sets the `filter` context to `None`
if one does not exist.

Fixes #3559
2015-10-28 12:39:20 -07:00
Rense VanderHoek
0d568ed59f format_html was missing in optional_logout template-tag
The new format_html() was still missing in optional_logout template-tag
at the NoReverseMatch exception.
2015-10-28 18:48:58 +01:00
Rense VanderHoek
6aef157daa Merge remote-tracking branch 'tomchristie/master' 2015-10-28 18:39:18 +01:00
José Padilla
b8c9c809ff Merge pull request #3547 from nikolas/bootstrap-3.3.5
Update bootstrap from 3.2.0 to 3.3.5
2015-10-28 09:42:01 -04:00
Tom Christie
bb555e6e5e Version 3.3.0 2015-10-28 11:32:15 +00:00
Tom Christie
372acbc4e9 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-10-28 11:21:06 +00:00
Tom Christie
144cff97fa Include billing addresses in funding sign ups 2015-10-28 11:20:35 +00:00
Adam Zapletal
edf97be7be Add section permalinks to docs
- Configure mkdocs to use the toc markdown extension
- Only show section link styles on hover
2015-10-27 15:20:59 -05:00
Tom Christie
fa6f053323 Merge pull request #3544 from dursk/nested-as-form-fields
Correctly handle False in NestedBoundField.as_form_field()
2015-10-27 16:55:36 +00:00
Tom Christie
f7ea425001 Merge pull request #3546 from jpadilla/format-html
Use format_html in tags that generate HTML
2015-10-27 14:12:25 +00:00
Nik Nyby
8c6ded38de Update bootstrap from 3.2.0 to 3.3.5 2015-10-26 10:40:59 -04:00
José Padilla
21cad8646a Use format_html in tags that generate HTML 2015-10-25 08:31:28 -04:00
Matthew Madurski
8aed3d4862 Correctly handle false in nested as_form_field 2015-10-24 19:48:17 -04:00
Tom Christie
af5474f9b3 Merge pull request #3539 from tomchristie/funding
Funding
2015-10-23 16:54:21 +01:00
Tom Christie
eeff5a1709 Merge branch 'master' into funding 2015-10-23 16:27:30 +01:00
Tom Christie
84e9013417 Merge pull request #3531 from tomchristie/version-3.3
Version 3.3
2015-10-23 16:24:08 +01:00
Tom Christie
b2fb0deb34 Add latest item to the release notes 2015-10-23 16:15:44 +01:00
Tom Christie
0fb1ebcfcf Remove unused import 2015-10-23 16:07:48 +01:00
Tom Christie
9a78db2707 Merge pull request #3536 from jpadilla/filepathfield-mapping
Map all supported FilePathField options
2015-10-23 15:23:26 +01:00
José Padilla
d64bfef56a Map all supported FilePathField options 2015-10-23 10:08:29 -04:00
auvipy
fa93d79026 removed south_migrations directory 2015-10-23 10:00:01 -04:00
auvipy
b71e6b596f removed south migrations 2015-10-23 10:00:00 -04:00
Tom Christie
ff285cfe66 TODO placeholder in release announcement 2015-10-22 15:15:55 +01:00
Tom Christie
7bfc420dc9 Add release notes, drop deprecated test 2015-10-22 15:11:10 +01:00
Tom Christie
4e7cc68ec9 Link tweaks 2015-10-22 14:42:35 +01:00
Tom Christie
ae852b2be4 Tweak links 2015-10-22 14:08:19 +01:00
Tom Christie
07b23c8685 Add version 3.3 to the docs index 2015-10-22 14:06:55 +01:00
Tom Christie
cf33008571 Release notes etc 2015-10-22 14:05:52 +01:00
Tom Christie
c53c9eddfe Merge pull request #3315 from tomchristie/filters
First pass at HTML rendering for filters
2015-10-22 11:42:35 +01:00
Tom Christie
0c6d46729c Docs on the filter HTML interface 2015-10-22 11:37:27 +01:00
Tom Christie
6305ae8916 Merge pull request #3475 from tomchristie/forms-api
Forms API
2015-10-22 09:59:57 +01:00
Xavier Ordoquy
71338ddd3f Merge pull request #3528 from peterdemin/patch-1
Fixed grammar in docs for "Writable nested serializers"
2015-10-21 15:35:23 +02:00
Peter Demin
423e0de358 Fixed grammar in docs for "Writable nested serializers" 2015-10-21 09:33:34 -04:00
Tom Christie
58faebcdb1 Merge pull request #3526 from likeon/fk-to_field
Added support for the to_field on ForeignKey fields
2015-10-21 14:00:32 +01:00
likeon
322bda8159 Added support for the to_field on ForeignKey fields 2015-10-21 15:33:18 +03:00
José Padilla
825e67454d Merge pull request #3527 from potpath/patch-2
Fix broken link caused by case sensitivity
2015-10-21 08:03:07 -04:00
potpath
9634cea474 Fix broken link caused by case sensitivity 2015-10-21 18:43:07 +07:00
Dawn Pattison
8fa7c5c914 Exclude collections.Mapping from allowable data types in ListField 2015-10-20 08:56:39 -04:00
Tom Christie
c68d932ac9 Merge pull request #3525 from tomchristie/django-19-beta
Test against Django 1.9 beta
2015-10-20 11:02:30 +01:00
Tom Christie
5b5d6f1d4b Test against Django 1.9 beta 2015-10-20 10:53:45 +01:00
Tom Christie
0d1637d666 Minor docs update 2015-10-20 10:49:39 +01:00
José Padilla
4e24374c14 Merge pull request #3521 from agconti/master
docs(third-party-resources): added `cookiecutter-django-rest` to misc third party resources
2015-10-19 21:35:31 -04:00
Tom Christie
34eb18b498 Merge branch 'master' into filters
Conflicts:
	rest_framework/compat.py
	rest_framework/filters.py
2015-10-19 13:14:42 +01:00
Tom Christie
86470b7813 Merge pull request #3517 from thedrow/feature/set-and-dict-literals
Replaced all dict and set conversions from lists to dict and set literals
2015-10-19 09:46:36 +01:00
agconti
6757da5aab docs(third-party-resources): added cookiecutter-django-rest to misc third party resources 2015-10-18 20:13:09 -04:00
Omer Katz
2e178bc970 Replaced all dict and set conversions from lists to dict and set literals. 2015-10-17 12:00:11 +03:00
Dawn Pattison
dac1637bb3 Use set instead of Set 2015-10-16 16:06:18 -04:00
Dawn Pattison
b9316154b1 Add tuple and Set to allowed ListField data types 2015-10-16 16:02:13 -04:00
José Padilla
df025f3d98 Merge pull request #3515 from Photonomie/doc-typo
Missing the `source=` keyword for the URLField parameter
2015-10-16 15:41:12 -04:00
Dawn Pattison
f808f08a0d Require that data is a list. 2015-10-16 14:43:43 -04:00
Pierre Dulac
dc72fb4746 Missing the source= keyword for the URLField parameter 2015-10-16 19:43:00 +02:00
Tom Christie
c94b354efa Merge pull request #3509 from jpadilla/textfield-max-length
Map TextField max_length to CharField
2015-10-16 12:31:26 +01:00
José Padilla
a1dad503cf Map TextField max_length to CharField 2015-10-16 07:17:33 -04:00
Xavier Ordoquy
1b4a41cb80 Merge pull request #3502 from auvipy/master
removed south migrations
2015-10-15 10:41:07 +02:00
auvipy
4db2501399 removed south_migrations directory 2015-10-15 14:17:56 +06:00
auvipy
392df94693 removed south migrations 2015-10-15 14:16:35 +06:00
Xavier Ordoquy
5570db402f Merge pull request #3501 from ztanner/patch-1
Various typo/grammar fixes
2015-10-15 08:21:22 +02:00
Zack Tanner
6fe021eea7 Various typo fixes 2015-10-14 19:09:11 -07:00
Aider Ibragimov
4a6d27ccbb update style of the note 2015-10-14 17:04:47 +03:00
José Padilla
ad001143c9 Merge pull request #3498 from Ins1ne/feature/admin_renderer_jquery
fix typo for adding jquery string in AdminRenderer
2015-10-14 09:06:52 -04:00
Aider Ibragimov
79008ea210 fix typo for adding jquery string in AdminRenderer 2015-10-14 15:56:26 +03:00
Aider Ibragimov
5342f22009 return typo back for new pr, update docs 2015-10-14 15:54:43 +03:00
Aider Ibragimov
b19865f88d fix typo in adding jquery string, update docs about detail page link for AdminRenderer 2015-10-14 15:14:35 +03:00
Tom Christie
90247afe29 Docs on Forms API 2015-10-12 21:14:58 +01:00
Xavier Ordoquy
68312cb0bc Merge pull request #3488 from demokrates/patch-1
Update versioning.md
2015-10-12 10:25:39 +02:00
demokrates
47c9d2a4d3 Update versioning.md
Changed settings attribute 'VERSION_PARAMETER' --> to 'VERSION_PARAM'.
2015-10-12 10:10:08 +02:00
Rense VanderHoek
c774a4c378 Merge branch 'master' of https://github.com/rense/django-rest-framework 2015-10-10 23:18:16 +02:00
Xavier Ordoquy
fa1cfae991 Merge pull request #3485 from dulmandakh/dulmandakh-guardian-check-installed-apps
Update compat.py
2015-10-09 08:13:42 +02:00
Dulmandakh
431ac45168 Update compat.py
try to import guardian if it's in INSTALLED_APPS
2015-10-09 11:03:19 +08:00
Tom Christie
85cd717ec0 Merge pull request #3481 from nryoung/fix-codecov
Fix codecov on Travis CI
2015-10-08 19:47:33 +01:00
Nic Young
739d3892c5 Fix codecov on Travis CI
The coverage report needs to be explicitly created with arguments passed
in to pytest-cov
2015-10-07 22:20:46 -07:00
Tom Christie
41182c6f06 Formns API 2015-10-06 10:58:20 +01:00
Xavier Ordoquy
6fb96e93ef Merge pull request #3469 from PhilipGarnero/patch-1
Added django-rest-framework-social-oauth2 to list of third party packages
2015-10-03 07:48:50 +02:00
Philip Garnero
3cdd3c5f6e Added django-rest-framework-social-oauth2 to list of third party packages 2015-10-02 14:30:27 -07:00
Tom Christie
63662e352d Merge pull request #3461 from mcastle/patch-1
Use serializers.ValidationError in AuthTokenSerializer
2015-10-02 11:07:20 +01:00
Xavier Ordoquy
689afd83cc Merge pull request #3462 from theengineear/patch-1
Small doc typo `throttles` --> `throttling`
2015-10-01 10:22:55 +02:00
Andrew
f60c0e99f6 Small doc typo throttles --> throttling 2015-10-01 14:25:04 +07:00
Marlon
670b0b710b Use serializers.ValidationError
Per django rest framework docs, and to prevent confusion with Django's ValidationError, `serializers.ValidationError` is preferred to `exceptions.ValidationError`.
2015-09-30 21:09:37 -05:00
Xavier Ordoquy
cadbfbabe2 Merge pull request #3459 from rhblind/master
Added drf-haystack to third party resources
2015-09-30 10:26:58 +02:00
Rolf Håvard Blindheim
0e56b2ea74 Added drf-haystack to third party resources 2015-09-30 10:24:21 +02:00
Xavier Ordoquy
71c37762d6 Merge pull request #3457 from pombredanne/patch-1
Fixed minor doc typo.
2015-09-29 22:00:44 +02:00
Philippe Ombredanne
3262ee6c90 Fixed minor doc typo. 2015-09-29 21:59:09 +02:00
Tom Christie
de5732f393 Merge pull request #3454 from tomchristie/json-field
Added JSONField.
2015-09-28 17:52:58 +01:00
Tom Christie
265ec8ac62 Handle binary or unicode with JSONField 2015-09-28 17:47:51 +01:00
Tom Christie
dad207de66 Don't attempt to test dicts (unordered) 2015-09-28 17:41:09 +01:00
Tom Christie
ec8098b7e2 Work around 2.x/3.x json.dumps() return type fuzziness 2015-09-28 17:32:36 +01:00
Tom Christie
10dbf1316f Added JSONField. Closes #3170. 2015-09-28 17:25:52 +01:00
Tom Christie
bae47b7f36 Merge pull request #3453 from tomchristie/remove-content-overriding
Remove content overriding
2015-09-28 16:42:42 +01:00
Tom Christie
ed677f0138 Update docs for content overriding 2015-09-28 16:37:48 +01:00
Tom Christie
c64896c849 More cleanup of browser overrides 2015-09-28 15:33:55 +01:00
Tom Christie
d7142e23ac Merge branch 'master' into remove-content-overriding 2015-09-28 15:15:50 +01:00
Tom Christie
3d7740fbf3 Merge pull request #3450 from tomchristie/django-19-alpha
Django 1.9 support
2015-09-28 12:01:59 +01:00
Tom Christie
02e1f69d2b Django 1.9 support 2015-09-28 11:44:07 +01:00
Tom Christie
c4211ce7d8 Merge pull request #3449 from tomchristie/carltongibson-drop-django-16
Drop django 16
2015-09-28 11:23:23 +01:00
Tom Christie
2d0b54e263 Merge branch 'drop-django-16' oft https://github.com/carltongibson/django-rest-framework into carltongibson-drop-django-16
Conflicts:
	docs/topics/release-notes.md
2015-09-28 11:17:48 +01:00
Tom Christie
4762a73e34 Merge pull request #3342 from tomchristie/version-3.3
Compat updates for version 3.3
2015-09-28 11:06:42 +01:00
Tom Christie
ca8313aeac Merge branch 'master' into version-3.3
Conflicts:
	docs/topics/release-notes.md
2015-09-28 10:57:14 +01:00
Tom Christie
6284bceaaf Merge pull request #3363 from tomchristie/dont-access-settings-on-import
Access settings lazily, not at module import.
2015-09-24 15:42:31 +01:00
Tom Christie
509c54de9b Merge pull request #3435 from stianjensen/unique-error
Use model error_messages when available
2015-09-24 13:10:14 +01:00
José Padilla
c28bc9896e Merge pull request #3433 from atombrella/base_html_fix
fixing a trivial HTML tag which is closed twice
2015-09-23 11:56:16 -04:00
Stian Jensen
62c000bc12 Use model error_messages when available
In the automatically applied UniqueValidator, use the error message from
error_messages defined in the model instead of the generic default
UniqueValidator message.

This fixes #2878.
2015-09-23 15:20:44 +02:00
Tom Christie
51443166a8 Merge pull request #3431 from paolopaolopaolo/issue-3265
Guard against calling `serializer.data` before `serializer.save()`
2015-09-23 09:51:54 +01:00
Mads Jensen
8a82a07f8d fixing a trivial HTML tag which is closed twice 2015-09-23 10:51:23 +02:00
Xavier Ordoquy
7661398a4a Merge pull request #3420 from linovia/release/3.2.4
Release/3.2.4
2015-09-23 01:51:07 +02:00
paolopaolopaolo
7640bfea9e Add assert statement to .save() method in Serializer:
- Asserts that `_data` does not exist when calling `.save()`
2015-09-22 11:49:51 -07:00
paolopaolopaolo
134f5fa4bc Fixes #3265 (now with Test Case)
- Added test_data_access_before_save_raises_error test
2015-09-22 11:40:19 -07:00
Carlton Gibson
8d740a11e4 Adjust README and Release Notes 2015-09-22 16:39:25 +02:00
Carlton Gibson
45ace5010e Remove OrderedDict fallback 2015-09-22 16:35:38 +02:00
Carlton Gibson
0b34408172 Remove unittest.skipUnless 2015-09-22 16:24:22 +02:00
Carlton Gibson
6e86a53c92 Remove apps.get_model fallback
* Corrects presumed logic error in `ResolveModelWithPatchedDjangoTests`
2015-09-22 16:14:45 +02:00
Carlton Gibson
68c88e180f Remove ContentType import fallback 2015-09-22 15:55:39 +02:00
Carlton Gibson
5c0dffa4f7 Remove Django 1.6 from test matrix 2015-09-22 15:39:51 +02:00
Tom Christie
eccf7cc7ac Merge pull request #3427 from carltongibson/exlude-guardian
Exclude Guardian testing against Django master
2015-09-22 14:32:42 +01:00
Carlton Gibson
524a28c6f8 Exclude Guardian testing against Django master 2015-09-22 15:14:25 +02:00
Tom Christie
5b2b675a21 Merge pull request #3421 from carltongibson/supported-versions-2
Drop Django 1.5
2015-09-22 12:48:11 +01:00
Tom Christie
41b796d844 Merge pull request #3426 from uruz/feature/fix-typo
Typo in test method name
2015-09-22 10:26:38 +01:00
Alexey Boriskin
0155a44aac Typo in test method name 2015-09-22 12:13:01 +03:00
Carlton Gibson
2aa33ed544 Adjust README and Release Notes 2015-09-21 20:23:39 +02:00
Carlton Gibson
8ea1606abf Remove Django 1.5 clean_manytomany_helptext fallback 2015-09-21 20:16:52 +02:00
Carlton Gibson
25de8c960f Remove Django 1.5 get_model_name fallback 2015-09-21 20:10:31 +02:00
Carlton Gibson
4a1ab3c18c Fix isort errors 2015-09-21 16:29:33 +02:00
Carlton Gibson
e625cff8a5 Remove Django 1.5 URLValidator fallback 2015-09-21 16:22:46 +02:00
Carlton Gibson
9216dc9a25 Remove Django 1.5 EmailValidator fallback 2015-09-21 16:20:07 +02:00
Carlton Gibson
8edb9d3c1f Drop testing against Django 1.5 2015-09-21 16:08:56 +02:00
Carlton Gibson
366dff4f26 Test Python 3.5 against Django master 2015-09-21 16:03:37 +02:00
Carlton Gibson
796baab86f Drop Pythons 3.2, 3.3 for Django master
No longer supported
2015-09-21 15:47:11 +02:00
Xavier Ordoquy
6ee3e29460 Add #3415 to the 3.2.4 release 2015-09-21 13:28:59 +02:00
Xavier Ordoquy
1054ea559c Fix the issue link. 2015-09-21 13:28:37 +02:00
Xavier Ordoquy
26715c2dae Merge remote-tracking branch 'origin/master' into release/3.2.4 2015-09-21 13:25:49 +02:00
Xavier Ordoquy
f2c65512c6 Merge pull request #3415 from adamsc64/issue_2761
Fixed #2761 - ListField truncation on HTTP PATCH
2015-09-21 13:06:44 +02:00
Xavier Ordoquy
089b8af4c1 Update the translations. 2015-09-21 08:07:56 +02:00
Xavier Ordoquy
d0510438b2 Bump version to 3.2.4. 2015-09-20 22:04:25 +02:00
Xavier Ordoquy
d85e7b9ccc Update Release notes for 3.2.4. 2015-09-20 22:03:52 +02:00
Xavier Ordoquy
df26614e85 Translation update. 2015-09-20 21:59:47 +02:00
Christopher Adams
9ccfc94077 Fixed #2761 - ListField truncation on HTTP PATCH
- Checked ``partial`` state when getting value in appropriate field
  classes; return ``empty`` immediately if key not submitted.
2015-09-19 10:18:04 -04:00
Christopher Adams
cb42b995fa Proof of bug #2761
- When not submitting key for list fields or multiple choice, partial
  serialization should result in empty state (key not there), not an
  empty list.
2015-09-19 10:17:57 -04:00
Tom Christie
eec1156f63 AJAX forms in admin interface 2015-09-17 16:53:28 +01:00
Tom Christie
b8ebe29844 Import sorting 2015-09-17 16:40:47 +01:00
Tom Christie
343fd5ec3d Merge branch 'canassa-method-not-allowed-not-raised' into remove-content-overriding 2015-09-17 16:39:30 +01:00
Tom Christie
66e372200f Merge branch 'method-not-allowed-not-raised' of https://github.com/canassa/django-rest-framework into canassa-method-not-allowed-not-raised 2015-09-17 16:38:42 +01:00
Tom Christie
4b4130e8b2 Fix request cloning, so method becomes set 2015-09-17 16:34:03 +01:00
Xavier Ordoquy
b1a5294a1a Merge pull request #3411 from yiyocx/patch-1
Improved Serializer relations docs
2015-09-17 17:33:53 +02:00
Yiyo
7df11078ee Improved Serializer relations docs 2015-09-17 10:30:22 -05:00
Tom Christie
a3067bea55 Merge branch 'master' into version-3.3 2015-09-17 16:24:46 +01:00
Tom Christie
566812ac0b Remove method and content overriding 2015-09-17 15:17:29 +01:00
Xavier Ordoquy
8cae462b3a Merge pull request #3401 from nryoung/update-transifex-client-reqs
Update transifex-client requirement to latest release version 0.11b3
2015-09-15 08:29:46 +02:00
Nic Young
4e7d0493db Update transifex-client requirement to latest release version 2015-09-14 21:05:28 -07:00
José Padilla
fc2e98c8cb Merge pull request #3400 from James1345/master
added knox package reference to 3rd party auth apps
2015-09-14 14:49:05 -04:00
James McMahon
6baca94830 added knox package reference to 3rd party auth apps 2015-09-14 19:34:07 +01:00
Tom Christie
b7d77d5bf2 Merge pull request #3396 from qqbuby/3395
fix issue #3395
2015-09-14 10:22:20 +01:00
qqbuby
1aa16caffe append a space after the comment mark to remain consistent with the other parts of the tutorial 2015-09-13 20:24:22 +08:00
José Padilla
2424ab02e8 Merge pull request #3397 from nryoung/add-serpy
Add link to serpy serialization
2015-09-13 07:38:01 -04:00
Nic Young
5c076e10bb Add link to serpy serialization, fixes #3391 2015-09-12 23:04:18 -07:00
Tom Christie
31539e1a21 Merge pull request #3393 from sloria/booleanfield-fix
Correctly handle [] and {} as invalid inputs to BooleanField
2015-09-12 07:20:56 +01:00
Steven Loria
284f9faa07 Correctly handle [] and {} as invalid inputs to BooleanField 2015-09-11 23:12:18 -04:00
qqbuby
1a8f9d0a0f fix issue #3395 to correct the output text at line 184in docs/tutorial/1-serialization.md 2015-09-12 01:36:40 +08:00
Tom Christie
a67eed1466 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-09-11 13:06:18 +01:00
Tom Christie
ab296ced4e Add link to django REST marshmallow 2015-09-11 13:06:09 +01:00
Tom Christie
5401440324 Merge pull request #3388 from nryoung/field-level-validation-note
Add note about field level validation, fixes #3306
2015-09-11 09:42:28 +01:00
Nic Young
4704da9a1a Add note about field level validation, fixes #3306
The documentation added warns the user that field level validation will
be skipped if the field is declared on the model with the parameter
`required=False`.
2015-09-10 22:55:55 -07:00
Xavier Ordoquy
cd4c389d1f Merge pull request #3382 from outime/patch-1
Fixed typo in ScopedRateThrottle example views
2015-09-10 10:16:29 +02:00
Xavier Ordoquy
b6b33b567e Merge pull request #3360 from lubomir/improve-docs-for-default
Improve documentation of default argument for fields
2015-09-10 10:15:17 +02:00
Rubén Díaz
671de792e2 Fixed typo in ScopedRateThrottle example views 2015-09-10 10:19:40 +03:00
Tom Christie
a985fc521f Merge pull request #3364 from linovia/bug/3361
Don't pass `allow_empty` to `ListSerializer`'s children.
2015-09-09 09:28:25 +01:00
Xavier Ordoquy
aa48182686 Add test coverage on allow_empty for nested serializers. 2015-09-07 23:11:01 +02:00
Tom Christie
b57e9cf405 Test protected branches 2015-09-07 10:22:44 +01:00
Xavier Ordoquy
4404d40f60 Only pass allow_empty to the ListSerializer if it was in the arguments.
Helps with backward compatibility.
2015-09-06 23:02:44 +02:00
Xavier Ordoquy
7ccdd015ae Merge pull request #3368 from potpath/patch-1
Update 6-viewsets-and-routers.md
2015-09-04 11:31:24 +02:00
potpath
bb95de13bf Update 6-viewsets-and-routers.md 2015-09-04 16:07:20 +07:00
Tom Christie
f9e53091c1 Drop handling of ImproperlyConfigured 2015-09-03 16:40:12 +01:00
Tom Christie
8b7ebb9d2c Fixed import sorting 2015-09-03 16:29:13 +01:00
Xavier Ordoquy
dcdd765647 Avoid passing allow_empty to the ListSerializer children. 2015-09-03 17:27:33 +02:00
Tom Christie
10da18b20b Access settings lazily, not at module import 2015-09-03 16:24:13 +01:00
Tom Christie
39ec564ae9 Do not access settings on compat import 2015-09-03 14:22:13 +01:00
Tom Christie
7905e9f9f4 Docs tweak 2015-09-03 11:57:11 +01:00
Tom Christie
e9e88cbc60 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-09-03 11:24:07 +01:00
Tom Christie
f9d1a34fdd Fix nested HTML dictionaries. Closes #3314. 2015-09-03 11:23:58 +01:00
Tom Christie
afd2a8f8f0 Adjust ModelField.null mappings now that Django-25320 is resolved 2015-09-03 10:12:52 +01:00
Lubomír Sedlář
a57ad07674 Add link to validators
The `set_context` method there is the same as for the default field.
2015-09-03 10:35:28 +02:00
Tom Christie
ec007a7e2d Merge pull request #3359 from raphaelmerx/master
DurationField accepts integers
2015-09-03 09:30:45 +01:00
Lubomír Sedlář
1c049edd8c Improve documentation of default argument for fields
The documentation now not only mentions that callables are acceptable
arguments, it also tells the reader what the callable should look like.
2015-09-03 09:46:54 +02:00
raphaelmerx
b9782b6850 DurationField accepts integers 2015-09-02 16:47:50 -07:00
Tom Christie
d48ec83688 Merge pull request #3358 from brittdawn/3357-self-tag-name-to-generic-relationships-docs
Replacing self.tag with self.tag_name in Generic Relationships documentation.
2015-09-02 18:19:41 +01:00
Britt Dawn
7c12a988fa Replacing self.tag with self.tag_name in Generic Relationships documentation. 2015-09-02 09:25:00 -07:00
Xavier Ordoquy
4dfc66e45d Merge pull request #3352 from miki725/url-filter
Added django-url-filter to 3rd party libraries
2015-09-01 08:52:57 +02:00
Miroslav Shubernetskiy
6926c71699 added django-url-filter to 3rd party libraries 2015-08-31 21:23:11 -04:00
Tom Christie
f87573ffa3 Merge pull request #3345 from jpadilla/fields
Update ModelSerializer 'fields'/'exclude'/'__all__' behavior
2015-08-28 14:57:05 +01:00
Tom Christie
f34777a2e9 Translations for HTML filters 2015-08-28 14:55:22 +01:00
José Padilla
9dd1b2516b Update ModelSerializer fields docs 2015-08-28 09:51:11 -04:00
koliber
dae5426e20 Changed formatting and updated docs 2015-08-28 15:35:32 +02:00
Tom Christie
3a0d54c7fb Fix testing example. Closes #3346 2015-08-28 13:52:18 +01:00
Tom Christie
78632849cf Comment against model_field.null 1.98 behavior 2015-08-28 13:29:57 +01:00
José Padilla
1fe8e9a0bf Add note on deprecation path 2015-08-28 08:11:07 -04:00
José Padilla
f3ef13ab59 Update to match docs on ModelForm fields 2015-08-28 08:05:20 -04:00
Tom Christie
8db6367188 Deal with 1.9's differing null behavior on reverse relationships and m2m 2015-08-28 12:08:32 +01:00
Tom Christie
b51c1ff0b0 Django 1.9's test case HttpResponse.json() is not cachable. 2015-08-28 11:55:23 +01:00
Tom Christie
7560e8381f Drop unused patterns 2015-08-28 10:53:44 +01:00
Tom Christie
6fa534f214 Fix urlpatterns in test 2015-08-28 10:44:49 +01:00
Tom Christie
a5ddd90df0 Log in and log out require escape and mark_safe 2015-08-28 10:27:49 +01:00
Tom Christie
24a2c3f5c3 Resolve unittest compat 2015-08-28 10:19:18 +01:00
Tom Christie
25c4c7f9fd Pep8 fix 2015-08-28 10:03:16 +01:00
Tom Christie
e70da5ac6b Compat for GenericForeignKey, GenericRelation 2015-08-28 10:03:08 +01:00
José Padilla
654e0e4527 Update ModelSerializer fields behavior 2015-08-27 13:09:08 -04:00
Tom Christie
4f27697467 Fix get_model import 2015-08-27 17:28:12 +01:00
Tom Christie
f691006f2c Resolve generic fields import 2015-08-27 17:16:19 +01:00
Tom Christie
48540f180a unittest compat fallback 2015-08-27 17:11:53 +01:00
Tom Christie
9aca6442a7 Add to the roadmap 2015-08-27 15:31:21 +01:00
Tom Christie
0b77e733a8 Don't display filter control on detail views 2015-08-27 14:35:39 +01:00
Tom Christie
9bcb1477e2 Minor tweaks 2015-08-27 14:28:28 +01:00
Tom Christie
aeb57913c9 Filter HTML refinments 2015-08-27 14:25:44 +01:00
Tom Christie
ea630bf3d1 Merge branch 'master' into filters 2015-08-27 14:02:15 +01:00
Tom Christie
f646b469d4 Copy tweaks 2015-08-26 13:22:18 +01:00
Tom Christie
eb37f90dcd Tweak buisiness case 2015-08-26 13:09:22 +01:00
Tom Christie
32946f4160 Tweaks to roadmap 2015-08-25 14:03:30 +01:00
Tom Christie
8264222497 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-08-25 13:32:42 +01:00
Tom Christie
086115c7b8 Clean up after publishing to PyPI 2015-08-25 13:32:35 +01:00
Tom Christie
3666b3f975 Merge pull request #3325 from slava-sh/patch-1
Fix typo
2015-08-24 19:45:19 +01:00
Slava Shklyaev
49d799c454 Fix typo 2015-08-24 21:09:08 +03:00
Tom Christie
1ba879278a Merge pull request #3324 from Rikuoja/master
Don't error on missing `search_fields` attribute.
2015-08-24 15:20:52 +01:00
Rikuoja
65df9fd5c6 Fix #3323 2015-08-24 17:02:49 +03:00
Tom Christie
0198bce34f Release 3.2.3 2015-08-24 10:59:52 +01:00
Tom Christie
b271946b31 Merge pull request #3321 from tomchristie/empty-charfield-html
Resolve empty HTML charfield behavior.
2015-08-24 10:41:36 +01:00
Tom Christie
9ac646385f Resolve empty HTML charfield behavior. Closes #3318. 2015-08-24 10:13:16 +01:00
Tom Christie
9758838d86 Merge pull request #3320 from jpadilla/master
Bump up maximum supported Django versions
2015-08-22 16:38:40 +01:00
José Padilla
01fa2647c9 Bump up maximum supported Django versions 2015-08-22 08:49:05 -04:00
Tom Christie
8527a2c9d2 Merge pull request #3316 from purple-sunrise/iregexp_search
Regex search option
2015-08-21 17:01:03 +01:00
borzdyko
f0782b9451 Doc for regex search filter 2015-08-21 18:26:23 +03:00
borzdyko
21d0e51831 Test for regex search filter 2015-08-21 18:23:39 +03:00
Tom Christie
5db900c625 First pass at HTML rendering for filters 2015-08-21 16:13:52 +01:00
borzdyko
314daaedfa Using https://docs.djangoproject.com/en/1.8/ref/models/querysets/#regex for search filter by starting field with '$' 2015-08-21 18:13:13 +03:00
Tom Christie
f601c6c1c3 Merge pull request #3313 from tomchristie/limit-selects
Limit rendering of relational selects to max 1000 items by default.
2015-08-21 11:41:55 +01:00
Tom Christie
c271568bf5 Remove erronous checkin 2015-08-21 10:57:46 +01:00
Tom Christie
314c0095aa iter_options function should have no cutoff by deault 2015-08-21 10:56:22 +01:00
Tom Christie
99beeb80e1 No cutoff for default ChoiceField, only for relationships 2015-08-21 10:53:10 +01:00
Tom Christie
f4412d0827 Docs for select cutoffs 2015-08-21 10:52:44 +01:00
Tom Christie
490f0c9f34 Merge branch 'callorico-master' 2015-08-20 12:39:25 +01:00
Tom Christie
b6c4d8c25a Resolve duplicate error for IPAddressField. Closes #3250. 2015-08-20 12:38:48 +01:00
Tom Christie
0f77c27d34 Merge branch 'master' of https://github.com/callorico/django-rest-framework into callorico-master 2015-08-20 12:30:33 +01:00
Tom Christie
75be91912c Allow AdminRenderer to function when pagination is disabled. Closes #3275. 2015-08-20 12:28:00 +01:00
Tom Christie
d86fd67895 Fix display of select multiple HTML fields. Closes #3290. 2015-08-20 12:11:14 +01:00
Tom Christie
b4b2dc18fa Clean-up refactoring of SearchFilter implementation 2015-08-20 11:35:32 +01:00
Tom Christie
aa4cd7e9d7 Guard against LimitOffsetPagination edge case. Closes #3303. 2015-08-20 10:12:52 +01:00
Tom Christie
1de197aa8d Tweaks for funding page 2015-08-20 10:10:06 +01:00
Tom Christie
ed65db367a Merge pull request #3300 from jpadilla/listfield-child
Raise error when `source=` use on a child.
2015-08-19 18:23:14 +01:00
José Padilla
8af366a732 Raise error when source= use on a child.
Closes #3292
2015-08-19 12:32:16 -04:00
Tom Christie
dd850df1d8 Merge pull request #3299 from kennydude/patch-1
Add import to example for filtering
2015-08-19 15:01:04 +01:00
Joe Simpson
a4af8cc623 Add import to example for filtering
`from rest_framework import filters` was missing from one of the examples
2015-08-19 14:44:40 +01:00
Tom Christie
c958d5d447 Redirect from www. to fund. when needed. 2015-08-19 12:35:23 +01:00
Tom Christie
0dc9f285be Paid plans title -> Funding 2015-08-19 12:16:00 +01:00
Tom Christie
7b0252a91c Merge pull request #3296 from FlorianHoornaar/patch-1
Fix typos in comments
2015-08-19 07:32:14 +01:00
Florian Hoornaar
1b5bc07d4c Fix typos in comments 2015-08-19 03:55:39 +02:00
koliber
2946251c91 Added explicit id field in multi update example
If the id field is implicitly created, it is created as `read_only=True`. This causes the data validation step to remove the id values in the validated data.
2015-08-18 14:47:04 +02:00
Tom Christie
bed3c45161 Merge pull request #3288 from thedrow/feature/cached-field-root-and-context
Cached the field's root and context property
2015-08-18 10:50:32 +01:00
Omer Katz
792005806b Cached the field's root and context property. 2015-08-18 12:38:13 +03:00
Tom Christie
b722b3b77a Note on bus factor 2015-08-14 13:08:54 +01:00
Tom Christie
71505e675a Flesh out the funding docs 2015-08-14 12:34:47 +01:00
Ollie Walsh
332c30afb9 Lint 2015-08-14 12:20:25 +01:00
Ollie Walsh
3d0292e1cd Do not ignore overridden View.get_view_name() in breadcrumbs 2015-08-14 12:16:57 +01:00
Tom Christie
a0602104c3 Link to correct plans in sign up 2015-08-13 17:14:19 +01:00
Tom Christie
d80acd1f1f Initial draft of funding page 2015-08-13 14:17:27 +01:00
Tom Christie
1b53e804ee 3.2.2 Release 2015-08-13 10:23:22 +01:00
Tom Christie
0e6c467851 Merge pull request #3263 from jgadelange/master
Resolved issue with rendering of nested serializers form when value is None
2015-08-13 10:16:19 +01:00
Tom Christie
ff5fdeef73 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-08-13 09:56:10 +01:00
Tom Christie
18af181191 Fix boolean checkboxes setting to False. Closes #3258. Closes #2776. 2015-08-13 09:56:03 +01:00
Tom Christie
7bfc147cc2 Merge pull request #3268 from ThaJay/patch-1
Update 2-requests-and-responses.md
2015-08-13 00:06:58 +01:00
ThaJay
76fedcc348 Update 2-requests-and-responses.md
just a small error, the trailing slash in the url should be omitted when adding a .suffix
2015-08-12 19:49:43 +02:00
Jeffrey de Lange
f5a9904cc8 Resolved issue with rendering of nested serializers form when value is None 2015-08-11 20:27:41 +02:00
Tom Christie
a3e64fbe0d Resolve issue with rendering nested serializer forms with empty values. Closes #3260. 2015-08-11 16:25:02 +01:00
Tom Christie
0df99a6c95 Fix erronous request.files docs, and incorrect request.FILES behavior. Closes #3261. 2015-08-11 16:21:02 +01:00
Tom Christie
b7e47e3d67 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-08-11 09:24:16 +01:00
Tom Christie
83e49dbe63 Fix checkbox input display. Refs #3258. 2015-08-11 09:23:49 +01:00
Tom Christie
4509dbc24e Merge pull request #3241 from jpadilla/master
Raise error if passed a serializer instance
2015-08-10 17:41:01 +01:00
Tom Christie
e0c93c1780 Tweaking display_value docs 2015-08-10 16:37:55 +01:00
Tom Christie
2d5e8dea15 Merge pull request #3255 from jamesbeith/issues/#3254-display-value
Add a method to return the string value used in `choices` of a `RelatedField`
2015-08-10 16:32:29 +01:00
James Beith
5c0a2b79b3 Remove converting a string in to a string
The `display_value` method returns a text type.
2015-08-10 15:33:04 +01:00
James Beith
eaf61449a8 Explain use case for display_value in docs 2015-08-10 13:02:07 +01:00
James Beith
66ae19229e Add docs for display_value 2015-08-10 12:38:27 +01:00
James Beith
e9d9cb7011 Add tests for display_value 2015-08-10 12:19:46 +01:00
James Beith
2f6e5d0509 Add display value method
Returns the text representation of the instance. Subclasses can override this method to provide a different display value used for populating the `choices` property.
2015-08-10 11:03:57 +01:00
Ryan Kaneshiro
bc6bf7236b Add test to repro duplicate validation error
Using the ModelSerializer with a model containing a GenericIPAddressField
produces duplicated validation error messages.
2015-08-07 16:53:43 -07:00
José Padilla
7a0416c50b Raise error if passed a serializer instance 2015-08-07 13:12:37 -04:00
Tom Christie
0cbfbc27d8 Tweak erronous assignment 2015-08-07 15:41:46 +01:00
Tom Christie
3ea394dbff Version 3.2.1 2015-08-07 14:55:18 +01:00
Tom Christie
fbd05aba57 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-08-07 14:47:09 +01:00
Tom Christie
e88f28dbad Call out supported versions. Closes #3232. 2015-08-07 14:47:00 +01:00
Tom Christie
368fb9fb2a Merge pull request #3238 from kezabelle/bugfix/3235
Fixed #3235 - ListField now returns the QueryDict value even if it's a list of only one item.
2015-08-07 14:44:32 +01:00
Tom Christie
65e1c938eb Fix for 1, 0 being rendered as true, false in the admin. Closes #3227. 2015-08-07 14:38:36 +01:00
Tom Christie
e63dcab8b3 Fix for rendering select templates on relationships 2015-08-07 14:36:00 +01:00
Tom Christie
88609ba3a3 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-08-07 14:24:37 +01:00
Tom Christie
19c1976fcc Leave requests.FILES alone, for compat with regular Django requests. Closes #3239. 2015-08-07 14:24:28 +01:00
Keryn Knight
0078f66104 Fixed #3235 - A querydict which yields a list with only one value now correctly returns the provided data. 2015-08-07 11:43:17 +01:00
Keryn Knight
08d60f5cc2 Refs #3235 - Test demonstrating a single value passed to ListField is lost. 2015-08-07 11:41:56 +01:00
Tom Christie
981265fc48 Merge pull request #3231 from maryokhin/feature/drf3.2-readme
Update README with 3.2 release
2015-08-07 11:26:13 +01:00
Tymur Maryokhin
85e3edd7ff Update README and docs with 3.2 release 2015-08-07 12:12:01 +02:00
Tom Christie
77867e1eef Merge pull request #3230 from maryokhin/master
Fully drop Django 1.4 support
2015-08-07 09:57:28 +01:00
Tymur Maryokhin
4e5da16961 Remove Django 1.4 compat code 2015-08-07 00:02:29 +02:00
José Padilla
2fd5b8a2f9 Merge pull request #3229 from charettes/3.2-announcement-typo
Fixed a small typo in the 3.2 release announcement.
2015-08-06 17:55:34 -04:00
Simon Charette
bcc0d54f98 Fixed a small typo in the 3.2 release announcement. 2015-08-06 16:56:39 -04:00
Tom Christie
67ddd54a89 Merge pull request #3226 from tomchristie/version-3.2
Version 3.2
2015-08-06 14:30:46 +01:00
Tom Christie
e3aaa323b7 Add 3.2 announcement 2015-08-06 14:18:23 +01:00
Tom Christie
b4f1a8a367 Update translations 2015-08-06 13:22:53 +01:00
Tom Christie
78053c7e6c Upgrade version to 3.2.0 2015-08-06 13:18:51 +01:00
Tom Christie
a428d76ada Add 3.2 release notes 2015-08-06 13:18:18 +01:00
Tom Christie
37b4d42488 Merge pull request #3225 from tomchristie/maxpeterson-grouped-choices-fix
Support grouped choices.
2015-08-06 13:01:08 +01:00
Tom Christie
33d6d4a420 Test more types of behavior in test_iter_options 2015-08-06 12:30:26 +01:00
Tom Christie
24dec32e7a Added test_iter_options 2015-08-06 12:18:09 +01:00
Tom Christie
4d69286efa Use same structure for both .choices and .grouped_choices 2015-08-06 12:03:38 +01:00
Tom Christie
a6fefe78ff Added docstring 2015-08-06 11:44:39 +01:00
Tom Christie
27ac5a3680 Support grouped choices 2015-08-06 11:43:03 +01:00
Tom Christie
95a1550388 Merge branch 'grouped-choices-fix' of https://github.com/maxpeterson/django-rest-framework into maxpeterson-grouped-choices-fix 2015-08-06 10:04:52 +01:00
Tom Christie
9a778793f8 Adding imports to docs 2015-08-06 09:56:09 +01:00
Tom Christie
bbe5044c04 Merge pull request #3223 from wwj718/patch-1
import permission_classes
2015-08-06 09:54:25 +01:00
Tom Christie
38a1b3ec6b Rationalize decimal logic. Closes #3222. 2015-08-06 09:51:00 +01:00
wwj718
c099d9aac4 import permission_classes
many people don't know how to import permission_classes
2015-08-06 11:08:56 +08:00
Tom Christie
f7d44dfae0 Loud errors on request.DATA et al. 2015-08-05 17:07:47 +01:00
Tom Christie
6942fa5dab Mask view docstring on 401 and 403 responses. Closes #3216. 2015-08-05 13:59:55 +01:00
Tom Christie
6161ac7d07 Fix parse_html_dict signature. Closes #3212. 2015-08-05 13:45:56 +01:00
Tom Christie
7b51508600 Error on double underscore ordering with CursorPagination. Refs #3221. 2015-08-05 13:42:44 +01:00
Tom Christie
18c9391218 Use shields.io image 2015-08-04 09:47:36 +01:00
Tom Christie
cc5af22dc0 Use 'shilds.io' badge for codecov 2015-08-04 09:45:20 +01:00
Tom Christie
1df5844e67 Merge pull request #3208 from treyhunner/add-codecov
Report test coverage via Codecov
2015-08-03 17:13:46 +01:00
Trey Hunner
34c74b8925 Add coverage badge 2015-08-03 08:57:18 -07:00
Cesar Canassa
60c17253ab Add test to check if a 415 status is returned for unsupported media types 2015-08-03 17:54:18 +02:00
Trey Hunner
4cb14d8240 Don't measure branch coverage 2015-08-03 08:39:24 -07:00
Tom Christie
7f80a2e0ad Merge pull request #3211 from tomchristie/Ins1ne-feature/filepathfield
Add `FilePathField`
2015-08-03 10:26:37 +01:00
Tom Christie
bf35906dc0 FilePathField subclassing from ChoiceField 2015-08-03 10:17:41 +01:00
Tom Christie
877e964d7e Don't need to support Django 1.4 with FilePathField. 2015-08-03 10:15:28 +01:00
Tom Christie
8d7c0a8474 Merge branch 'feature/filepathfield' of https://github.com/Ins1ne/django-rest-framework into Ins1ne-feature/filepathfield 2015-08-03 10:09:46 +01:00
Tom Christie
650866cc43 Blank relational fields map to required=False serializer fields. Closes #3210. 2015-08-03 09:48:03 +01:00
Tom Christie
472784b70a Docs for custom hyperlinked fields. 2015-08-03 09:27:03 +01:00
Trey Hunner
48b21b6063 Always measure branch coverage 2015-07-31 18:28:49 -07:00
Trey Hunner
5b95536376 Run codecov after success on Travis CI 2015-07-31 18:21:52 -07:00
Tom Christie
9cd455a5a8 Merge pull request #3206 from Ian-Foote/patch-1
Fix custom HyperlinkedRelatedField example
2015-07-31 13:03:56 +01:00
Ian Foote
ed55fbe862 Fix custom HyperlinkedRelatedField example
Fix `get_object` method signature to match [`HyperlinkedRelatedField.get_object`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/relations.py#L227-L236).
2015-07-31 12:59:50 +01:00
Tom Christie
a543fae180 Merge pull request #2766 from delinhabit/allow-null-list-serializer
Modify subtle ChildSerializer(many=True, allow_null=True) behavior.
2015-07-31 10:11:21 +01:00
Tom Christie
9a661f52e5 Merge pull request #3202 from tomchristie/respect-blank-on-many-to-many
Respect blank on many to many fields.
2015-07-31 10:01:38 +01:00
Tom Christie
e68d737825 Respect blank on many to many, and set allow_empty=False if it is not present. Closes #2804. 2015-07-30 17:03:08 +01:00
Tom Christie
aa3f844b3d Merge pull request #3199 from tomchristie/remove-url-from-future
Remove 'load url from future' tags in templates.
2015-07-30 16:29:11 +01:00
Tom Christie
f087dcf7e2 Merge pull request #3200 from tomchristie/version-3.2
Version 3.2 deprecations.
2015-07-30 16:18:59 +01:00
Tom Christie
ad599100bf Merge pull request #3201 from Helioscene/master
Add package reference to docs: DRY Rest Permissions
2015-07-30 16:07:25 +01:00
Tom Christie
ed3f9593af Merge branch 'version-3.2' into remove-url-from-future 2015-07-30 16:02:40 +01:00
Tom Christie
1b3b01e042 Remove unused imports 2015-07-30 15:59:27 +01:00
David Kaplan
8d7627a079 Update third-party-resources.md
Add DRY Rest Framework reference onto the third party resources page.
2015-07-30 10:51:44 -04:00
David Kaplan
b969e9a872 Update permissions.md
Add DRY Rest Permissions info to the permissions page
2015-07-30 10:47:12 -04:00
Tom Christie
c8ad0cce19 Bump minimum Django version to 1.5 2015-07-30 15:43:39 +01:00
Tom Christie
4fd971e3e5 Update exception handler test in line with deprecations 2015-07-30 15:42:11 +01:00
Tom Christie
c203ca4c64 Deprecations 2015-07-30 15:26:42 +01:00
Tom Christie
5b39d820be Remove 'load url from future' tags in templates. 2015-07-30 15:14:02 +01:00
Tom Christie
1f55bc747b Merge pull request #2926 from tomchristie/admin-style
Admin style renderer
2015-07-30 15:01:37 +01:00
Tom Christie
1f50f08f28 Merge pull request #3190 from Hachikooking/master
Correct API ROOT to enable parametered urls
2015-07-30 14:54:17 +01:00
Tom Christie
79b825ef32 Drop unused import 2015-07-30 14:38:04 +01:00
Tom Christie
a4e0f03050 Tweak quickstart to show newest users first in list view 2015-07-30 14:18:09 +01:00
Tom Christie
5c1d6a9200 Docs for AdminRenderer 2015-07-30 14:07:51 +01:00
Tom Christie
accd8fe16b Merge pull request #3198 from jpadilla/search
Fix weird search behavior
2015-07-30 09:09:49 +01:00
Trey Hunner
cb257ec524 Measure code coverage in tox 2015-07-29 20:45:23 -07:00
José Padilla
ea1a8f4ac5 Fix weird search behavior. Closes #3197 2015-07-29 21:25:21 -04:00
José Padilla
0b345516a5 Turn off autocomplete on search form 2015-07-29 21:24:55 -04:00
Hachikooking
d2ae7d4fcd Add args to the function call for unnamed parameters 2015-07-29 14:43:25 +02:00
clemence.lop
2109f55244 Correct API ROOT to enable parametered urls 2015-07-28 15:55:49 +02:00
Tom Christie
6e3ba202af Merge pull request #2690 from delinhabit/hyperlinked-relation-callable-source
Support source='some_method' for HyperlinkedRelatedField.
2015-07-27 16:19:48 +01:00
Ion Scerbatiuc
d4353cc1fd Moved the code comment inside the if block and removed whitespace 2015-07-27 07:57:05 -07:00
Ion Scerbatiuc
0386a01673 Addressed CR comments 2015-07-27 07:45:35 -07:00
Tom Christie
c5a04a8516 Add test for nullable ChoiceField and blank HTML input. Closes #2623. 2015-07-27 13:51:03 +01:00
Tom Christie
75beb6ab2d Note on ValidationError in perform_create. Closes #2791. 2015-07-27 13:32:30 +01:00
Tom Christie
402fb39396 HStoreField maps to ListField(CharField(allow_blank=True). Closes #2659. 2015-07-27 13:18:49 +01:00
Tom Christie
f1e2135b04 Restyle horizontal checkbox. Closes #2783. 2015-07-27 13:11:24 +01:00
Tom Christie
798cd1a637 Fix for DjangoObjectPermissionsFilter with Guardian < 1.3 2015-07-27 10:20:37 +01:00
Tom Christie
99d9afc9d0 Remove out-of-date note on footer block in browsable API template. Closes #3187. 2015-07-27 09:18:41 +01:00
Tom Christie
caf337a4ae Merge pull request #3188 from jpadilla/master
Add missing link to third party resources
2015-07-27 09:17:02 +01:00
José Padilla
4f0220b780 Add missing link 2015-07-26 20:00:34 -04:00
Ion Scerbatiuc
47a22a55ca Added a possible fix 2015-07-25 09:44:00 -07:00
Ion Scerbatiuc
46b65d1647 Added another test case for PK relations 2015-07-25 09:42:27 -07:00
Ion Scerbatiuc
f53c6c7741 Added a test to reproduce the issue 2015-07-25 08:28:46 -07:00
Ion Scerbatiuc
bbd44ae94b Updated the test cases based on the CR comments 2015-07-25 08:22:14 -07:00
Ion Scerbatiuc
085c3e8a2b Fixed python 2.6 compatibility 2015-07-25 08:10:15 -07:00
Ion Scerbatiuc
bf25a6ecbc Test case for using allow_null with many=True and a fix for it 2015-07-25 08:10:15 -07:00
Tom Christie
bdeb28944f Use RuntimeError, not AssertionError when guarding against direct View.queryset evalutation. Refs #3180. 2015-07-24 09:13:39 +01:00
Tom Christie
36d8d3681a Merge pull request #3180 from tomchristie/guarded-queryset
Guard against erroneous direct .queryset evaluation in CBVs.
2015-07-24 09:11:56 +01:00
Tom Christie
108dfafa44 Fix Django 1.5/1.4 compat issue 2015-07-24 09:02:16 +01:00
Tom Christie
c0e3e670ca Fix Django compat for Queryset import 2015-07-23 17:43:49 +01:00
Tom Christie
e05021c8c6 Guard against erronous direct .queryset evaluation in CBVs. 2015-07-23 17:17:18 +01:00
Tom Christie
4c1597efe0 Error modals 2015-07-23 16:16:48 +01:00
Tom Christie
b996266431 Merge master 2015-07-23 15:28:29 +01:00
Tom Christie
9d136abb24 Merge pull request #3179 from tomchristie/browsable-api-errors
Errors in browsable API on error.
2015-07-23 15:25:43 +01:00
Tom Christie
d14bc3c4e1 Fix test cases for python3 2015-07-23 14:41:28 +01:00
Tom Christie
92008d3d16 None -> '' in the context of form field values 2015-07-23 14:36:23 +01:00
Tom Christie
90fe0fb881 Errors in browsable API on error. Closes #3024. 2015-07-23 14:31:25 +01:00
Tom Christie
6e6fa893e4 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-07-23 12:41:44 +01:00
Tom Christie
22631c73a7 Resolve assertion error with LimitOffsetPagination and erronous parameters. Closes #2920. 2015-07-23 12:41:35 +01:00
Tom Christie
e7d14532b0 Merge pull request #3178 from ilogik/master
fixed a typo in docs
2015-07-23 11:21:33 +01:00
Adrian Mester
d9c934debd fixed a typo in docs 2015-07-23 13:10:20 +03:00
Tom Christie
77e69451c1 Update CONTRIBUTING.md 2015-07-22 13:05:56 +01:00
Tom Christie
762a30dbda Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-07-22 12:36:43 +01:00
Tom Christie
f9c61e8090 Prominent notes on deprecation status of pagination settings. Closes #3173. 2015-07-22 12:36:32 +01:00
Tom Christie
cab981837f Merge pull request #3172 from jpadilla/master
Update quickstart.md
2015-07-20 07:17:59 +01:00
José Padilla
7f7e6b33ff Update quickstart.md
Closes #3171
2015-07-19 21:47:09 -04:00
Aider Ibragimov
205f388631 fix import sort order 2015-07-19 01:32:51 +03:00
Aider Ibragimov
c4f1c98572 fix lint issues 2015-07-19 01:22:57 +03:00
Aider Ibragimov
a1397ac699 fix bugs, move version branching to compat, update ModelSerializer mapping 2015-07-19 00:26:03 +03:00
Aider Ibragimov
d845157983 Merge branch 'master' of https://github.com/tomchristie/django-rest-framework into feature/filepathfield 2015-07-18 23:34:07 +03:00
Tom Christie
85cc8e9f1a Merge pull request #3168 from tomchristie/error-on-erronous-commit-argument
Helpful error on erronous 'serializer.save(commit=False)'
2015-07-17 12:50:06 +01:00
Tom Christie
138e9fcc8f Helpful error on erronous 'serializer.save(commit=False)' 2015-07-17 12:39:22 +01:00
Tom Christie
b22658536d Merge pull request #3165 from tomchristie/guardian-1-3-support
Upgrade guardian support to 1.3.
2015-07-16 16:55:30 +01:00
Tom Christie
788aae2aaf Upgrade guardian support to 1.3. Closes #3163. 2015-07-16 16:46:07 +01:00
Tom Christie
7b21336872 Rename model to play nice with Django 1.7. 2015-07-16 16:18:14 +01:00
Tom Christie
0b6eb4a881 Fix for Django 1.7 issue with long default verbose_name arguments on ChoiceField 2015-07-16 16:01:50 +01:00
Tom Christie
0ccb148183 Support QueryDict list arguments with ListField. Closes #3155. 2015-07-16 15:59:15 +01:00
Tom Christie
c940f15901 Internal use warning against HTMLFormRenderer. Closes #2773. 2015-07-16 15:50:51 +01:00
Tom Christie
8de13e7e9c Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-07-16 15:46:40 +01:00
Tom Christie
e14391e041 Fix for ModelSerializer ChoiceField with nonstandard args. Closes #3126. 2015-07-16 15:46:27 +01:00
Tom Christie
098ff83eb8 Merge pull request #3162 from lgiordani/fix_tutorial_serializer
Removed import of unused django.forms.widgets
2015-07-16 15:36:55 +01:00
Leonardo Giordani
4f6eba3ce8 Removed import of unused django.forms.widgets 2015-07-16 16:25:01 +02:00
Tom Christie
713333d354 Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-07-16 15:17:27 +01:00
Tom Christie
806b0b34da Include nested objects in metadata for OPTIONS. Closes #3156. Closes #2915. 2015-07-16 15:17:18 +01:00
Tom Christie
5c264c0e1f Merge pull request #3161 from tomchristie/allow-empty
Added allow_empty flag
2015-07-16 14:34:36 +01:00
Tom Christie
264d423493 Added allow_empty flag for ListField, ListSerializer, ManyRelation, MultipleChoiceField. 2015-07-16 13:51:15 +01:00
Tom Christie
81709a2c73 Merge pull request #3160 from vstoykov/test-for-3153
Test for #3153
2015-07-16 13:49:59 +01:00
Venelin Stoykov
73c0ebc2d5 Test for #3153 2015-07-16 15:40:41 +03:00
Tom Christie
db40b7eb91 Add coverage to runtests. Closes #2936. 2015-07-16 12:39:01 +01:00
Tom Christie
a8acdbc388 Resolve issue with nested serializers in HTML forms. Closes #3153. 2015-07-16 12:04:38 +01:00
Tom Christie
cde7154c59 Runtests should not suppress stdout. In the context of a web app only serves to hide erronous print statements. 2015-07-16 11:50:22 +01:00
Tom Christie
d231f36588 Support default values being used for empty HTML fields. Closes #3130. 2015-07-16 11:47:40 +01:00
Tom Christie
7315ed8b00 Resolve browsable API form issues with nested serializers. Closes #3153. 2015-07-16 10:49:00 +01:00
Tom Christie
c879aaf398 page_size needs to be stored as state on CursorPagination. Refs 3147. 2015-07-16 10:26:16 +01:00
Tom Christie
0ea64f6b33 More docs on configuring a custom metadata class. 2015-07-16 10:19:27 +01:00
Tom Christie
a9f1d99cb5 Fix 'metadata' action on viewsets. Closes #3158. Closes #3157. Closes #3115. 2015-07-16 10:08:22 +01:00
Tom Christie
6b08e97b6a Form fields should use textual only value representations. Closes #3139. Closes #2416. Closes #2558. 2015-07-14 15:47:13 +01:00
Tom Christie
8d306823b4 Update docs on ALLOWED_VERSIONS and DEFAULT_VERSION. Closes #2778. 2015-07-14 15:03:33 +01:00
Tom Christie
132eab7bbd Raise helpful error when erronously including nested data in multipart post requests with test client. Closes #2919. 2015-07-14 14:49:44 +01:00
Tom Christie
c14ad7add7 Handle .choices for related fields when queryset argument is actually a mamanger instance. Closes #3145. 2015-07-14 13:31:24 +01:00
Tom Christie
1b51bcdbae Merge branch 'master' of github.com:tomchristie/django-rest-framework 2015-07-14 13:21:20 +01:00
Tom Christie
bca2ea35df Ensure that realtionship fields '.choices' returns an empty dict when accessed with a read-only field. Closes #2910. 2015-07-14 13:21:08 +01:00
Tom Christie
9c952dcfe9 Merge pull request #3147 from tomchristie/uploadcare-cursor-limits
Add `get_page_size` hook to `CursorPagination`
2015-07-14 12:44:13 +01:00
Tom Christie
468361425d page_size should be local, not overwriting class attribute. 2015-07-14 12:32:27 +01:00
Tom Christie
3c57e08f62 Clarifications to read_only fields. Closes #3064. 2015-07-14 12:22:51 +01:00
Tom Christie
586c3350d4 Writable Nested Serializer example in relationships docs. Closes #2924. 2015-07-14 12:10:40 +01:00
Tom Christie
2b51d5594b Remove whitespace and comment changes 2015-07-14 11:41:25 +01:00
Tom Christie
14a32ae32d Add get_page_size hook to CursorPagination. Closes #3068. 2015-07-14 11:40:15 +01:00
Tom Christie
1d012aeb93 Merge branch 'cursor-limits' of https://github.com/uploadcare/django-rest-framework into uploadcare-cursor-limits 2015-07-14 11:37:18 +01:00
Tom Christie
209bcb9087 Added url_field_name class attribute to ModelSerializer. Closes #3106. 2015-07-14 11:21:33 +01:00
Tom Christie
538ffaf6c7 Store self.action='metadata' for OPTIONS requests on viewsets. Closes #3115. 2015-07-14 11:13:26 +01:00
Xavier Ordoquy
11e3cfbf6e Merge pull request #3142 from peleccom/patch-1
Fixed typo in docs
2015-07-13 16:07:06 +02:00
Alexander Pitkin
6d4ae2c40f Fixed type in docs
Fixed typo in Miscellaneous notes of 3.0 release announcement docs
2015-07-13 16:46:14 +03:00
homm
a3afcfb6d3 duplicate get_page_size and related properties from PageNumberPagination 2015-07-13 14:44:48 +03:00
homm
59905e9335 revert BasePageSizePagination class and CursorPagination inheritance 2015-07-13 14:36:47 +03:00
Carlton Gibson
6ff5385996 Merge pull request #3140 from dptechdev/patch-1
Update rest-hypermedia-hateoas.md
2015-07-11 23:54:17 +02:00
Derek Pauley
387dfd5dc3 Update rest-hypermedia-hateoas.md
There was a typo under ## What REST framework doesn't provide. 

Original: What REST framework doesn't do is give you is machine readable hypermedia formats such as [HAL][hal],

Fixed: What REST framework doesn't do is give you machine readable hypermedia formats such as [HAL][hal],
2015-07-11 13:23:57 -05:00
Xavier Ordoquy
061081c732 Merge pull request #3133 from YuriHeupa/patch-2
Changed typo in Renderer docs of BrowsableAPIRenderer
2015-07-10 08:15:35 +02:00
Yuri Hernani Heupa
c04c8808c6 Changed typo in Renderer docs
The BrowsableAPIRenderer was misspelled with an extra 'e' letter
2015-07-09 22:41:53 -03:00
Xavier Ordoquy
f33ca01511 Merge pull request #3112 from juannyG/master
Fix nested serializer required=False multipart data validation bug
2015-07-08 15:15:14 +02:00
Juan Gutierrez
2887fc4a0b update QueryDict initialization to satisfy older versions of Django 2015-07-08 08:25:12 -04:00
Juan Gutierrez
35db2b142f remove FakeMultiDict definition in nested serializer tests and replace with django QueryDict 2015-07-08 08:19:42 -04:00
José Padilla
8e6db16e91 Merge pull request #3118 from dealertrack/master
Added django-rest-framework-braces in Misc list of 3rd party tools
2015-07-06 18:07:59 -04:00
Miroslav Shubernetskiy
3bb9e251d7 added django-rest-framework-braces in Misc list of 3rd party tools 2015-07-06 17:35:21 -04:00
Xavier Ordoquy
b24741ae89 Merge pull request #3114 from jpadilla/master
Fix custom parser example
2015-07-06 10:22:09 +02:00
José Padilla
f161241e07 Fix custom parser example 2015-07-05 16:48:33 -04:00
Juan Gutierrez
b0c5f9db2f allow a non-required nested serializer to validate correctly when receiving multipart data 2015-07-03 12:28:48 -04:00
Max Peterson
ee2afb83e2 Fix 1.4 tests and make flatten_choice a utility. 2015-07-03 13:56:49 +01:00
Max Peterson
56b3f19605 Add support for grouped choices.
This also adds support for mixing single and paired choices:
```
[
    ('poor', 'Poor quality'),
    'medium',
    ('good', 'Good quality'),
]
```
2015-07-03 12:27:01 +01:00
José Padilla
c091addb83 Merge pull request #3105 from MattBroach/broach
added link to Django Rest Multiple Models to Third Party Packages on Generic Views API docs
2015-07-02 18:35:45 -04:00
Matt Broach
b9e09e2f90 Added django-rest-multiple-models link to general Third Party resources page as well 2015-07-02 18:18:30 -04:00
Matt Broach
9e58bf6500 added link to Django Rest Multiple Models to Third Party Packages 2015-07-02 17:20:41 -04:00
Tom Christie
c3507552d5 Merge pull request #3104 from Seraf/master
Adding recursion on child of List Field
2015-07-02 13:30:28 +01:00
Julien Syx
2b979d4356 Adding recursion on child of List Field 2015-07-02 14:15:43 +02:00
Tom Christie
8d69c4c068 Improve OPTIONS descriptions for lists dicts and nested serializers 2015-07-02 12:55:42 +01:00
Tom Christie
21ec3b506a Merge pull request #3103 from tomchristie/trollknurr-master
Ensure no duplication of results with SearchFilter with Oracle databases.
2015-07-02 12:23:31 +01:00
Tom Christie
e6ca0fcb4c Remove erronous newline 2015-07-02 11:53:05 +01:00
Tom Christie
37815920e3 Update to master and tweak remaining issues 2015-07-02 11:50:40 +01:00
Tom Christie
055986b5b0 More helpful exception when URL cannot reverse and field value was empty. Closes #2698. 2015-07-02 11:36:14 +01:00
Tom Christie
c4f908d4ee Introduce datetime_parser as class level attribute on all date/time fields. Refs #3093. 2015-07-02 11:23:52 +01:00
Tom Christie
6ce9e3baf0 Remove datetime_parser argument from DateTimeField 2015-07-02 11:22:18 +01:00
Tom Christie
6d79ea2cde Merge pull request #3093 from sorreltree/master
Ability to customize DateTimeField with a custom datetime_parser
2015-07-02 11:21:25 +01:00
Tom Christie
fb4233736f Empty settings should also be coerced to lists. Closes #3087. 2015-07-02 10:28:46 +01:00
Tom Christie
a03b89f326 Restrict isort to rest_framework and tests directories 2015-07-02 10:18:08 +01:00
Tom Christie
d979dc6522 Tweak exception message 2015-07-02 10:16:43 +01:00
Tom Christie
e3c3d8826f Merge pull request #3071 from antonyc/patch-1
Made exception message more verbose
2015-07-02 10:14:01 +01:00
Tom Christie
39ed03c21c Merge pull request #3088 from atleta/master
Handle AttributeError as well (when the imported module exists but the specified function/class does not).
2015-07-02 09:52:53 +01:00
Tom Christie
5fd346a8d3 Merge pull request #3102 from linovia/feature/update_django_filter
Upgrade django-filter to 0.10.0
2015-07-02 09:19:08 +01:00
Xavier Ordoquy
4b5f18d293 Upgrade django-filter to 0.10.0 2015-07-01 23:19:50 +02:00
Xavier Ordoquy
c5a1427c7a Merge pull request #3100 from bitterjug/fixdocs
Remove unused import from docs example
2015-07-01 21:50:28 +02:00
Mark Skipper
b743818430 Remove unused import from docs example 2015-07-01 20:39:05 +01:00
Tom Christie
a63fd55067 Merge pull request #3099 from tredzko/master
Update extra_kwargs on model serializer for required and read_only
2015-07-01 16:30:01 +01:00
Tyler Redzko
af08c70242 Update extra_kwargs on model serializer
Ensures that the 'read_only' and 'required' keys from `extra_kwargs` are
retained when present. Closes #3091.
2015-07-01 10:10:18 -04:00
José Padilla
5bb02cc7b9 Merge pull request #3094 from linovia/bug/2893
Update `get_serializer` signature (fix #2893)
2015-06-30 18:53:53 -04:00
Xavier Ordoquy
b6e46a6483 Update get_serializer signature
- remove the `files` and `allow_add_remove` arguments that were part of the 2.x API.
2015-07-01 00:26:54 +02:00
Michael Bacon
5f40ab53de Ability to customize DateTimeField with a custom datetime_parser 2015-06-30 14:51:47 -04:00
José Padilla
ca455fc80f Merge pull request #3090 from alasdairnicol/2900
Fixed #2900 -- Made example validator class in docs inherit from object
2015-06-30 13:03:14 -04:00
Alasdair Nicol
061cc5a42b Fixed #2900 -- Made example validator class in docs inherit from object 2015-06-30 16:33:01 +01:00
Laszlo Marai
f0bced6413 Handle AttributeError as well (when the imported module exists but
the specified function/class does not).
2015-06-30 05:49:44 +02:00
Tom Christie
5833a1847f Merge pull request #3086 from vstoykov/fix-manyrelated-choices
Fix ManyRelatedField.choices
2015-06-29 14:21:47 +01:00
Venelin Stoykov
c3c9a712fa Fix ManyRelatedField.choices
Use choices from self.child_relation. 
We don't need to repeat ourself because can get out of sync.
2015-06-29 15:35:55 +03:00
Tom Christie
36e4f20111 Update runtests.py 2015-06-29 09:39:27 +01:00
Tom Christie
af1a4bd683 Merge pull request #3085 from jpadilla/import-cleanup
Print helpful command if isort fails
2015-06-29 09:38:34 +01:00
José Padilla
0f1d9217f0 Print helpful command if isort fails 2015-06-27 16:06:53 -04:00
Tom Christie
3e1687282b Merge pull request #3048 from jpadilla/import-cleanup
Cleanup import following PEP 8 style guide
2015-06-26 14:55:28 +01:00
José Padilla
b4ba8ef4d7 Setup isort for code style linting 2015-06-26 09:16:33 -04:00
José Padilla
7351a3f6ca Sort imports with isort 2015-06-25 16:55:51 -04:00
José Padilla
83c9136c90 Cleanup import following PEP 8 style guide 2015-06-25 16:10:17 -04:00
Shtarev
e8b23c4789 thin logic 2015-06-25 21:14:00 +03:00
Tom Christie
47765bc429 Merge pull request #3034 from m-vellinga/master
Use get_queryset() for RelatedField choices property
2015-06-25 16:41:43 +01:00
Tom Christie
df7c114490 Merge pull request #3076 from jpadilla/issues/2704
Progressing #2704
2015-06-25 14:49:15 +01:00
José Padilla
d6e30c75ff Add test and fix for #2704 2015-06-25 09:35:36 -04:00
Tom Christie
cd0c9b7555 Merge pull request #3074 from tomchristie/unsaved_file_objects_serialize_to_none
Unsaved file objects may not have an associated URL.
2015-06-24 14:33:56 +01:00
Tom Christie
321133242f Unsaved file objects may not have an associated URL. 2015-06-24 14:24:19 +01:00
Tom Christie
9b8f966e06 Merge pull request #3073 from tomchristie/support_trim_whitespace_with_allow_blank_false
Support allow_blank=False with trim_whitespace=True.
2015-06-24 13:43:12 +01:00
Tom Christie
39ece9bee0 Support allow_blank=False with trim_whitespace=True. 2015-06-24 13:32:54 +01:00
Tom Christie
d5609979ca Merge pull request #3072 from tomchristie/fix-link-headers
Fix link headers in examples, as per RFC5988.
2015-06-24 13:16:19 +01:00
Tom Christie
632fc98f77 Fix link headers in examples, as per RFC5988. 2015-06-24 12:57:23 +01:00
Tom Christie
8329411cc3 Merge pull request #2539 from donewell/permission-detail
add message to custom permission
2015-06-24 11:32:02 +01:00
Tom Christie
8d4c96ecd6 Merge pull request #3012 from jannon/fix-allow-blank-mapping
only include 'allow_blank' on supported fields
2015-06-24 11:01:10 +01:00
Anton Chaporgin
47acec0f9d Made exception message more verbose
This exception helps you to upgrade from 2 -> 3 and since a lot of fields may be in 2 using serializers.Field as parent class, this message should contain at least name of upgraded field to help user to grep and fix the codebase faster.
2015-06-24 11:59:49 +03:00
Tom Christie
a17270589c Merge pull request #3067 from uploadcare/cursor-hooks
Cursor hooks
2015-06-23 21:59:50 +01:00
homm
30b36a594f use PageSizePaginationMixin for CursorPagination
tests for custom page_size in CursorPagination
2015-06-23 19:14:10 +03:00
homm
9bc0319ff4 Revert tests 2015-06-23 19:02:05 +03:00
homm
60656e9182 merge CursorPagination.decode_cursor and _decode_cursor
merge `CursorPagination.encode_cursor` and `_encode_cursor`
2015-06-23 19:00:42 +03:00
homm
9a5373d41c make PageSizePaginationMixin from all this page_size stuff 2015-06-23 18:19:38 +03:00
homm
b01e91eb71 test custom cursor format 2015-06-23 18:09:17 +03:00
homm
b3716ccb91 make MockObject, MockQuerySet and ExamplePagination visible outside of setup 2015-06-23 18:07:32 +03:00
homm
ab03729b58 allow cursor format customization 2015-06-23 18:00:26 +03:00
Tom Christie
e4b0273f76 Merge pull request #3063 from jpadilla/url-format-override
Document setting URL_FORMAT_OVERRIDE to None
2015-06-23 13:04:48 +01:00
José Padilla
83ef64dbf5 Document setting URL_FORMAT_OVERRIDE to None
This also hides the format dropdown from the
Browsable API if URL_FORMAT_OVERRIDE is disabled.

Closes #3057
2015-06-23 07:50:44 -04:00
Tom Christie
5e15edde96 Merge pull request #3062 from jpadilla/docs-version
Remove Twitter button for mobile rendering
2015-06-23 12:38:07 +01:00
José Padilla
9bdf9a510e Remove Twitter button for mobile rendering 2015-06-23 07:17:12 -04:00
Tom Christie
b1fc388f82 Merge pull request #3060 from jpadilla/docs-version
Add PyPI version badge to docs. Closes #3023
2015-06-23 12:04:55 +01:00
José Padilla
8554980c86 Add PyPI version badge to docs. Closes #3023 2015-06-23 06:22:35 -04:00
Tom Christie
1e678791de Merge pull request #2922 from thedrow/patch-11
Cache fields list for to_internal_value and to_representation
2015-06-23 08:53:32 +01:00
Tom Christie
bbca795cb7 Merge pull request #3056 from jpadilla/master
Track maximum supported 1.7 and 1.8 versions
2015-06-23 08:50:22 +01:00
José Padilla
b519407b57 Track maximum supported 1.7 and 1.8 versions 2015-06-22 16:04:52 -04:00
Tom Christie
e3b578258a Merge pull request #2769 from nonZero/patch-1
Wrong error message on bad field lookup
2015-06-22 17:04:04 +01:00
Tom Christie
15a386e85d Merge pull request #3045 from paxnovem/issue_3042
Fixed many=False issue on related fields
2015-06-22 15:40:59 +01:00
Tom Christie
894aa9b47e Merge pull request #3054 from thekorn/compat_requestfactory_secure
Compat requestfactory secure
2015-06-22 15:33:24 +01:00
Markus Korn
b42b16d0e6 compat: invert logic for checking the django version when implementing
RequestFactory.generic()
2015-06-22 16:13:42 +02:00
José Padilla
5d4bb0ef22 Merge pull request #3038 from jpadilla/dropdown
Set dynamic maximum height for dropdown widgets
2015-06-22 09:13:41 -04:00
Markus Korn
aa1ad4fb64 test_requests TestSecure: skip tests for django versions where the secure
argument is not available
2015-06-22 14:28:09 +02:00
Markus Korn
06c61fc511 compat: only add compat implementation of RequestFactory.generic() if not
provided by django
2015-06-22 14:05:56 +02:00
Markus Korn
d86e494e86 test_quests: added TestSecure for the emulation of secure connections in test cases 2015-06-22 14:04:46 +02:00
Omer Katz
1701ddae35 Fixed formatting of _readable_fields list comprehension to match the formatting of the _writable_fields list comprehension. 2015-06-20 08:51:03 +03:00
Brian Grohe
51cda112f5 Simplified if statement to one line solution
Based on feedback on the pull request, changed solution to
be simpler for issue 3042
2015-06-19 09:21:35 -04:00
Xavier Ordoquy
8c5fc2a94b Merge pull request #2732 from pquentin/patch-versioning
Document per-view versioning settings
2015-06-19 12:56:24 +02:00
Xavier Ordoquy
7cb618a09f Merge pull request #3047 from jpadilla/html-cleanup
Consistent 2 space tabbing and formatting
2015-06-18 19:29:38 +02:00
José Padilla
5e917789ec Consistent 2 space tabbing and formatting 2015-06-18 09:00:05 -04:00
Brian Grohe
d24990ece2 Fixed many=False issue in related fields
Added check to pop many from kwargs before passing to __init__
Fixed my lint issue from the previous commit
2015-06-17 13:48:34 -04:00
Brian Grohe
79736e516a Added failing test case
Adding failing test case when many=false is explicitly defined

https://github.com/tomchristie/django-rest-framework/issues/3042
2015-06-17 13:18:50 -04:00
Jannon Frank
2c415d7e03 models.TextFields get mapped to serializers.CharField too 2015-06-16 14:05:19 -07:00
Xavier Ordoquy
e368986fcf Merge pull request #3043 from accordeiro/accordeiro/docs-typo-fix
Fixed minor typo on viewsets.md
2015-06-16 22:49:41 +02:00
Xavier Ordoquy
139ba7adeb Merge pull request #3006 from osantana/master
Handle invalid characters in "Authorization: token ..." headers
2015-06-16 22:40:15 +02:00
Alexandre Cordeiro
deb2c9eb87 Fixed minor typo on viewsets.md
I'm not sure how the contribution policy for the docs is, but I thought it'd be faster to issue a pull request than reaching out to you guys/creating an issue for something so simple. Hope it's not a problem :)
2015-06-16 17:36:11 -03:00
Xavier Ordoquy
5524339e0e Merge pull request #3037 from jpadilla/master
Fix versioning urls
2015-06-16 21:34:31 +02:00
José Padilla
33a08928d7 Set dynamic maximum height for dropdown widgets 2015-06-15 21:46:08 -04:00
José Padilla
0be6d87fac Fix versioning urls 2015-06-15 16:51:37 -04:00
José Padilla
7f0acbd5a5 Merge pull request #3026 from linovia/feature/format_suffix_patterns_and_trailing_slash
`format_suffix_patterns` is applied before the trailing slash.
2015-06-15 16:38:12 -04:00
Xavier Ordoquy
be9327ad3a Merge pull request #3025 from linovia/documentation
Replace the former `get_filter_backends` by `filter_queryset`.
2015-06-15 22:28:41 +02:00
Xavier Ordoquy
49404f6977 Merge pull request #2789 from ovangle/primary_key_serialization
Primary key serialization
2015-06-15 22:23:01 +02:00
Thomas Stephenson
a1e0bae9da Custom serialization of PrimaryKeyRelatedField values
Adds a 'pk_field' parameter which can be used to proxy serialization and
deserialization of arbitrary primary key values.
2015-06-15 04:43:49 +10:00
Kevin Brown
b0889446a5 Merge pull request #3027 from linovia/feature/url_patterns_removal
Remove `django.conf.urls.pattern`
2015-06-11 16:40:40 -04:00
Xavier Ordoquy
bfd7219352 Define the urlpatterns as a list of `url().... 2015-06-11 01:01:47 +02:00
Xavier Ordoquy
9f1805f2f0 Removed unused imports. 2015-06-11 00:51:33 +02:00
Xavier Ordoquy
1e51230f1b Remove django.conf.urls.pattern as it'll be removed in Django 2.0 2015-06-11 00:45:23 +02:00
Xavier Ordoquy
fb2c09f6ae Remove unused patterns import. 2015-06-11 00:36:37 +02:00
Xavier Ordoquy
e7e5946c2e format_suffix_patterns is applied before the trailing slash. 2015-06-11 00:32:05 +02:00
Xavier Ordoquy
c80796ec04 Mention filter_queryset as an alternative to former get_filter_backends 2015-06-10 23:32:52 +02:00
Xavier Ordoquy
2749b12eaf Merge pull request #3017 from nmandery/feature/set-filter_backends-in-api-docs
Set the filter_backends class variable in the DjangoFilterBackend docs
2015-06-09 10:29:34 +02:00
Xavier Ordoquy
b06f944d2d Merge pull request #3016 from hellysmile/non_atomic_requests
Fix set_rollback on @transaction.non_atomic_requests.
2015-06-08 23:43:50 +02:00
Xavier Ordoquy
ca0a7ee1de Revert "Bump the django-guardian & django-filter to latests versions."
This reverts commit e095b91f60.
2015-06-08 21:48:05 +02:00
Xavier Ordoquy
e095b91f60 Bump the django-guardian & django-filter to latests versions. 2015-06-08 21:42:42 +02:00
hellysmile
cbfce93129 Fitx TestCase due Django interals. 2015-06-08 18:15:31 +03:00
Nico Mandery
325789db95 set the filter_backends class variable in the DjangoFilterBackend documentation for clearness 2015-06-08 15:18:30 +02:00
hellysmile
b015ae99e6 Inline @transaction.non_atomic_requests for Django<1.6. 2015-06-08 07:39:08 +03:00
hellysmile
c292b3d132 Fix set_rollback on @transaction.non_atomic_requests. 2015-06-08 07:10:57 +03:00
Tom Christie
6651432d59 Merge pull request #3015 from strixcuriosus/limit-offset-pagination-link-urls
Include correct limits in LimitOffsetPagination link urls
2015-06-05 20:37:04 +01:00
Ash Hoover
35c28a2a71 Include correct limits in LimitOffsetPagination link urls 2015-06-05 08:56:33 -07:00
malinich
4a2bad03c5 outdated method 'get_filter_backends' has been deleted from the documentation 2015-06-05 15:40:13 +03:00
Jannon Frank
b0752217ae only include 'allow_blank' on CharField 2015-06-05 02:21:13 -07:00
Tom Christie
bde05bfd3e Merge pull request #3010 from jaredpetersen/master
Remove reference to Bootstrap Customizer in browsable-api.md
2015-06-05 08:55:10 +01:00
Jared Petersen
2b2fbbd299 Update browsable-api.md
The Bootstrap Customizer has been discontinued and is no longer available (http://getbootstrap.com/2.3.2/customize.html), so I removed the reference to it in the page.
2015-06-04 21:28:21 -07:00
Xavier Ordoquy
8935db1be9 Merge pull request #3003 from linovia/release/3.1.3
Release 3.1.3
2015-06-04 15:04:55 +01:00
Xavier Ordoquy
9a20609223 Merge pull request #3004 from linovia/translations/3.1.3
Translations updated for 3.1.3
2015-06-04 14:59:32 +01:00
Xavier Ordoquy
886220cb70 Last minute pull request 2015-06-04 14:56:00 +01:00
Tom Christie
a3d6601e09 Merge pull request #3008 from linovia/feature/ipaddress-fix
`IPAddressField` improvements
2015-06-04 14:54:50 +01:00
Xavier Ordoquy
757e45acee Adding the last minute PR. 2015-06-04 14:37:01 +01:00
Tom Christie
e8cc948f6b Merge pull request #2695 from delinhabit/refactor-decimalfield
[enhancement] Refactored DecimalField to allow easier subclassing
2015-06-04 14:26:28 +01:00
Xavier Ordoquy
dee5fb5647 Merge remote-tracking branch 'reference/master' into feature/ipaddress-fix
Conflicts:
	docs/api-guide/fields.md
2015-06-04 14:21:33 +01:00
Osvaldo Santana Neto
7ae71deb84 Handle invalid characters in headers 2015-06-03 14:55:34 -03:00
Xavier Ordoquy
051b86e6fd Translations updated for 3.1.3 2015-06-03 17:34:13 +01:00
Xavier Ordoquy
bc778732bf Release notes for 3.1.3 2015-06-03 17:27:38 +01:00
Xavier Ordoquy
f3dbe9bb2a Bump to version 3.1.3 2015-06-03 16:57:18 +01:00
Xavier Ordoquy
0c66c7cfa6 Merge pull request #3000 from linovia/ovangle/uuid_format2
Add 'format' argument to UUIDField
2015-06-03 12:32:23 +01:00
Tom Christie
b1b47036d7 Use six.text_type for hyperlink names 2015-06-03 11:53:27 +01:00
Tom Christie
99e97fa9d3 Cleanup hyperlink rendering implementation 2015-06-03 11:47:33 +01:00
Tom Christie
ae704eec58 Fix issue with pagination control always displaying 2015-06-03 11:35:03 +01:00
Tom Christie
25bb3b1502 Use chevron control for row linking, rather than hyperlinking first item 2015-06-03 11:15:54 +01:00
Tom Christie
90f2e26679 Add Hyperlink and rendering in admin style renderer 2015-06-03 11:00:38 +01:00
Shtarev
745d8d0004 added comment 2015-06-03 09:04:28 +03:00
Tom Christie
bb97485627 Merge pull request #2998 from linovia/documentation/include_translations_in_process
Include translations in release process
2015-06-02 16:25:49 +01:00
Xavier Ordoquy
a97cbd1d68 Merge pull request #2999 from linovia/feature/short_pytest_tracebacks
Let py.test use the short traceback format.
2015-06-02 16:24:47 +01:00
Xavier Ordoquy
ea00fc7a85 Fix the UUID examples style. 2015-06-02 16:10:14 +01:00
Xavier Ordoquy
734bf3cfe6 Merge pull request #2981 from jannon/fix-model-serializer-metadata
Read-Only RelatedField Metadata Failure Test and Fix
2015-06-02 15:09:05 +01:00
Xavier Ordoquy
a61f865518 Add format examples. 2015-06-02 14:18:26 +01:00
Xavier Ordoquy
c82f6aa835 Merge remote-tracking branch 'origin/master' into documentation/include_translations_in_process 2015-06-02 13:49:24 +01:00
Xavier Ordoquy
0c97dd1806 Merge remote-tracking branch 'reference/master' 2015-06-02 13:04:57 +01:00
Xavier Ordoquy
e8e1908097 Remove the checked box and add a todo list during development cycle. 2015-06-02 13:01:17 +01:00
Xavier Ordoquy
87a523465b Let py.test use the short traceback format. 2015-06-02 10:49:47 +01:00
Xavier Ordoquy
1957679368 Merge pull request #2887 from ticosax/doom-transaction-on-error
Rollback the transaction on error if ATOMIC_REQUESTS is set.
2015-06-02 10:34:03 +01:00
Xavier Ordoquy
8fa3284620 Merge remote-tracking branch 'reference/master' 2015-06-02 10:24:28 +01:00
Xavier Ordoquy
6c1a285c83 Add the translations to the process. 2015-06-02 10:17:19 +01:00
Tom Christie
7f6fb3183f Merge pull request #2994 from linovia/documentation/add_warning_about_login
Add a warning about totally custom login views.
2015-06-02 09:51:08 +01:00
Jannon Frank
a97c989248 fix read_only related field metadata 2015-06-02 00:40:00 -07:00
Xavier Ordoquy
d4dd22ff1c Merge pull request #2997 from ticosax/fix-typo-duration-field
fix Typo
2015-06-02 08:27:11 +01:00
Nicolas Delaby
34dc98e8ad improve wording 2015-06-02 09:19:58 +02:00
Nicolas Delaby
8ad38208a1 more assertions make the test more readable 2015-06-02 09:19:58 +02:00
Nicolas Delaby
d1371cc949 Use post instead of get for sanity of use-case. 2015-06-02 09:19:58 +02:00
Nicolas Delaby
c2d2417237 Tell default error handler to doom the transaction on error
if `ATOMIC_REQUESTS` is enabled.
2015-06-02 09:19:58 +02:00
Nicolas Delaby
27fd48586e allow to pass arbitrary arguments to py.test 2015-06-02 09:19:18 +02:00
Nicolas Delaby
3f3a01b4b8 fix Typo 2015-06-02 09:18:24 +02:00
Xavier Ordoquy
d79956d40e Translation update. 2015-06-02 00:20:46 +01:00
Xavier Ordoquy
4ad8c17371 Add a warning about totally custom login views. 2015-06-01 18:13:40 +01:00
Xavier Ordoquy
f8eacc5bc0 Merge pull request #2993 from linovia/bug/2894
MultipleChoiceField empties incorrectly on a partial update using multipart/form-data (#2894)
2015-06-01 17:48:20 +01:00
Xavier Ordoquy
14055dd3f4 Merge pull request #2989 from ticosax/duration-field
Add DurationField
2015-06-01 17:38:57 +01:00
Nicolas Delaby
f701ecceb7 Add DurationField 2015-06-01 18:20:53 +02:00
Xavier Ordoquy
5c90bf9cc0 Fix for #2894 thanks to @carljm 2015-06-01 16:13:35 +01:00
Xavier Ordoquy
94e2d3ca61 Test case upgrade to use partial data 2015-06-01 16:13:12 +01:00
Xavier Ordoquy
989c08109b Failing test case for #2894 2015-06-01 16:04:05 +01:00
Tom Christie
0fdaa0dbba Merge pull request #2992 from linovia/feature/clean_mock_html_dir
Remove an extra MockHTMLDict definition.
2015-06-01 15:54:09 +01:00
Xavier Ordoquy
2f524ec1a3 Remove an extra MockHTMLDict definition. 2015-06-01 15:46:27 +01:00
Xavier Ordoquy
e3f856ff1d Merge pull request #2975 from sheppard/read-only-nested
can't create nested serializers for unique_together relations
2015-06-01 12:01:40 +01:00
Tom Christie
a0f66ffc69 Merge pull request #2849 from d0ugal/master
Migrate from Google search to MkDocs.
2015-06-01 09:31:44 +01:00
Dougal Matthews
daad630aa0 Update MkDocs version 2015-05-31 18:32:47 +01:00
Dougal Matthews
f5aa163aac Added a missing semicolon 2015-05-31 18:30:30 +01:00
Dougal Matthews
e6c7468055 Use the new pages structure.
This is optional, but will be required by MkDocs 1.0
2015-05-31 18:30:29 +01:00
Dougal Matthews
8ace80c287 Only load the search results when the search form is submitted for the
first time
2015-05-31 18:30:29 +01:00
Dougal Matthews
33666c459b Remove Google search and replace it with Mkdocs
This change updates the modal to use MkDocs for search.
2015-05-31 18:30:29 +01:00
Dougal Matthews
eae9390f1b Update <title> to match MkDocs changes
The {{ page_title }} and {{ site_name }} variables are now separated to
add flexibility th themes.
2015-05-31 18:30:29 +01:00
Dougal Matthews
d118cee7dd As of MkDocs 0.12 the Home link was added back to the navigation 2015-05-31 18:30:29 +01:00
Dougal Matthews
64523f1edc Update the Documentation 404.html template to subclass base.html
This allows us to delete lots of code and avoid hard-coding the
navigation. This does mean that {{ current_page }} isn't always
available and needs to be conditionally used.
2015-05-31 18:30:29 +01:00
Xavier Ordoquy
24855f70ac Merge pull request #2987 from cosmith/patch-1
Fix minor typo
2015-05-30 23:17:07 +01:00
Corentin Smith
fa29f7dd1f Fix minor typo 2015-05-30 17:57:35 +02:00
Tom Christie
512a6db21e Merge pull request #2984 from marctc/patch-2
Update validators.md
2015-05-29 16:41:58 +01:00
Marc
9d624d5b6b Update validators.md
Missing colon.
2015-05-29 16:57:13 +02:00
Xavier Ordoquy
ecb3ba5e1f Merge pull request #2948 from bimusiek/master
Added test ensuring DecimalField accepts `2E+2` as 200 and validates decimal place correctly.
2015-05-29 11:52:33 +02:00
Xavier Ordoquy
6634ce0da5 Merge pull request #2977 from arnaudlimbourg/patch-1
THe DRF Any Permission is not maintained anymore
2015-05-28 17:05:21 +02:00
Arnaud Limbourg
5550f1534c removing section since package is not maintained 2015-05-28 15:52:37 +02:00
S. Andrew Sheppard
4a3c844b7f flake8 2015-05-28 08:29:15 -05:00
S. Andrew Sheppard
0b8b288be5 python2 compat 2015-05-28 08:20:43 -05:00
Arnaud Limbourg
2bfef08d3a THe DRF Any Permission is not maintained anymore 2015-05-28 15:12:18 +02:00
S. Andrew Sheppard
8c7b5fc5c1 pop required extra_kwargs if read_only is set 2015-05-27 21:14:13 -05:00
S. Andrew Sheppard
805a915e7c can't nest unique_together relations 2015-05-27 21:06:57 -05:00
Tom Christie
ab7cb44bc5 Merge pull request #2974 from jpadilla/master
Use shields.io instead of pypip.in
2015-05-27 16:18:30 +01:00
José Padilla
7eeb0e81c0 Use shields.io instead of pypip.in 2015-05-27 10:47:44 -04:00
Tom Christie
95a27a108d Merge pull request #2933 from cancan101/overide_method_action
Set the action on a view when override_method regardless of its None-ness
2015-05-27 09:10:58 +01:00
José Padilla
ad3bb05a87 Merge pull request #2971 from aschn/master
Add drf-tracking to third-party-resources.md
2015-05-26 21:37:29 -04:00
Anna Schneider
9903392053 Merge pull request #1 from aschn/aschn-patch-2968
Add drf-tracking to third-party-resources.md
2015-05-26 17:01:24 -07:00
Anna Schneider
6553e253f3 Add drf-tracking to third-party-resources.md 2015-05-26 16:58:08 -07:00
Tom Christie
eeef85373c Merge pull request #2962 from aericson/fix-dependency-of-mkdoc
Update mkdocs version to 0.12.2
2015-05-26 09:18:27 +01:00
Carlton Gibson
578c8de4c2 Merge pull request #2965 from tinchodipalma/patch-1
Fix markdown link references in release notes
2015-05-25 10:14:55 +02:00
Martin Di Palma
7449e29cf7 Links issues
The following items had a wrong href value:

- Dont require pk strictly for related fields. (#2745, #2754)
- Restrict integer field to integers and strings. (#2835, #2836)
2015-05-25 02:24:11 -03:00
Xavier Ordoquy
c6d94fb6d2 Merge pull request #2963 from aericson/add-cdrf-to-docs
Add Classy Django REST Framework(cdrf.co) to Third Party Resources
2015-05-22 22:47:32 +02:00
André Ericson
e6e5a27836 Add Classy Django REST Framework(cdrf.co) to Third Party Resources 2015-05-22 17:18:59 -03:00
André Ericson
021644b913 Update mkdocs version to 0.12.2
The old version of mkdocs required 'Markdown>=2.3.1,<2.5' and
requirements-optionals.txt lists markdown==2.5.2 causing mkdocs
to fail.
2015-05-22 16:39:49 -03:00
Tom Christie
010f2ee9bd Merge pull request #2952 from Ernest0x/patch-3
Support basic authentication with custom user models that change username field
2015-05-20 09:56:38 +01:00
Petros Moisiadis
192719eed0 Improve coding style
On Tom's suggestion, improve coding style by using a single-line call to getattr() with a default value instead of a multi-line if/else clause.
2015-05-19 20:00:19 +03:00
Petros Moisiadis
a96ebd74b1 Fix flake8 error
Fix flake8 error
2015-05-19 19:48:53 +03:00
Petros Moisiadis
c63ea01f4f Support User model in Django 1.4 that has not a USERNAME_FIELD attribute
Support User model in Django 1.4 that has not a USERNAME_FIELD attribute.
2015-05-19 19:05:50 +03:00
Tom Christie
c916ad6315 Handle create and delete redirects 2015-05-19 16:30:45 +01:00
Petros Moisiadis
43b4ae752d Import get_user_model from compat module
Import get_user_model from compat module to be compatible with older django versions (e.g. 1.4).
2015-05-19 18:00:17 +03:00
Petros Moisiadis
a13075486d Compatibility code for getting user model
Compatibility code for getting user model
2015-05-19 17:57:27 +03:00
Tom Christie
ec8e7f27e7 Fixes for format preservation 2015-05-19 15:49:37 +01:00
Petros Moisiadis
bb002262ac Support basic authentication with custom user models that change username field
Support basic authentication with custom user models with a username field that is not named 'username'.
2015-05-19 17:42:44 +03:00
Tom Christie
f32fff43f0 Reduce font weight 2015-05-19 11:55:13 +01:00
Michał Hernas
e8c226c2db Fixed lint problems 2015-05-18 16:55:40 +02:00
Michał Hernas
069ea31cfb Added test ensuring DecimalField accepts 2E+2 as 200 and validates
decimal place correctly.
2015-05-18 16:42:24 +02:00
Omer Katz
67ff078388 Renamed the cached fields lists. 2015-05-17 09:54:33 +03:00
Tom Christie
e33fed70d6 Merge pull request #2940 from rapilabs/master
Allow unexpected values for ChoiceField/MultipleChoiceField representations
2015-05-15 16:54:55 +01:00
David Sanders
b7edd46313 Use simpler dict.get() rather than try/except 2015-05-16 01:01:27 +10:00
tony
0906bf2c08 fix empty and_query 2015-05-15 16:44:12 +03:00
tony
de95598a1e removed using view.model.objects 2015-05-15 13:46:56 +03:00
David Sanders
8e84a9f6d0 Allow invalid outputs to pass through to_representation() for ChoiceField & MultipleChoiceField 2015-05-15 18:59:10 +10:00
Tom Christie
b4d82a0f55 Preserve format query param 2015-05-15 09:18:45 +01:00
tony
c47ec60ea2 no need to do distinct on every loop cycle & add analogue of distinct for oracle users 2015-05-14 17:04:22 +03:00
tony
7813d2fb35 fix DISTINCT for Oracle databases 2015-05-14 13:57:36 +03:00
Xavier Ordoquy
6add1acc4e Add a few cosmetic changes to the release notes. 2015-05-14 11:18:18 +02:00
Xavier Ordoquy
475e431055 Fix the broken links. 2015-05-14 11:15:26 +02:00
Alex Rothberg
a804d0bd75 set the action when override_method regardless of its None-ness 2015-05-13 22:53:32 -04:00
Tom Christie
9424e59b9e Styling of nested lists/objects in detail view 2015-05-12 16:28:49 +01:00
Tom Christie
a1421cd4a3 Basic formatting for dict and list values 2015-05-12 16:18:45 +01:00
Tom Christie
9a504efd26 Basic formatting for admin cells 2015-05-12 15:21:49 +01:00
Tom Christie
995aa47570 First pass templates for admin style 2015-05-12 14:49:09 +01:00
Marco Vellinga
478b1dbd06 Use get_queryset() for RelatedField choices property instead of self.queryset.all() 2015-05-11 15:28:10 +02:00
Omer Katz
1ee3173583 Cache fields list for to_internal_value and to_representation. 2015-05-09 14:37:49 +03:00
Rense VanderHoek
5b7404cb9c Merge remote-tracking branch 'upstream/master'
* upstream/master: (54 commits)
  docs/renderers: `StaticHTMLRenderer` instead of `TemplateHTMLRenderer`
  Django 1.8 is no longer in beta
  Removed deprecated '.model' attribute check
  Update example of nested data
  Update serializers documentation (removed feature)
  more sp fixes
  Fix typo.
  Workaround for bug in pip
  Test against Django's master branch
  Django 1.8 released
  Should use "ordering" in model Meta, not order_by
  `query_params` in favor of `QUERY_PARAMS`
  Fixed docstring typo
  Reference typos in fields.md
  Use default reason phrases from HTTP standard.
  Metadata should detect null boolean field type.
  Fix older release notes link
  Try to resolve pep8 versioning clash.
  Swapping to hassattr logic for pk attribute references in relations
  Added enhancement for pk reference in many=True relations
  ...
2015-04-18 13:44:31 +02:00
Thomas Stephenson
236b731072 Add 'format' argument to UUIDField
To allow serializations to control the representation format of a
UUID value
2015-04-12 22:07:25 +10:00
Andrea Grandi
d6effbf779 Remove unpack_ipv4 parameter 2015-04-02 19:40:17 +01:00
Andrea Grandi
466575bee6 Lowercase the input 2015-03-26 18:14:53 +00:00
Udi Oron
b95ef25cbb Wrong error message on bad field lookup 2015-03-26 20:13:35 +02:00
Andrea Grandi
a0049dd489 Add a blank line to make lint happier 2015-03-22 23:21:09 +00:00
Andrea Grandi
1d883e0825 Add two more tests for IPAddressField, checking the IPv4 and IPv6 protocols separately 2015-03-22 16:46:16 +00:00
Quentin Pradet
8ba66e2c10 Document per-view versioning settings
That is, document the default_version, allowed_version and version_param
class variables.
2015-03-20 15:06:30 +01:00
Ion Scerbatiuc
022c4d540b Refactored DecimalField to allow easier subclassing 2015-03-14 07:16:17 -07:00
Rense VanderHoek
b172ed0d35 Update from upstream 2015-03-09 12:14:36 +01:00
Aider Ibragimov
c44376c613 remove unnecessary check 2015-03-04 14:17:58 +03:00
Aider Ibragimov
e5d95e319e fix FilePathField kwargs for django < 1.5 2015-03-03 16:58:04 +03:00
Aider Ibragimov
04cc1964bd remove dict compehension 2015-03-03 16:45:20 +03:00
Aider Ibragimov
5f8338e276 Merge branch 'master' of https://github.com/tomchristie/django-rest-framework into feature/filepathfield 2015-03-03 14:34:18 +03:00
Aider Ibragimov
c20a0250df add FilePathField, update docs 2015-03-03 14:34:06 +03:00
Rense VanderHoek
8348008781 Merge pull request #1 from tomchristie/master
Update from tom
2015-03-02 13:57:35 +01:00
Aider Ibragimov
de72022f80 Merge branch 'master' of https://github.com/Ins1ne/django-rest-framework into feature/ipaddress 2015-02-28 14:29:27 +03:00
Aider Ibragimov
313b3d7c3b Update ModelSerializer mappings 2015-02-28 10:18:47 +03:00
Aider Ibragimov
4d5eee04a0 add IPAddressField, update docs 2015-02-28 10:11:38 +03:00
donewell
3d25dadbf3 change custom message for clarity 2015-02-11 11:20:03 +00:00
donewell
9a9a00bff2 simplify argument handling 2015-02-11 11:15:01 +00:00
donewell
9ea615af14 add message to custom permission
change detail to message and update text
2015-02-10 20:11:53 +00:00
535 changed files with 70101 additions and 13868 deletions

2
.github/FUNDING.yml vendored Normal file
View File

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

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

6
.gitignore vendored
View File

@ -2,6 +2,8 @@
*.db
*~
.*
*.py.bak
/site/
/htmlcov/
@ -11,6 +13,8 @@
/*.egg-info/
/env/
MANIFEST
coverage.*
!.github
!.gitignore
!.travis.yml
!.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,45 +0,0 @@
language: python
sudo: false
env:
- TOX_ENV=py27-flake8
- TOX_ENV=py27-docs
- TOX_ENV=py34-django18
- TOX_ENV=py33-django18
- TOX_ENV=py32-django18
- TOX_ENV=py27-django18
- TOX_ENV=py34-django17
- TOX_ENV=py33-django17
- TOX_ENV=py32-django17
- TOX_ENV=py27-django17
- TOX_ENV=py34-django16
- TOX_ENV=py33-django16
- TOX_ENV=py32-django16
- TOX_ENV=py27-django16
- TOX_ENV=py26-django16
- TOX_ENV=py34-django15
- TOX_ENV=py33-django15
- TOX_ENV=py32-django15
- TOX_ENV=py27-django15
- TOX_ENV=py26-django15
- TOX_ENV=py27-django14
- TOX_ENV=py26-django14
- TOX_ENV=py27-djangomaster
- TOX_ENV=py32-djangomaster
- TOX_ENV=py33-djangomaster
- TOX_ENV=py34-djangomaster
matrix:
fast_finish: true
allow_failures:
- env: TOX_ENV=py27-djangomaster
- env: TOX_ENV=py32-djangomaster
- env: TOX_ENV=py33-djangomaster
- env: TOX_ENV=py34-djangomaster
install:
- pip install tox
script:
- tox -e $TOX_ENV

View File

@ -1,9 +1,9 @@
[main]
host = https://www.transifex.com
lang_map = sr@latin:sr_Latn, zh-Hans:zh_Hans, zh-Hant:zh_Hant
[django-rest-framework.djangopo]
file_filter = rest_framework/locale/<lang>/LC_MESSAGES/django.po
source_file = rest_framework/locale/en_US/LC_MESSAGES/django.po
source_lang = en_US
type = PO

View File

@ -1,211 +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.
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, 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.
# Development
To start developing on Django REST framework, clone the repo:
git clone git@github.com:tomchristie/django-rest-framework.git
Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.
## Testing
To run the tests, clone the repository, and then:
# Setup the virtual environment
virtualenv env
source env/bin/activate
pip install -r requirements.txt
# Run the tests
./runtests.py
### Test options
Run using a more concise output style.
./runtests.py -q
Run the tests using a more concise output style, no coverage, no flake8.
./runtests.py --fast
Don't run the flake8 code linting.
./runtests.py --nolint
Only run the flake8 code linting, don't run the tests.
./runtests.py --lintonly
Run the tests for a given test case.
./runtests.py MyTestCase
Run the tests for a given test method.
./runtests.py MyTestCase.test_this_method
Shorter form to run the tests for a given test method.
./runtests.py test_this_method
Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
### Running against multiple environments
You can also use the excellent [tox][tox] testing tool to run the tests against all supported versions of Python and Django. Install `tox` globally, and then simply run:
tox
## Pull requests
It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.
It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests.
It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests.
GitHub's documentation for working on pull requests is [available here][pull-requests].
Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django.
Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect.
![Travis status][travis-status]
*Above: Travis build notifications*
## 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]: http://www.w3.org/People/Berners-Lee/FAQ.html
[code-of-conduct]: https://www.djangoproject.com/conduct/
[google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[so-filter]: http://stackexchange.com/filters/66475/rest-framework
[issues]: https://github.com/tomchristie/django-rest-framework/issues?state=open
[pep-8]: http://www.python.org/dev/peps/pep-0008/
[travis-status]: ../img/travis-status.png
[pull-requests]: https://help.github.com/articles/using-pull-requests
[tox]: http://tox.readthedocs.org/en/latest/
[markdown]: http://daringfireball.net/projects/markdown/basics
[docs]: https://github.com/tomchristie/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,16 +1,21 @@
# License
Copyright (c) 2011-2015, Tom Christie
Copyright © 2011-present, [Encode OSS Ltd](https://www.encode.io/).
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED

View File

@ -1,6 +1,8 @@
include README.md
include LICENSE.md
recursive-include rest_framework/static *.js *.css *.png *.eot *.svg *.ttf *.woff
recursive-include rest_framework/templates *.html
recursive-exclude * __pycache__
recursive-exclude * *.py[co]
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__
global-exclude *.py[co]

5
PULL_REQUEST_TEMPLATE.md Normal file
View File

@ -0,0 +1,5 @@
*Note*: Before submitting a code change, please review our [contributing guidelines](https://www.django-rest-framework.org/community/contributing/#pull-requests).
## Description
Please describe your pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue. When linking to an issue, please use `refs #...` in the description of the pull request.

168
README.md
View File

@ -1,17 +1,36 @@
# [Django REST framework][docs]
[![build-status-image]][travis]
[![build-status-image]][build-status]
[![coverage-status-image]][codecov]
[![pypi-version]][pypi]
**Awesome web-browsable Web APIs.**
Full documentation for the project is available at [http://www.django-rest-framework.org][docs].
Full documentation for the project is available at [https://www.django-rest-framework.org/][docs].
---
**Note**: We have now released Django REST framework 3.1. For older codebases you may want to refer to the version 2.4.4 [source code](https://github.com/tomchristie/django-rest-framework/tree/version-2.4.x), and [documentation](http://tomchristie.github.io/rest-framework-2-docs/).
# Funding
For more details see the [3.1 release notes][3.1-announcement]
REST framework is a *collaboratively funded project*. If you use
REST framework commercially we strongly encourage you to invest in its
continued development by [signing up for a paid plan][funding].
The initial aim is to provide a single full-time position on REST framework.
*Every single sign-up makes a significant impact towards making that possible.*
[![][sentry-img]][sentry-url]
[![][stream-img]][stream-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], [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].
---
@ -21,22 +40,25 @@ 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]
----
# Requirements
* Python (2.6.5+, 2.7, 3.2, 3.3, 3.4)
* Django (1.4.11+, 1.5.6+, 1.6.3+, 1.7, 1.8)
* 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.
# Installation
@ -45,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
@ -59,21 +82,24 @@ Startup up a new project like so...
pip install django
pip install djangorestframework
django-admin.py startproject example .
./manage.py syncdb
django-admin startproject example .
./manage.py migrate
./manage.py createsuperuser
Now edit the `example/urls.py` module in your project:
```python
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets, routers
from django.urls import include, path
from rest_framework import routers, serializers, viewsets
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
fields = ['url', 'username', 'email', 'is_staff']
# ViewSets define the view behavior.
@ -86,12 +112,11 @@ class UserViewSet(viewsets.ModelViewSet):
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
```
@ -100,16 +125,16 @@ We'd also like to configure a couple of settings for our API.
Add the following to your `settings.py` module:
```python
INSTALLED_APPS = (
INSTALLED_APPS = [
... # Make sure to include the default installed apps here.
'rest_framework',
)
]
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
]
}
```
@ -120,17 +145,17 @@ That's it, we're done!
You can now open the API in your browser at `http://127.0.0.1:8000/`, and view your new 'users' API. If you use the `Login` control in the top right corner you'll also be able to add, create and delete users from the system.
You can also interact with the API using command line tools such as [`curl`](http://curl.haxx.se/). For example, to list the users endpoint:
You can also interact with the API using command line tools such as [`curl`](https://curl.haxx.se/). For example, to list the users endpoint:
$ curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
[
{
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin",
"email": "admin@example.com",
"is_staff": true,
}
]
[
{
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin",
"email": "admin@example.com",
"is_staff": true,
}
]
Or to create a new user:
@ -144,39 +169,58 @@ Or to create a new user:
# Documentation & Support
Full documentation for the project is available at [http://www.django-rest-framework.org][docs].
Full documentation for the project is available at [https://www.django-rest-framework.org/][docs].
For questions and support, use the [REST framework discussion group][group], or `#restframework` on freenode IRC.
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
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 see the [security policy][security-policy].
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
[build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.svg?branch=master
[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master
[pypi-version]: https://pypip.in/version/djangorestframework/badge.svg
[pypi]: https://pypi.python.org/pypi/djangorestframework
[twitter]: https://twitter.com/_tomchristie
[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/
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[sandbox]: http://restframework.herokuapp.com/
[oauth1-section]: http://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth
[oauth2-section]: http://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit
[serializer-section]: http://www.django-rest-framework.org/api-guide/serializers/#serializers
[modelserializer-section]: http://www.django-rest-framework.org/api-guide/serializers/#modelserializer
[functionview-section]: http://www.django-rest-framework.org/api-guide/views/#function-based-views
[generic-views]: http://www.django-rest-framework.org/api-guide/generic-views/
[viewsets]: http://www.django-rest-framework.org/api-guide/viewsets/
[routers]: http://www.django-rest-framework.org/api-guide/routers/
[serializers]: http://www.django-rest-framework.org/api-guide/serializers/
[authentication]: http://www.django-rest-framework.org/api-guide/authentication/
[image]: http://www.django-rest-framework.org/img/quickstart.png
[funding]: https://fund.django-rest-framework.org/topics/funding/
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[docs]: http://www.django-rest-framework.org/
[security-mail]: mailto:rest-framework-security@googlegroups.com
[3.1-announcement]: http://www.django-rest-framework.org/topics/3.1-announcement/
[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
[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/?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
[serializer-section]: https://www.django-rest-framework.org/api-guide/serializers/#serializers
[modelserializer-section]: https://www.django-rest-framework.org/api-guide/serializers/#modelserializer
[functionview-section]: https://www.django-rest-framework.org/api-guide/views/#function-based-views
[generic-views]: https://www.django-rest-framework.org/api-guide/generic-views/
[viewsets]: https://www.django-rest-framework.org/api-guide/viewsets/
[routers]: https://www.django-rest-framework.org/api-guide/routers/
[serializers]: https://www.django-rest-framework.org/api-guide/serializers/
[authentication]: https://www.django-rest-framework.org/api-guide/authentication/
[image]: https://www.django-rest-framework.org/img/quickstart.png
[docs]: https://www.django-rest-framework.org/
[security-policy]: https://github.com/encode/django-rest-framework/security/policy

7
SECURITY.md Normal file
View File

@ -0,0 +1,7 @@
# Security Policy
## Reporting a Vulnerability
**Please report security issues by emailing security@encode.io**.
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.

11
codecov.yml Normal file
View File

@ -0,0 +1,11 @@
coverage:
precision: 2
round: down
range: "80...100"
status:
project: yes
patch: no
changes: no
comment: off

View File

@ -1,4 +1,7 @@
source: authentication.py
---
source:
- authentication.py
---
# Authentication
@ -8,9 +11,9 @@ source: authentication.py
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted.
REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.
REST framework provides several authentication schemes out of the box, and also allows you to implement custom schemes.
Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.
Authentication always runs at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.
The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class.
@ -20,7 +23,7 @@ The `request.auth` property is used for any additional authentication informatio
**Note:** Don't forget that **authentication by itself won't allow or disallow an incoming request**, it simply identifies the credentials that the request was made with.
For information on how to setup the permission polices for your API please see the [permissions documentation][permission].
For information on how to set up the permission policies for your API please see the [permissions documentation][permission].
---
@ -37,14 +40,14 @@ The value of `request.user` and `request.auth` for unauthenticated requests can
The default authentication schemes may be set globally, using the `DEFAULT_AUTHENTICATION_CLASSES` setting. For example.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
]
}
You can also set the authentication scheme on a per-view or per-viewset basis,
using the `APIView` class based views.
using the `APIView` class-based views.
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
@ -52,25 +55,25 @@ using the `APIView` class based views.
from rest_framework.views import APIView
class ExampleView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None
'user': str(request.user), # `django.contrib.auth.User` instance.
'auth': str(request.auth), # None
}
return Response(content)
Or, if you're using the `@api_view` decorator with function based views.
@api_view(['GET'])
@authentication_classes((SessionAuthentication, BasicAuthentication))
@permission_classes((IsAuthenticated,))
@authentication_classes([SessionAuthentication, BasicAuthentication])
@permission_classes([IsAuthenticated])
def example_view(request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None
'user': str(request.user), # `django.contrib.auth.User` instance.
'auth': str(request.auth), # None
}
return Response(content)
@ -87,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.
@ -117,37 +126,44 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
## TokenAuthentication
---
**Note:** The token authentication provided by Django REST framework is a fairly simple implementation.
For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the [Django REST Knox][django-rest-knox] third party package.
---
This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
To use the `TokenAuthentication` scheme you'll need to [configure the authentication classes](#setting-the-authentication-scheme) to include `TokenAuthentication`, and additionally include `rest_framework.authtoken` in your `INSTALLED_APPS` setting:
INSTALLED_APPS = (
INSTALLED_APPS = [
...
'rest_framework.authtoken'
)
]
---
**Note:** Make sure to run `manage.py syncdb` after changing your settings. The `rest_framework.authtoken` app provides both Django (from v1.7) and South database migrations. See [Schema migrations](#schema-migrations) below.
---
Make sure to run `manage.py migrate` after changing your settings.
The `rest_framework.authtoken` app provides Django database migrations.
You'll also need to create tokens for your users.
from rest_framework.authtoken.models import Token
token = Token.objects.create(user=...)
print token.key
print(token.key)
For clients to authenticate, the token key should be included in the `Authorization` HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example:
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
*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.
* `request.user` will be a Django `User` instance.
* `request.auth` will be a `rest_framework.authtoken.models.BasicToken` instance.
* `request.auth` will be a `rest_framework.authtoken.models.Token` instance.
Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
@ -163,7 +179,9 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
---
#### Generating Tokens
### Generating Tokens
#### By using signals
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
@ -187,11 +205,13 @@ If you've already created some users, you can generate tokens for all existing u
for user in User.objects.all():
Token.objects.get_or_create(user=user)
#### By exposing an api endpoint
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
from rest_framework.authtoken import views
urlpatterns += [
url(r'^api-token-auth/', views.obtain_auth_token)
path('api-token-auth/', views.obtain_auth_token)
]
Note that the URL part of the pattern can be whatever you want to use.
@ -200,39 +220,65 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the `obtain_auth_token` view, you can do so by overriding the `ObtainAuthToken` view class, and using that in your url conf instead.
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.
#### Schema migrations
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.
The `rest_framework.authtoken` app includes both Django native migrations (for Django versions >1.7) and South migrations (for Django versions <1.7) that will create the authtoken table.
If you need a customized version of the `obtain_auth_token` view, you can do so by subclassing the `ObtainAuthToken` view class, and using that in your url conf instead.
----
For example, you may return additional user information beyond the `token` value:
**Note**: From REST Framework v2.4.0 using South with Django <1.7 requires upgrading South v1.0+
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
----
class CustomAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'user_id': user.pk,
'email': user.email
})
And in your `urls.py`:
urlpatterns += [
path('api-token-auth/', CustomAuthToken.as_view())
]
If you're using a [custom user model][custom-user-model] you'll need to make sure that any initial migration that creates the user table runs before the authtoken table is created.
#### With Django admin
You can do so by inserting a `needed_by` attribute in your user migration:
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`.
class Migration:
`your_app/admin.py`:
needed_by = (
('authtoken', '0001_initial'),
)
from rest_framework.authtoken.admin import TokenAdmin
def forwards(self):
...
TokenAdmin.raw_id_fields = ['user']
For more details, see the [south documentation on dependencies][south-dependencies].
Also note that if you're using a `post_save` signal to create tokens, then the first time you create the database tables, you'll need to ensure any migrations are run prior to creating any superusers. For example:
#### Using Django manage.py command
Since version 3.6.4 it's possible to generate a user token using the following command:
./manage.py drf_create_token <username>
this command will return the API token for the given user, creating it if it doesn't exist:
Generated token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b for user user1
In case you want to regenerate the token (for example if it has been compromised or leaked) you can pass an additional parameter:
./manage.py drf_create_token -r <username>
python manage.py syncdb --noinput # Won't create a superuser just yet, due to `--noinput`.
python manage.py migrate
python manage.py createsuperuser
## SessionAuthentication
@ -245,7 +291,33 @@ 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 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
This authentication scheme allows you to delegate authentication to your web server, which sets the `REMOTE_USER`
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 behavior, consult the
[Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/).
If successfully authenticated, `RemoteUserAuthentication` provides the following credentials:
* `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, 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/)
# Custom authentication
@ -256,23 +328,29 @@ 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.
If the `.authenticate_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access.
---
**Note:** When your custom authenticator is invoked by the request object's `.user` or `.auth` properties, you may see an `AttributeError` re-raised as a `WrappedAttributeError`. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from your custom authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. These errors should be fixed or otherwise handled by your authenticator.
---
## Example
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'.
from django.contrib.auth.models import User
from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import exceptions
class ExampleAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
username = request.META.get('X_USERNAME')
username = request.META.get('HTTP_X_USERNAME')
if not username:
return None
@ -287,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 2.7 and Python 3.3+. The package is maintained by [Evonove][evonove] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by [jazzband][jazzband] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
#### Installation & configuration
### Installation & configuration
Install using `pip`.
@ -301,15 +383,15 @@ Install using `pip`.
Add the package to your `INSTALLED_APPS` and modify your REST framework settings.
INSTALLED_APPS = (
INSTALLED_APPS = [
...
'oauth2_provider',
)
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
)
'DEFAULT_AUTHENTICATION_CLASSES': [
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
]
}
For more details see the [Django REST framework - Getting started][django-oauth-toolkit-getting-started] documentation.
@ -318,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`.
@ -328,17 +410,9 @@ Install the package using `pip`.
For details on configuration and usage see the Django REST framework OAuth documentation for [authentication][django-rest-framework-oauth-authentication] and [permissions][django-rest-framework-oauth-permissions].
## Digest Authentication
HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. [Juan Riaza][juanriaza] maintains the [djangorestframework-digestauth][djangorestframework-digestauth] package which provides HTTP digest authentication support for REST framework.
## Django OAuth2 Consumer
The [Django OAuth2 Consumer][doac] library from [Rediker Software][rediker] is another package that provides [OAuth 2.0 support for REST framework][doac-rest-framework]. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.
## JSON Web Token Authentication
JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. [Blimp][blimp] maintains the [djangorestframework-jwt][djangorestframework-jwt] package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password.
JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. A package for JWT authentication is [djangorestframework-simplejwt][djangorestframework-simplejwt] which provides some features as well as a pluggable token blacklist app.
## Hawk HTTP Authentication
@ -346,53 +420,81 @@ The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let y
## HTTP Signature Authentication
HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] package which provides an easy to use HTTP Signature Authentication mechanism.
HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] (outdated) package which provides an easy-to-use HTTP Signature Authentication mechanism. You can use the updated fork version of [djangorestframework-httpsignature][djangorestframework-httpsignature], which is [drf-httpsig][drf-httpsig].
## Djoser
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.
## django-rest-auth
## django-rest-auth / dj-rest-auth
[Django-rest-auth][django-rest-auth] library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.
This library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.
[cite]: http://jacobian.org/writing/rest-worst-practices/
[http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
[http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4
[basicauth]: http://tools.ietf.org/html/rfc2617
[oauth]: http://oauth.net/2/
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.
## drf-social-oauth2
[Drf-social-oauth2][drf-social-oauth2] is a framework that helps you authenticate with major social oauth2 vendors, such as Facebook, Google, Twitter, Orcid, etc. It generates tokens in a JWTed way with an easy setup.
## drfpasswordless
[drfpasswordless][drfpasswordless] adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.
## django-rest-authemail
[django-rest-authemail][django-rest-authemail] provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully functional example project and detailed instructions are included.
## Django-Rest-Durin
[Django-Rest-Durin][django-rest-durin] is built with the idea to have one library that does token auth for multiple Web/CLI/Mobile API clients via one interface but allows different token configuration for each API Client that consumes the API. It provides support for multiple tokens per user via custom models, views, permissions that work with Django-Rest-Framework. The token expiration time can be different per API client and is customizable via the Django Admin Interface.
More information can be found in the [Documentation](https://django-rest-durin.readthedocs.io/en/latest/index.html).
## 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/dev/ref/csrf/#ajax
[mod_wsgi_official]: http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization
[custom-user-model]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model
[south-dependencies]: http://south.readthedocs.org/en/latest/dependencies.html
[django-oauth-toolkit-getting-started]: https://django-oauth-toolkit.readthedocs.org/en/latest/rest-framework/getting_started.html
[django-rest-framework-oauth]: http://jpadilla.github.io/django-rest-framework-oauth/
[django-rest-framework-oauth-authentication]: http://jpadilla.github.io/django-rest-framework-oauth/authentication/
[django-rest-framework-oauth-permissions]: http://jpadilla.github.io/django-rest-framework-oauth/permissions/
[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/
[django-rest-framework-oauth-authentication]: https://jpadilla.github.io/django-rest-framework-oauth/authentication/
[django-rest-framework-oauth-permissions]: https://jpadilla.github.io/django-rest-framework-oauth/permissions/
[juanriaza]: https://github.com/juanriaza
[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
[oauth-1.0a]: http://oauth.net/core/1.0a
[django-oauth-plus]: http://code.larlet.fr/django-oauth-plus
[django-oauth2-provider]: https://github.com/caffeinehit/django-oauth2-provider
[django-oauth2-provider-docs]: https://django-oauth2-provider.readthedocs.org/en/latest/
[rfc6749]: http://tools.ietf.org/html/rfc6749
[oauth-1.0a]: https://oauth.net/core/1.0a/
[django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
[evonove]: https://github.com/evonove/
[jazzband]: https://github.com/jazzband/
[oauthlib]: https://github.com/idan/oauthlib
[doac]: https://github.com/Rediker-Software/doac
[rediker]: https://github.com/Rediker-Software
[doac-rest-framework]: https://github.com/Rediker-Software/doac/blob/master/docs/integrations.md#
[blimp]: https://github.com/GetBlimp
[djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt
[djangorestframework-simplejwt]: https://github.com/davesque/django-rest-framework-simplejwt
[etoccalino]: https://github.com/etoccalino/
[djangorestframework-httpsignature]: https://github.com/etoccalino/django-rest-framework-httpsignature
[amazon-http-signature]: http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
[drf-httpsig]: https://github.com/ahknight/drf-httpsig
[amazon-http-signature]: https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
[http-signature-ietf-draft]: https://datatracker.ietf.org/doc/draft-cavage-http-signatures/
[hawkrest]: http://hawkrest.readthedocs.org/en/latest/
[hawkrest]: https://hawkrest.readthedocs.io/en/latest/
[hawk]: https://github.com/hueniverse/hawk
[mohawk]: http://mohawk.readthedocs.org/en/latest/
[mac]: http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05
[mohawk]: https://mohawk.readthedocs.io/en/latest/
[mac]: https://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05
[djoser]: https://github.com/sunscrapers/djoser
[django-rest-auth]: https://github.com/Tivix/django-rest-auth
[dj-rest-auth]: https://github.com/jazzband/dj-rest-auth
[drf-social-oauth2]: https://github.com/wagnerdelima/drf-social-oauth2
[django-rest-knox]: https://github.com/James1345/django-rest-knox
[drfpasswordless]: https://github.com/aaronn/django-rest-framework-passwordless
[django-rest-authemail]: https://github.com/celiao/django-rest-authemail
[django-rest-durin]: https://github.com/eshaan7/django-rest-durin
[login-required-middleware]: https://docs.djangoproject.com/en/stable/ref/middleware/#django.contrib.auth.middleware.LoginRequiredMiddleware
[django-pyoidc] : https://github.com/makinacorpus/django_pyoidc

91
docs/api-guide/caching.md Normal file
View File

@ -0,0 +1,91 @@
# Caching
> A certain woman had a very sharp consciousness but almost no
> memory ... She remembered enough to work, and she worked hard.
> - Lydia Davis
Caching in REST Framework works well with the cache utilities
provided in Django.
---
## Using cache with apiview and viewsets
Django provides a [`method_decorator`][decorator] to use
decorators with class based views. This can be used with
other cache decorators such as [`cache_page`][page],
[`vary_on_cookie`][cookie] and [`vary_on_headers`][headers].
```python
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie, vary_on_headers
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import viewsets
class UserViewSet(viewsets.ViewSet):
# With cookie: cache requested url for each user for 2 hours
@method_decorator(cache_page(60 * 60 * 2))
@method_decorator(vary_on_cookie)
def list(self, request, format=None):
content = {
"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"))
def get(self, request, format=None):
content = {
"user_feed": request.user.get_user_feed(),
}
return Response(content)
class PostView(APIView):
# Cache page for the requested url
@method_decorator(cache_page(60 * 60 * 2))
def get(self, request, format=None):
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.
[page]: https://docs.djangoproject.com/en/dev/topics/cache/#the-per-view-cache
[cookie]: https://docs.djangoproject.com/en/dev/topics/http/decorators/#django.views.decorators.vary.vary_on_cookie
[headers]: https://docs.djangoproject.com/en/dev/topics/http/decorators/#django.views.decorators.vary.vary_on_headers
[decorator]: https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-the-class

View File

@ -1,4 +1,7 @@
source: negotiation.py
---
source:
- negotiation.py
---
# Content negotiation
@ -6,7 +9,7 @@ source: negotiation.py
>
> &mdash; [RFC 2616][cite], Fielding et al.
[cite]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html
[cite]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html
Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences.
@ -77,9 +80,9 @@ The default content negotiation class may be set globally, using the `DEFAULT_CO
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation',
}
You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class based views.
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
@ -94,4 +97,4 @@ You can also set the content negotiation used for an individual view, or viewset
'accepted media type': request.accepted_renderer.media_type
})
[accept-header]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
[accept-header]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

View File

@ -1,4 +1,7 @@
source: exceptions.py
---
source:
- exceptions.py
---
# Exceptions
@ -35,7 +38,7 @@ Might receive an error response indicating that the `DELETE` method is not allow
Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the `NON_FIELD_ERRORS_KEY` setting.
Any example validation error might look like this:
An example validation error might look like this:
HTTP/1.1 400 Bad Request
Content-Type: application/json
@ -47,7 +50,7 @@ Any example validation error might look like this:
You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.
The function must take a pair of arguments, this first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a `Response` object, or return `None` if the exception cannot be handled. If the handler returns `None` then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.
The function must take a pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a `Response` object, or return `None` if the exception cannot be handled. If the handler returns `None` then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.
For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:
@ -98,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` and `.default_detail` properties 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:
@ -107,10 +110,42 @@ For example, if your API relies on a third party service that may sometimes be u
class ServiceUnavailable(APIException):
status_code = 503
default_detail = 'Service temporarily unavailable, try again later.'
default_code = 'service_unavailable'
#### Inspecting API exceptions
There are a number of different properties available for inspecting the status
of an API exception. You can use these to build custom exception handling
for your project.
The available attributes and methods are:
* `.detail` - Return the textual description of the error.
* `.get_codes()` - Return the code identifier of the error.
* `.get_full_details()` - Return both the textual description and the code identifier.
In most cases the error detail will be a simple item:
>>> print(exc.detail)
You do not have permission to perform this action.
>>> print(exc.get_codes())
permission_denied
>>> print(exc.get_full_details())
{'message':'You do not have permission to perform this action.','code':'permission_denied'}
In the case of validation errors the error detail will be either a list or
dictionary of items:
>>> print(exc.detail)
{"name":"This field is required.","age":"A valid integer is required."}
>>> print(exc.get_codes())
{"name":"required","age":"invalid"}
>>> print(exc.get_full_details())
{"name":{"message":"This field is required.","code":"required"},"age":{"message":"A valid integer is required.","code":"invalid"}}
## ParseError
**Signature:** `ParseError(detail=None)`
**Signature:** `ParseError(detail=None, code=None)`
Raised if the request contains malformed data when accessing `request.data`.
@ -118,7 +153,7 @@ By default this exception results in a response with the HTTP status code "400 B
## AuthenticationFailed
**Signature:** `AuthenticationFailed(detail=None)`
**Signature:** `AuthenticationFailed(detail=None, code=None)`
Raised when an incoming request includes incorrect authentication.
@ -126,7 +161,7 @@ By default this exception results in a response with the HTTP status code "401 U
## NotAuthenticated
**Signature:** `NotAuthenticated(detail=None)`
**Signature:** `NotAuthenticated(detail=None, code=None)`
Raised when an unauthenticated request fails the permission checks.
@ -134,7 +169,7 @@ By default this exception results in a response with the HTTP status code "401 U
## PermissionDenied
**Signature:** `PermissionDenied(detail=None)`
**Signature:** `PermissionDenied(detail=None, code=None)`
Raised when an authenticated request fails the permission checks.
@ -142,15 +177,15 @@ By default this exception results in a response with the HTTP status code "403 F
## NotFound
**Signature:** `NotFound(detail=None)`
**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".
## MethodNotAllowed
**Signature:** `MethodNotAllowed(method, detail=None)`
**Signature:** `MethodNotAllowed(method, detail=None, code=None)`
Raised when an incoming request occurs that does not map to a handler method on the view.
@ -158,7 +193,7 @@ By default this exception results in a response with the HTTP status code "405 M
## NotAcceptable
**Signature:** `NotAcceptable(detail=None)`
**Signature:** `NotAcceptable(detail=None, code=None)`
Raised when an incoming request occurs with an `Accept` header that cannot be satisfied by any of the available renderers.
@ -166,7 +201,7 @@ By default this exception results in a response with the HTTP status code "406 N
## UnsupportedMediaType
**Signature:** `UnsupportedMediaType(media_type, detail=None)`
**Signature:** `UnsupportedMediaType(media_type, detail=None, code=None)`
Raised if there are no parsers that can handle the content type of the request data when accessing `request.data`.
@ -174,7 +209,7 @@ By default this exception results in a response with the HTTP status code "415 U
## Throttled
**Signature:** `Throttled(wait=None, detail=None)`
**Signature:** `Throttled(wait=None, detail=None, code=None)`
Raised when an incoming request fails the throttling checks.
@ -182,12 +217,11 @@ By default this exception results in a response with the HTTP status code "429 T
## ValidationError
**Signature:** `ValidationError(detail)`
**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.
* The `detail` argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the `validate()` method of a serializer. For example. `raise serializers.ValidationError({'name': 'Please enter a valid name.'})`
* By convention you should import the serializers module and use a fully qualified `ValidationError` style, in order to differentiate it from Django's built-in validation error. For example. `raise serializers.ValidationError('This field must be an integer value.')`
The `ValidationError` class should be used for serializer and field validation, and by validator classes. It is also raised when calling `serializer.is_valid` with the `raise_exception` keyword argument:
@ -198,5 +232,42 @@ The generic views use the `raise_exception=True` flag, which means that you can
By default this exception results in a response with the HTTP status code "400 Bad Request".
[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html
---
# Generic Error Views
Django REST Framework provides two error views suitable for providing generic JSON `500` Server Error and
`400` Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an
API-only application.)
Use these as per [Django's Customizing error views documentation][django-custom-error-views].
## `rest_framework.exceptions.server_error`
Returns a response with status code `500` and `application/json` content type.
Set as `handler500`:
handler500 = 'rest_framework.exceptions.server_error'
## `rest_framework.exceptions.bad_request`
Returns a response with status code `400` and `application/json` content type.
Set as `handler400`:
handler400 = 'rest_framework.exceptions.bad_request'
# 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

@ -1,4 +1,7 @@
source: fields.py
---
source:
- fields.py
---
# Serializer fields
@ -20,6 +23,8 @@ Each serializer field class constructor takes at least these arguments. Some Fi
### `read_only`
Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.
Set this to `True` to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.
Defaults to `False`
@ -37,25 +42,50 @@ 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 behavior is to not populate the attribute at all.
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a `requires_context = True` attribute, then the serializer field will be passed as an argument.
For example:
class CurrentUserDefault:
"""
May be applied as a `default=...` value on a serializer field.
Returns the current user.
"""
requires_context = True
def __call__(self, serializer_field):
return serializer_field.context['request'].user
When serializing the instance, default will be used if the object attribute or dictionary key is not present in the instance.
Note that setting a `default` value implies that the field is not required. Including both the `default` and `required` keyword arguments is invalid and will raise an error.
### `allow_null`
Normally an error will be raised if `None` is passed to a serializer field. Set this keyword argument to `True` if `None` should be considered a valid value.
Note that, without an explicit `default`, setting this argument to `True` will imply a `default` value of `null` for serialization output, but does not imply a default for input deserialization.
Defaults to `False`
### `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 behavior is to not populate the attribute at all.
May be set to a function or other callable, in which case the value will be evaluated each time it is used.
Note that setting a `default` value implies that the field is not required. Including both the `default` and `required` keyword arguments is invalid and will raise an error.
### `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('get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`.
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.
@ -79,13 +109,19 @@ A text string that may be used as a description of the field in HTML form fields
### `initial`
A value that should be used for pre-populating the value of HTML form fields.
A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as
you may do with any regular Django `Field`:
import datetime
from rest_framework import serializers
class ExampleSerializer(serializers.Serializer):
day = serializers.DateField(initial=datetime.date.today)
### `style`
A dictionary of key-value pairs that can be used to control how renderers should render the field. The API for this should still be considered experimental, and will be formalized with the 3.1 release.
A dictionary of key-value pairs that can be used to control how renderers should render the field.
Two options are currently used in HTML form generation, `'input_type'` and `'base_template'`.
Two examples here are `'input_type'` and `'base_template'`:
# Use <input type="password"> for the input.
password = serializers.CharField(
@ -94,11 +130,11 @@ Two options are currently used in HTML form generation, `'input_type'` and `'bas
# Use a radio input instead of a select input.
color_channel = serializers.ChoiceField(
choices=['red', 'green', 'blue']
style = {'base_template': 'radio.html'}
}
choices=['red', 'green', 'blue'],
style={'base_template': 'radio.html'}
)
**Note**: The `style` argument replaces the old-style version 2.x `widget` keyword argument. Because REST framework 3 now uses templated HTML form generation, the `widget` option that was used to support Django built-in widgets can no longer be supported. Version 3.1 is planned to include public API support for customizing HTML form generation.
For more details see the [HTML & Forms][html-and-forms] documentation.
---
@ -110,18 +146,19 @@ A boolean representation.
When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to `False`, even if it has a `default=True` option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.
Note that Django 2.1 removed the `blank` kwarg from `models.BooleanField`.
Prior to Django 2.1 `models.BooleanField` fields were always `blank=True`. Thus
since Django 2.1 default `serializers.BooleanField` instances will be generated
without the `required` kwarg (i.e. equivalent to `required=True`) whereas with
previous versions of Django, default `BooleanField` instances will be generated
with a `required=False` option. If you want to control this behavior manually,
explicitly declare the `BooleanField` on the serializer class, or use the
`extra_kwargs` option to set the `required` flag.
Corresponds to `django.db.models.fields.BooleanField`.
**Signature:** `BooleanField()`
## NullBooleanField
A boolean representation that also accepts `None` as a valid value.
Corresponds to `django.db.models.fields.NullBooleanField`.
**Signature:** `NullBooleanField()`
---
# String fields
@ -134,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.
@ -183,6 +220,40 @@ A field that ensures the input is a valid UUID string. The `to_internal_value` m
"de305d54-75b4-431b-adb2-eb6b9e546013"
**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"`
Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value`
## FilePathField
A field whose choices are limited to the filenames in a certain directory on the filesystem
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`.
## IPAddressField
A field that ensures the input is a valid IPv4 or IPv6 string.
Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.GenericIPAddressField`.
**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'.
---
# Numeric fields
@ -195,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
@ -206,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
@ -217,11 +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. Note that this number must be 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.
- `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_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
@ -233,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
@ -247,18 +317,17 @@ A date and time representation.
Corresponds to `django.db.models.fields.DateTimeField`.
**Signature:** `DateTimeField(format=None, input_formats=None)`
**Signature:** `DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None, default_timezone=None)`
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. In this case the datetime encoding will be determined by the renderer.
* `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 `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.
In the case of JSON this means the default datetime representation uses the [ECMA 262 date time string specification][ecma262]. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: `2013-01-29T12:34:56.123Z`.
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.
@ -278,7 +347,7 @@ A date representation.
Corresponds to `django.db.models.fields.DateField`
**Signature:** `DateField(format=None, input_formats=None)`
**Signature:** `DateField(format=api_settings.DATE_FORMAT, input_formats=None)`
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATE_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 `date` objects should be returned by `to_representation`. In this case the date 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 `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
@ -293,15 +362,28 @@ A time representation.
Corresponds to `django.db.models.fields.TimeField`
**Signature:** `TimeField(format=None, input_formats=None)`
**Signature:** `TimeField(format=api_settings.TIME_FORMAT, input_formats=None)`
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `TIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `time` objects should be returned by `to_representation`. In this case the time encoding will be determined by the renderer.
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
#### `TimeField` format strings
#### `TimeField` format strings
Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`)
## DurationField
A Duration representation.
Corresponds to `django.db.models.fields.DurationField`
The `validated_data` for these fields will contain a `datetime.timedelta` instance.
The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu]'`.
**Signature:** `DurationField(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.
---
# Choice selection fields
@ -314,8 +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`.
* `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.
@ -325,8 +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`.
* `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.
@ -347,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
@ -359,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.
@ -373,9 +459,12 @@ Requires either the `Pillow` package or `PIL` package. The `Pillow` package is
A field class that validates a list of objects.
**Signature**: `ListField(child)`
**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.
* `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:
@ -394,9 +483,10 @@ We can now reuse our custom `StringListField` class throughout our application,
A field class that validates a dictionary of objects. The keys in `DictField` are always assumed to be string values.
**Signature**: `DictField(child)`
**Signature**: `DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
* `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
* `allow_empty` - Designates if empty dictionaries are allowed.
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
@ -407,6 +497,26 @@ You can also use the declarative style, as with `ListField`. For example:
class DocumentField(DictField):
child = CharField()
## HStoreField
A preconfigured `DictField` that is compatible with Django's postgres `HStoreField`.
**Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
* `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
* `allow_empty` - Designates if empty dictionaries are allowed.
Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings.
## JSONField
A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.
**Signature**: `JSONField(binary, 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`.
---
# Miscellaneous fields
@ -419,12 +529,12 @@ This field is used by default with `ModelSerializer` when including field names
**Signature**: `ReadOnlyField()`
For example, is `has_expired` was a property on the `Account` model, then the following serializer would automatically generate it as a `ReadOnlyField`:
For example, if `has_expired` was a property on the `Account` model, then the following serializer would automatically generate it as a `ReadOnlyField`:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'has_expired')
fields = ['id', 'account_name', 'has_expired']
## HiddenField
@ -440,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.
@ -456,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:
@ -469,6 +585,7 @@ The serializer method referred to by the `method_name` argument should accept a
class Meta:
model = User
fields = '__all__'
def get_days_since_joined(self, obj):
return (now() - obj.date_joined).days
@ -481,15 +598,15 @@ If you want to create a custom field, you'll need to subclass `Field` and then o
The `.to_representation()` method is called to convert the initial datatype into a primitive, serializable datatype.
The `to_internal_value()` method is called to restore a primitive datatype into its internal python representation. This method should raise a `serializers.ValidationError` if the data is invalid.
Note that the `WritableField` class that was present in version 2.x no longer exists. You should subclass `Field` and override `to_internal_value()` if the field supports data input.
The `.to_internal_value()` method is called to restore a primitive datatype into its internal python representation. This method should raise a `serializers.ValidationError` if the data is invalid.
## Examples
### A Basic Custom Field
Let's look at an example of serializing a class that represents an RGB color value:
class Color(object):
class Color:
"""
A color represented in the RGB colorspace.
"""
@ -502,8 +619,8 @@ Let's look at an example of serializing a class that represents an RGB color val
"""
Color objects are serialized into 'rgb(#, #, #)' notation.
"""
def to_representation(self, obj):
return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue)
def to_representation(self, value):
return "rgb(%d, %d, %d)" % (value.red, value.green, value.blue)
def to_internal_value(self, data):
data = data.strip('rgb(').rstrip(')')
@ -512,27 +629,27 @@ Let's look at an example of serializing a class that represents an RGB color val
By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override `.get_attribute()` and/or `.get_value()`.
As an example, let's create a field that can be used represent the class name of the object being serialized:
As an example, let's create a field that can be used to represent the class name of the object being serialized:
class ClassNameField(serializers.Field):
def get_attribute(self, obj):
def get_attribute(self, instance):
# We pass the object instance onto `to_representation`,
# not just the field attribute.
return obj
return instance
def to_representation(self, obj):
def to_representation(self, value):
"""
Serialize the object's class name.
Serialize the value's class name.
"""
return obj.__class__.__name__
return value.__class__.__name__
#### Raising validation errors
### Raising validation errors
Our `ColorField` class above currently does not perform any data validation.
To indicate invalid data, we should raise a `serializers.ValidationError`, like so:
def to_internal_value(self, data):
if not isinstance(data, six.text_type):
if not isinstance(data, str):
msg = 'Incorrect type. Expected a string, but got %s'
raise ValidationError(msg % type(data).__name__)
@ -556,8 +673,7 @@ The `.fail()` method is a shortcut for raising `ValidationError` that takes a me
}
def to_internal_value(self, data):
if not isinstance(data, six.text_type):
msg = 'Incorrect type. Expected a string, but got %s'
if not isinstance(data, str):
self.fail('incorrect_type', input_type=type(data).__name__)
if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data):
@ -571,7 +687,138 @@ The `.fail()` method is a shortcut for raising `ValidationError` that takes a me
return Color(red, green, blue)
This style keeps you error messages more cleanly separated from your code, and should be preferred.
This style keeps your error messages cleaner and more separated from your code, and should be preferred.
### Using `source='*'`
Here we'll take an example of a _flat_ `DataPoint` model with `x_coordinate` and `y_coordinate` attributes.
class DataPoint(models.Model):
label = models.CharField(max_length=50)
x_coordinate = models.SmallIntegerField()
y_coordinate = models.SmallIntegerField()
Using a custom field and `source='*'` we can provide a nested representation of
the coordinate pair:
class CoordinateField(serializers.Field):
def to_representation(self, value):
ret = {
"x": value.x_coordinate,
"y": value.y_coordinate
}
return ret
def to_internal_value(self, data):
ret = {
"x_coordinate": data["x"],
"y_coordinate": data["y"],
}
return ret
class DataPointSerializer(serializers.ModelSerializer):
coordinates = CoordinateField(source='*')
class Meta:
model = DataPoint
fields = ['label', 'coordinates']
Note that this example doesn't handle validation. Partly for that reason, in a
real project, the coordinate nesting might be better handled with a nested serializer
using `source='*'`, with two `IntegerField` instances, each with their own `source`
pointing to the relevant field.
The key points from the example, though, are:
* `to_representation` is passed the entire `DataPoint` object and must map from that
to the desired output.
>>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2)
>>> out_serializer = DataPointSerializer(instance)
>>> out_serializer.data
ReturnDict([('label', 'Example'), ('coordinates', {'x': 1, 'y': 2})])
* Unless our field is to be read-only, `to_internal_value` must map back to a dict
suitable for updating our target object. With `source='*'`, the return from
`to_internal_value` will update the root validated data dictionary, rather than a single key.
>>> data = {
... "label": "Second Example",
... "coordinates": {
... "x": 3,
... "y": 4,
... }
... }
>>> in_serializer = DataPointSerializer(data=data)
>>> in_serializer.is_valid()
True
>>> in_serializer.validated_data
OrderedDict([('label', 'Second Example'),
('y_coordinate', 4),
('x_coordinate', 3)])
For completeness lets do the same thing again but with the nested serializer
approach suggested above:
class NestedCoordinateSerializer(serializers.Serializer):
x = serializers.IntegerField(source='x_coordinate')
y = serializers.IntegerField(source='y_coordinate')
class DataPointSerializer(serializers.ModelSerializer):
coordinates = NestedCoordinateSerializer(source='*')
class Meta:
model = DataPoint
fields = ['label', 'coordinates']
Here the mapping between the target and source attribute pairs (`x` and
`x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField`
declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`.
Our new `DataPointSerializer` exhibits the same behavior as the custom field
approach.
Serializing:
>>> out_serializer = DataPointSerializer(instance)
>>> out_serializer.data
ReturnDict([('label', 'testing'),
('coordinates', OrderedDict([('x', 1), ('y', 2)]))])
Deserializing:
>>> in_serializer = DataPointSerializer(data=data)
>>> in_serializer.is_valid()
True
>>> in_serializer.validated_data
OrderedDict([('label', 'still testing'),
('x_coordinate', 3),
('y_coordinate', 4)])
But we also get the built-in validation for free:
>>> invalid_data = {
... "label": "still testing",
... "coordinates": {
... "x": 'a',
... "y": 'b',
... }
... }
>>> invalid_serializer = DataPointSerializer(data=invalid_data)
>>> invalid_serializer.is_valid()
False
>>> invalid_serializer.errors
ReturnDict([('coordinates',
{'x': ['A valid integer is required.'],
'y': ['A valid integer is required.']})])
For this reason, the nested serializer approach would be the first to try. You
would use the custom field approach when the nested serializer becomes infeasible
or overly complex.
# Third party packages
@ -585,27 +832,29 @@ The [drf-compound-fields][drf-compound-fields] package provides "compound" seria
The [drf-extra-fields][drf-extra-fields] package provides extra serializer fields for REST framework, including `Base64ImageField` and `PointField` classes.
## djangrestframework-recursive
## djangorestframework-recursive
the [djangorestframework-recursive][djangorestframework-recursive] package provides a `RecursiveField` for serializing and deserializing recursive structures
## 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
The [django-rest-framework-hstore][django-rest-framework-hstore] package provides an `HStoreField` to support [django-hstore][django-hstore] `DictionaryField` model field.
[cite]: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data
[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
[ecma262]: http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
[strftime]: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
[django-widgets]: https://docs.djangoproject.com/en/dev/ref/forms/widgets/
[iso8601]: http://www.w3.org/TR/NOTE-datetime
[drf-compound-fields]: http://drf-compound-fields.readthedocs.org
[cite]: https://docs.djangoproject.com/en/stable/ref/forms/api/#django.forms.Form.cleaned_data
[html-and-forms]: ../topics/html-and-forms.md
[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
[strftime]: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
[iso8601]: https://www.w3.org/TR/NOTE-datetime
[drf-compound-fields]: https://drf-compound-fields.readthedocs.io
[drf-extra-fields]: https://github.com/Hipo/drf-extra-fields
[djangorestframework-recursive]: https://github.com/heywbj/django-rest-framework-recursive
[django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis
[django-rest-framework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore
[django-hstore]: https://github.com/djangonauts/django-hstore
[python-decimal-rounding-modes]: https://docs.python.org/3/library/decimal.html#rounding-modes
[django-current-timezone]: https://docs.djangoproject.com/en/stable/topics/i18n/timezones/#default-time-zone-and-current-time-zone
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related

View File

@ -1,4 +1,7 @@
source: filters.py
---
source:
- filters.py
---
# Filtering
@ -42,7 +45,7 @@ Another style of filtering might involve restricting the queryset based on some
For example if your URL config contained an entry like this:
url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
re_path('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
@ -72,7 +75,7 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
by filtering against a `username` query parameter in the URL.
"""
queryset = Purchase.objects.all()
username = self.request.query_params.get('username', None)
username = self.request.query_params.get('username')
if username is not None:
queryset = queryset.filter(purchaser__username=username)
return queryset
@ -83,26 +86,30 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.
Generic filters can also present themselves as HTML controls in the browsable API and admin API.
![Filter Example](../img/filter-controls.png)
## Setting filter backends
The default filter backends may be set globally, using the `DEFAULT_FILTER_BACKENDS` setting. For example.
The default filter backends may be set globally, using the `DEFAULT_FILTER_BACKENDS` setting. For example.
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}
You can also set the filter backends on a per-view, or per-viewset basis,
using the `GenericAPIView` class based views.
using the `GenericAPIView` class-based views.
import django_filters.rest_framework
from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
from rest_framework import filters
from rest_framework import generics
from myapp.serializers import UserSerializer
from rest_framework import generics
class UserListView(generics.ListAPIView):
queryset = User.objects.all()
serializer = UserSerializer
filter_backends = (filters.DjangoFilterBackend,)
serializer_class = UserSerializer
filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
## Filtering and object lookups
@ -123,7 +130,7 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering
"""
model = Product
serializer_class = ProductSerializer
filter_class = ProductFilter
filterset_class = ProductFilter
def get_queryset(self):
user = self.request.user
@ -135,112 +142,69 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering
## DjangoFilterBackend
The `DjangoFilterBackend` class supports highly customizable field filtering, using the [django-filter package][django-filter].
The [`django-filter`][django-filter-docs] library includes a `DjangoFilterBackend` class which
supports highly customizable field filtering for REST framework.
To use REST framework's `DjangoFilterBackend`, first install `django-filter`.
To use `DjangoFilterBackend`, first install `django-filter`.
pip install django-filter
Then add `'django_filters'` to Django's `INSTALLED_APPS`:
#### Specifying filter fields
INSTALLED_APPS = [
...
'django_filters',
...
]
If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against.
You should now either add the filter backend to your settings:
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}
Or add the filter backend to an individual View or ViewSet.
from django_filters.rest_framework import DjangoFilterBackend
class UserListView(generics.ListAPIView):
...
filter_backends = [DjangoFilterBackend]
If all you need is simple equality-based filtering, you can set a `filterset_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against.
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_fields = ('category', 'in_stock')
filter_backends = [DjangoFilterBackend]
filterset_fields = ['category', 'in_stock']
This will automatically create a `FilterSet` class for the given fields, and will allow you to make requests such as:
http://example.com/api/products?category=clothing&in_stock=True
#### Specifying a FilterSet
For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view.
You can read more about `FilterSet`s in the [django-filter documentation][django-filter-docs].
It's also recommended that you read the section on [DRF integration][django-filter-drf-docs].
For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view. For example:
import django_filters
from myapp.models import Product
from myapp.serializers import ProductSerializer
from rest_framework import generics
class ProductFilter(django_filters.FilterSet):
min_price = django_filters.NumberFilter(name="price", lookup_type='gte')
max_price = django_filters.NumberFilter(name="price", lookup_type='lte')
class Meta:
model = Product
fields = ['category', 'in_stock', 'min_price', 'max_price']
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_class = ProductFilter
Which will allow you to make requests such as:
http://example.com/api/products?category=clothing&max_price=10.00
You can also span relationships using `django-filter`, let's assume that each
product has foreign key to `Manufacturer` model, so we create filter that
filters using `Manufacturer` name. For example:
import django_filters
from myapp.models import Product
from myapp.serializers import ProductSerializer
from rest_framework import generics
class ProductFilter(django_filters.FilterSet):
class Meta:
model = Product
fields = ['category', 'in_stock', 'manufacturer__name']
This enables us to make queries like:
http://example.com/api/products?manufacturer__name=foo
This is nice, but it exposes the Django's double underscore convention as part of the API. If you instead want to explicitly name the filter argument you can instead explicitly include it on the `FilterSet` class:
import django_filters
from myapp.models import Product
from myapp.serializers import ProductSerializer
from rest_framework import generics
class ProductFilter(django_filters.FilterSet):
manufacturer = django_filters.CharFilter(name="manufacturer__name")
class Meta:
model = Product
fields = ['category', 'in_stock', 'manufacturer']
And now you can execute:
http://example.com/api/products?manufacturer=foo
For more details on using filter sets see the [django-filter documentation][django-filter-docs].
---
**Hints & Tips**
* By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'DEFAULT_FILTER_BACKENDS'` setting.
* When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].)
* `django-filter` supports filtering across relationships, using Django's double-underscore syntax.
* For Django 1.3 support, make sure to install `django-filter` version 0.5.4, as later versions drop support for 1.3.
---
## SearchFilter
The `SearchFilter` class supports simple single query parameter based searching, and is based on the [Django admin's search functionality][search-django-admin].
When in use, the browsable API will include a `SearchFilter` control:
![Search Filter](../img/search-filter.png)
The `SearchFilter` class will only be applied if the view has a `search_fields` attribute set. The `search_fields` attribute should be a list of names of text type fields on the model, such as `CharField` or `TextField`.
from rest_framework import filters
class UserListView(generics.ListAPIView):
queryset = User.objects.all()
serializer = UserSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('username', 'email')
serializer_class = UserSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['username', 'email']
This will allow the client to filter the items in the list by making queries such as:
@ -248,21 +212,40 @@ This will allow the client to filter the items in the list by making queries suc
You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:
search_fields = ('username', 'email', 'profile__profession')
search_fields = ['username', 'email', 'profile__profession']
By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.
For [JSONField][JSONField] and [HStoreField][HStoreField] fields you can filter based on nested values within the data structure using the same double-underscore notation:
The search behavior may be restricted by prepending various characters to the `search_fields`.
search_fields = ['data__breed', 'data__owner__other_pets__0__name']
* '^' Starts-with search.
* '=' Exact matches.
* '@' Full-text search. (Currently only supported Django's MySQL backend.)
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 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:
search_fields = ('=username', '=email')
search_fields = ['=username', '=email']
By default, the search parameter is named `'search`', but this may be overridden with the `SEARCH_PARAM` setting.
By default, the search parameter is named `'search'`, but this may be overridden with the `SEARCH_PARAM` setting.
To dynamically change search fields based on request content, it's possible to subclass the `SearchFilter` and override the `get_search_fields()` function. For example, the following subclass will only search on `title` if the query parameter `title_only` is in the request:
from rest_framework import filters
class CustomSearchFilter(filters.SearchFilter):
def get_search_fields(self, view, request):
if request.query_params.get('title_only'):
return ['title']
return super().get_search_fields(view, request)
For more details, see the [Django documentation][search-django-admin].
@ -270,7 +253,11 @@ For more details, see the [Django documentation][search-django-admin].
## OrderingFilter
The `OrderingFilter` class supports simple query parameter controlled ordering of results. By default, the query parameter is named `'ordering'`, but this may by overridden with the `ORDERING_PARAM` setting.
The `OrderingFilter` class supports simple query parameter controlled ordering of results.
![Ordering Filter](../img/ordering-filter.png)
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:
@ -286,13 +273,13 @@ 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()
serializer_class = UserSerializer
filter_backends = (filters.OrderingFilter,)
ordering_fields = ('username', 'email')
filter_backends = [filters.OrderingFilter]
ordering_fields = ['username', 'email']
This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data.
@ -303,7 +290,7 @@ If you are confident that the queryset being used by the view doesn't contain an
class BookingsListView(generics.ListAPIView):
queryset = Booking.objects.all()
serializer_class = BookingSerializer
filter_backends = (filters.OrderingFilter,)
filter_backends = [filters.OrderingFilter]
ordering_fields = '__all__'
### Specifying a default ordering
@ -315,57 +302,14 @@ Typically you'd instead control this by setting `order_by` on the initial querys
class UserListView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = (filters.OrderingFilter,)
ordering_fields = ('username', 'email')
ordering = ('username',)
filter_backends = [filters.OrderingFilter]
ordering_fields = ['username', 'email']
ordering = ['username']
The `ordering` attribute may be either a string or a list/tuple of strings.
---
## DjangoObjectPermissionsFilter
The `DjangoObjectPermissionsFilter` is intended to be used together with the [`django-guardian`][guardian] package, with custom `'view'` permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.
This filter class must be used with views that provide either a `queryset` or a `model` attribute.
If you're using `DjangoObjectPermissionsFilter`, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass `DjangoObjectPermissions` and add `'view'` permissions to the `perms_map` attribute.
A complete example using both `DjangoObjectPermissionsFilter` and `DjangoObjectPermissions` might look something like this.
**permissions.py**:
class CustomObjectPermissions(permissions.DjangoObjectPermissions):
"""
Similar to `DjangoObjectPermissions`, but adding 'view' permissions.
"""
perms_map = {
'GET': ['%(app_label)s.view_%(model_name)s'],
'OPTIONS': ['%(app_label)s.view_%(model_name)s'],
'HEAD': ['%(app_label)s.view_%(model_name)s'],
'POST': ['%(app_label)s.add_%(model_name)s'],
'PUT': ['%(app_label)s.change_%(model_name)s'],
'PATCH': ['%(app_label)s.change_%(model_name)s'],
'DELETE': ['%(app_label)s.delete_%(model_name)s'],
}
**views.py**:
class EventViewSet(viewsets.ModelViewSet):
"""
Viewset that only lists events if user has 'view' permissions, and only
allows operations on individual events if user has appropriate 'view', 'add',
'change' or 'delete' permissions.
"""
queryset = Event.objects.all()
serializer = EventSerializer
filter_backends = (filters.DjangoObjectPermissionsFilter,)
permission_classes = (myapp.permissions.CustomObjectPermissions,)
For more information on adding `'view'` permissions for models, see the [relevant section][view-permissions] of the `django-guardian` documentation, and [this blogpost][view-permissions-blogpost].
---
# Custom generic filtering
You can also provide your own generic filtering backend, or write an installable app for other developers to use.
@ -387,6 +331,14 @@ For example, you might need to restrict users to only being able to see objects
We could achieve the same behavior by overriding `get_queryset()` on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.
## Customizing the interface
Generic filters may also present an interface in the browsable API. To do so you should implement a `to_html()` method which returns a rendered HTML representation of the filter. This method should have the following signature:
`to_html(self, request, queryset, view)`
The method should return a rendered HTML string.
# Third party packages
The following third party packages provide additional filter implementations.
@ -399,13 +351,22 @@ The [django-rest-framework-filters package][django-rest-framework-filters] works
The [djangorestframework-word-filter][django-rest-framework-word-search-filter] developed as alternative to `filters.SearchFilter` which will search full word in text, or exact match.
[cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters
[django-filter]: https://github.com/alex/django-filter
[django-filter-docs]: https://django-filter.readthedocs.org/en/latest/index.html
[guardian]: https://django-guardian.readthedocs.org/
[view-permissions]: https://django-guardian.readthedocs.org/en/latest/userguide/assign.html
[view-permissions-blogpost]: http://blog.nyaruka.com/adding-a-view-permission-to-django-models
[nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py
[search-django-admin]: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields
## Django URL Filter
[django-url-filter][django-url-filter] provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django `QuerySet`s.
## drf-url-filters
[drf-url-filter][drf-url-filter] is a simple Django app to apply filters on drf `ModelViewSet`'s `Queryset` in a clean, simple and configurable way. It also supports validations on incoming query params and their values. A beautiful python package `Voluptuous` is being used for validations on the incoming query parameters. The best part about voluptuous is you can define your own validations as per your query params requirements.
[cite]: https://docs.djangoproject.com/en/stable/topics/db/queries/#retrieving-specific-objects-with-filters
[django-filter-docs]: https://django-filter.readthedocs.io/en/latest/index.html
[django-filter-drf-docs]: https://django-filter.readthedocs.io/en/latest/guide/rest_framework.html
[search-django-admin]: https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields
[django-rest-framework-filters]: https://github.com/philipn/django-rest-framework-filters
[django-rest-framework-word-search-filter]: https://github.com/trollknurr/django-rest-framework-word-search-filter
[django-url-filter]: https://github.com/miki725/django-url-filter
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
[HStoreField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#hstorefield
[JSONField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#jsonfield
[postgres-search]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/search/

View File

@ -1,4 +1,7 @@
source: urlpatterns.py
---
source:
- urlpatterns.py
---
# Format suffixes
@ -20,8 +23,8 @@ Returns a URL pattern list which includes format suffix patterns appended to eac
Arguments:
* **urlpatterns**: Required. A URL pattern list.
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
Example:
@ -29,20 +32,20 @@ Example:
from blog import views
urlpatterns = [
url(r'^/$', views.apt_root),
url(r'^comments/$', views.comment_list),
url(r'^comments/(?P<pk>[0-9]+)/$', views.comment_detail)
path('', views.apt_root),
path('comments/', views.comment_list),
path('comments/<int:pk>/', views.comment_detail)
]
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example:
@api_view(('GET', 'POST'))
@api_view(['GET', 'POST'])
def comment_list(request, format=None):
# do stuff...
Or with class based views:
Or with class-based views:
class CommentList(APIView):
def get(self, request, format=None):
@ -59,7 +62,7 @@ Also note that `format_suffix_patterns` does not support descending into `includ
If using the `i18n_patterns` function provided by Django, as well as `format_suffix_patterns` you should make sure that the `i18n_patterns` function is applied as the final, or outermost function. For example:
url patterns = [
urlpatterns = [
]
@ -69,6 +72,16 @@ If using the `i18n_patterns` function provided by Django, as well as `format_suf
---
## Query parameter formats
An alternative to the format suffixes is to include the requested format in a query parameter. REST framework provides this option by default, and it is used in the browsable API to switch between differing available representations.
To select a representation using its short format, use the `format` query parameter. For example: `http://example.com/organizations/?format=csv`.
The name of this query parameter can be modified using the `URL_FORMAT_OVERRIDE` setting. Set the value to `None` to disable this behavior.
---
## Accept headers vs. format suffixes
There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead.
@ -80,4 +93,4 @@ It is actually a misconception. For example, take the following quote from Roy
The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern.
[cite]: http://tech.groups.yahoo.com/group/rest-discuss/message/5857
[cite2]: http://tech.groups.yahoo.com/group/rest-discuss/message/14844
[cite2]: https://groups.yahoo.com/neo/groups/rest-discuss/conversations/topics/14844

View File

@ -1,5 +1,8 @@
source: mixins.py
generics.py
---
source:
- mixins.py
- generics.py
---
# Generic views
@ -7,7 +10,7 @@ source: mixins.py
>
> &mdash; [Django Documentation][cite]
One of the key benefits of class based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
@ -25,23 +28,14 @@ Typically when using the generic views, you'll override the view, and set severa
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (IsAdminUser,)
paginate_by = 100
permission_classes = [IsAdminUser]
For more complex cases you might also want to override various methods on the view class. For example.
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (IsAdminUser,)
def get_paginate_by(self):
"""
Use smaller pagination for HTML representations.
"""
if self.request.accepted_renderer.format == 'html':
return 20
return 100
permission_classes = [IsAdminUser]
def list(self, request):
# Note the use of `get_queryset()` instead of `self.queryset`
@ -51,7 +45,7 @@ For more complex cases you might also want to override various methods on the vi
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something like the following entry:
url(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
path('users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
---
@ -71,16 +65,14 @@ 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**:
The following attributes are used to control pagination when used with list views.
* `pagination_class` - The pagination class that should be used when paginating list results. Defaults to the same value as the `DEFAULT_PAGINATION_CLASS` setting, which is `'rest_framework.pagination.PageNumberPagination'`.
Note that usage of the `paginate_by`, `paginate_by_param` and `page_kwarg` attributes are now pending deprecation. The `pagination_serializer_class` attribute and `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting have been removed completely. Pagination settings should instead be controlled by overriding a pagination class and setting any configuration attributes there. See the pagination documentation for more details.
* `pagination_class` - The pagination class that should be used when paginating list results. Defaults to the same value as the `DEFAULT_PAGINATION_CLASS` setting, which is `'rest_framework.pagination.PageNumberPagination'`. Setting `pagination_class=None` will disable pagination on this view.
**Filtering**:
@ -104,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.
@ -124,21 +122,24 @@ For example:
Note that if your API doesn't include any object level permissions, you may optionally exclude the `self.check_object_permissions`, and simply return the object from the `get_object_or_404` lookup.
#### `get_filter_backends(self)`
#### `filter_queryset(self, queryset)`
Returns the classes that should be used to filter the queryset. Defaults to returning the `filter_backends` attribute.
May be overridden to provide more complex behavior with filters, such as using different (or even exclusive) lists of filter_backends depending on different criteria.
Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
For example:
def get_filter_backends(self):
if "geo_route" in self.request.query_params:
return (GeoRouteFilter, CategoryFilter)
elif "geo_point" in self.request.query_params:
return (GeoPointFilter, CategoryFilter)
def filter_queryset(self, queryset):
filter_backends = [CategoryFilter]
return (CategoryFilter,)
if 'geo_route' in self.request.query_params:
filter_backends = [GeoRouteFilter, CategoryFilter]
elif 'geo_point' in self.request.query_params:
filter_backends = [GeoPointFilter, CategoryFilter]
for backend in list(filter_backends):
queryset = backend().filter_queryset(self.request, queryset, view=self)
return queryset
#### `get_serializer_class(self)`
@ -153,19 +154,6 @@ For example:
return FullAccountSerializer
return BasicAccountSerializer
#### `get_paginate_by(self)`
Returns the page size to use with pagination. By default this uses the `paginate_by` attribute, and may be overridden by the client if the `paginate_by_param` attribute is set.
You may want to override this method to provide more complex behavior, such as modifying page sizes based on the media type of the response.
For example:
def get_paginate_by(self):
if self.request.accepted_renderer.format == 'html':
return 20
return 100
**Save and deletion hooks**:
The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
@ -185,14 +173,20 @@ These override points are also particularly useful for adding behavior that occu
instance = serializer.save()
send_email_confirmation(user=self.request.user, modified=instance)
**Note**: These methods replace the old-style version 2.x `pre_save`, `post_save`, `pre_delete` and `post_delete` methods, which are no longer available.
You can also use these hooks to provide additional validation, by raising a `ValidationError()`. This can be useful if you need some validation logic to apply at the point of database save. For example:
def perform_create(self, serializer):
queryset = SignupRequest.objects.filter(user=self.request.user)
if queryset.exists():
raise ValidationError('You have already signed up')
serializer.save(user=self.request.user)
**Other methods**:
You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`.
* `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys.
* `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False, allow_add_remove=False)` - Returns a serializer instance.
* `get_serializer(self, instance=None, data=None, many=False, partial=False)` - Returns a serializer instance.
* `get_paginated_response(self, data)` - Returns a paginated style `Response` object.
* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view.
* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
@ -223,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
@ -233,8 +227,6 @@ Also provides a `.partial_update(request, *args, **kwargs)` method, which is sim
If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response.
If an object is created, for example when making a `DELETE` request followed by a `PUT` request to the same URL, this returns a `201 Created` response, with a serialized representation of the object as the body of the response.
If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
## DestroyModelMixin
@ -333,7 +325,7 @@ Often you'll want to use the existing generic views, but use some slightly custo
For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:
class MultipleFieldLookupMixin(object):
class MultipleFieldLookupMixin:
"""
Apply this mixin to any view or viewset to get multiple field filtering
based on a `lookup_fields` attribute, instead of the default single field filtering.
@ -343,15 +335,18 @@ 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:
filter[field] = self.kwargs[field]
return get_object_or_404(queryset, **filter) # Lookup the object
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)
return obj
You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.
class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_fields = ('account', 'username')
lookup_fields = ['account', 'username']
Using custom mixins is a good option if you have custom behavior that needs to be used.
@ -387,16 +382,17 @@ If you need to generic PUT-as-create behavior you may want to include something
The following third party packages provide additional generic view implementations.
## Django REST Framework bulk
## Django Rest Multiple Models
The [django-rest-framework-bulk package][django-rest-framework-bulk] implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.
[Django Rest Multiple Models][django-rest-multiple-models] provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
[cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views
[cite]: https://docs.djangoproject.com/en/stable/ref/class-based-views/#base-vs-generic-views
[GenericAPIView]: #genericapiview
[ListModelMixin]: #listmodelmixin
[CreateModelMixin]: #createmodelmixin
[RetrieveModelMixin]: #retrievemodelmixin
[UpdateModelMixin]: #updatemodelmixin
[DestroyModelMixin]: #destroymodelmixin
[django-rest-framework-bulk]: https://github.com/miki725/django-rest-framework-bulk
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related

View File

@ -1,4 +1,7 @@
source: metadata.py
---
source:
- metadata.py
---
# Metadata
@ -67,8 +70,8 @@ If you have specific requirements for creating schema endpoints that are accesse
For example, the following additional route could be used on a viewset to provide a linkable schema endpoint.
@list_route(methods=['GET'])
def schema(self, request):
@action(methods=['GET'], detail=False)
def api_schema(self, request):
meta = self.metadata_class()
data = meta.determine_metadata(request, self)
return Response(data)
@ -98,6 +101,24 @@ The following class could be used to limit the information that is returned to `
'description': view.get_view_description()
}
[cite]: http://tools.ietf.org/html/rfc7231#section-4.3.7
Then configure your settings to use this custom class:
REST_FRAMEWORK = {
'DEFAULT_METADATA_CLASS': 'myproject.apps.core.MinimalMetadata'
}
# Third party packages
The following third party packages provide additional metadata implementations.
## DRF-schema-adapter
[drf-schema-adapter][drf-schema-adapter] is a set of tools that makes it easier to provide schema information to frontend frameworks and libraries. It provides a metadata mixin as well as 2 metadata classes and several adapters suitable to generate [json-schema][json-schema] as well as schema information readable by various libraries.
You can also write your own adapter to work with your specific frontend.
If you wish to do so, it also provides an exporter that can export those schema information to json files.
[cite]: https://tools.ietf.org/html/rfc7231#section-4.3.7
[no-options]: https://www.mnot.net/blog/2012/10/29/NO_OPTIONS
[json-schema]: http://json-schema.org/
[json-schema]: https://json-schema.org/
[drf-schema-adapter]: https://github.com/drf-forms/drf-schema-adapter

View File

@ -1,4 +1,7 @@
source: pagination.py
---
source:
- pagination.py
---
# Pagination
@ -15,16 +18,21 @@ The pagination API can support either:
The built-in styles currently all use links included as part of the content of the response. This style is more accessible when using the browsable API.
Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular `APIView`, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the `mixins.ListMixin` and `generics.GenericAPIView` classes for an example.
Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular `APIView`, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the `mixins.ListModelMixin` and `generics.GenericAPIView` classes for an example.
Pagination can be turned off by setting the pagination class to `None`.
## Setting the pagination style
The default pagination style may be set globally, using the `DEFAULT_PAGINATION_CLASS` settings key. For example, to use the built-in limit/offset pagination, you would do:
The pagination style may be set globally, using the `DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` setting keys. For example, to use the built-in limit/offset pagination, you would do something like this:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 100
}
Note that you need to set both the pagination class, and the page size that should be used. Both `DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` are `None` by default.
You can also set the pagination class on an individual view by using the `pagination_class` attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis.
## Modifying the pagination style
@ -41,18 +49,18 @@ If you want to modify particular aspects of the pagination style, you'll want to
page_size_query_param = 'page_size'
max_page_size = 1000
You can then apply your new style to a view using the `.pagination_class` attribute:
You can then apply your new style to a view using the `pagination_class` attribute:
class BillingRecordsView(generics.ListAPIView):
queryset = Billing.objects.all()
serializer = BillingRecordsSerializer
serializer_class = BillingRecordsSerializer
pagination_class = LargeResultsSetPagination
Or apply the style globally, using the `DEFAULT_PAGINATION_CLASS` settings key. For example:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination'
}
}
---
@ -70,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": [
@ -80,7 +88,7 @@ This pagination style accepts a single number page number in the request query p
#### Setup
To enable the `PageNumberPagination` style globally, use the following configuration, modifying the `PAGE_SIZE` as desired:
To enable the `PageNumberPagination` style globally, use the following configuration, and set the `PAGE_SIZE` as desired:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
@ -95,6 +103,7 @@ The `PageNumberPagination` class includes a number of attributes that may be ove
To set these attributes you should override the `PageNumberPagination` class, and then enable your custom pagination class as above.
* `django_paginator_class` - The Django Paginator class to use. Default is `django.core.paginator.Paginator`, which should be fine for most use cases.
* `page_size` - A numeric value indicating the page size. If set, this overrides the `PAGE_SIZE` setting. Defaults to the same value as the `PAGE_SIZE` settings key.
* `page_query_param` - A string value indicating the name of the query parameter to use for the pagination control.
* `page_size_query_param` - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to `None`, indicating that the client may not control the requested page size.
@ -106,7 +115,7 @@ To set these attributes you should override the `PageNumberPagination` class, an
## LimitOffsetPagination
This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an
This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an
"offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the `page_size` in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items.
**Request**:
@ -117,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": [
@ -173,9 +182,13 @@ Proper usage of cursor pagination should have an ordering field that satisfies t
* Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation.
* Should be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart "position plus offset" style that allows it to properly support not-strictly-unique values as the ordering.
* Should be a non-nullable value that can be coerced to a string.
* Should not be a float. Precision errors easily lead to incorrect results.
Hint: use decimals instead.
(If you already have a float field and must paginate on that, an
[example `CursorPagination` subclass that uses decimals to limit precision is available here][float_cursor_pagination_example].)
* The field should have a database index.
Using an ordering field that does not satisfy these constraints will generally still work, but you'll be loosing some of the benefits of cursor pagination.
Using an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination.
For more technical details on the implementation we use for cursor pagination, the ["Building cursors for the Disqus API"][disqus-cursor-api] blog post gives a good overview of the basic approach.
@ -205,29 +218,29 @@ 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):
return Response({
'links': {
'next': self.get_next_link(),
'previous': self.get_previous_link()
'next': self.get_next_link(),
'previous': self.get_previous_link()
},
'count': self.page.paginator.count,
'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',
@ -236,29 +249,6 @@ We'd then need to setup the custom class in our configuration:
Note that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an `OrderedDict` when constructing the body of paginated responses, but this is optional.
## Header based pagination
Let's modify the built-in `PageNumberPagination` style, so that instead of include the pagination links in the body of the response, we'll instead include a `Link` header, in a [similar style to the GitHub API][github-link-pagination].
class LinkHeaderPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
next_url = self.get_next_link()
previous_url = self.get_previous_link()
if next_url is not None and previous_url is not None:
link = '<{next_url}; rel="next">, <{previous_url}; rel="prev">'
elif next_url is not None:
link = '<{next_url}; rel="next">'
elif previous_url is not None:
link = '<{previous_url}; rel="prev">'
else:
link = ''
link = link.format(next_url=next_url, previous_url=previous_url)
headers = {'Link': link} if link else {}
return Response(data, headers=headers)
## Using your custom pagination class
To have your custom pagination class be used by default, use the `DEFAULT_PAGINATION_CLASS` setting:
@ -270,11 +260,9 @@ To have your custom pagination class be used by default, use the `DEFAULT_PAGINA
API responses for list endpoints will now include a `Link` header, instead of including the pagination links as part of the body of the response, for example:
---
![Link Header][link-header]
*A custom pagination style, using the 'Link' header'*
*A custom pagination style, using the 'Link' header*
---
@ -309,9 +297,20 @@ The following third party packages are also available.
The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` mixin class][paginate-by-max-mixin] that allows your API clients to specify `?page_size=max` to obtain the maximum allowed page size.
[cite]: https://docs.djangoproject.com/en/dev/topics/pagination/
[github-link-pagination]: https://developer.github.com/guides/traversing-with-pagination/
## drf-proxy-pagination
The [`drf-proxy-pagination` package][drf-proxy-pagination] includes a `ProxyPagination` class which allows to choose pagination class with a query parameter.
## 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 REST API documentation][github-traversing-with-pagination].
[cite]: https://docs.djangoproject.com/en/stable/topics/pagination/
[link-header]: ../img/link-header-pagination.png
[drf-extensions]: http://chibisov.github.io/drf-extensions/docs/
[paginate-by-max-mixin]: http://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin
[disqus-cursor-api]: http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api/
[drf-extensions]: https://chibisov.github.io/drf-extensions/docs/
[paginate-by-max-mixin]: https://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin
[drf-proxy-pagination]: https://github.com/tuffnatty/drf-proxy-pagination
[drf-link-header-pagination]: https://github.com/tbeadle/django-rest-framework-link-header-pagination
[disqus-cursor-api]: 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

@ -1,4 +1,7 @@
source: parsers.py
---
source:
- parsers.py
---
# Parsers
@ -8,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.
---
@ -29,13 +32,13 @@ As an example, if you are sending `json` encoded data using jQuery with the [.aj
The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow only requests with `JSON` content, instead of the default of JSON or form data.
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
)
]
}
You can also set the parsers used for an individual view, or viewset,
using the `APIView` class based views.
using the `APIView` class-based views.
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
@ -45,15 +48,19 @@ using the `APIView` class based views.
"""
A view that can accept POST requests with JSON content.
"""
parser_classes = (JSONParser,)
parser_classes = [JSONParser]
def post(self, request, format=None):
return Response({'received data': request.data})
Or, if you're using the `@api_view` decorator with function based views.
from rest_framework.decorators import api_view
from rest_framework.decorators import parser_classes
from rest_framework.parsers import JSONParser
@api_view(['POST'])
@parser_classes((JSONParser,))
@parser_classes([JSONParser])
def example_view(request, format=None):
"""
A view that can accept POST requests with JSON content.
@ -66,7 +73,7 @@ Or, if you're using the `@api_view` decorator with function based views.
## JSONParser
Parses `JSON` request content.
Parses `JSON` request content. `request.data` will be populated with a dictionary of data.
**.media_type**: `application/json`
@ -80,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.
@ -90,20 +97,23 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
Parses raw file upload content. The `request.data` property will be a dictionary with a single key `'file'` containing the uploaded file.
If the view used with `FileUploadParser` is called with a `filename` URL keyword argument, then that argument will be used as the filename. If it is called without a `filename` URL keyword argument, then the client must set the filename in the `Content-Disposition` HTTP header. For example `Content-Disposition: attachment; filename=upload.jpg`.
If the view used with `FileUploadParser` is called with a `filename` URL keyword argument, then that argument will be used as the filename.
If it is called without a `filename` URL keyword argument, then the client must set the filename in the `Content-Disposition` HTTP header. For example `Content-Disposition: attachment; filename=upload.jpg`.
**.media_type**: `*/*`
##### Notes:
* The `FileUploadParser` is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the `MultiPartParser` parser instead.
* The `FileUploadParser` is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the `MultiPartParser` instead.
* Since this parser's `media_type` matches any content type, `FileUploadParser` should generally be the only parser set on an API view.
* `FileUploadParser` respects Django's standard `FILE_UPLOAD_HANDLERS` setting, and the `request.upload_handlers` attribute. See the [Django documentation][upload-handlers] for more details.
##### Basic usage example:
# views.py
class FileUploadView(views.APIView):
parser_classes = (FileUploadParser,)
parser_classes = [FileUploadParser]
def put(self, request, filename, format=None):
file_obj = request.data['file']
@ -112,6 +122,11 @@ If the view used with `FileUploadParser` is called with a `filename` URL keyword
# ...
return Response(status=204)
# urls.py
urlpatterns = [
# ...
re_path(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
]
---
@ -144,17 +159,16 @@ By default this will include the following keys: `view`, `request`, `args`, `kwa
The following is an example plaintext parser that will populate the `request.data` property with a string representing the body of the request.
class PlainTextParser(BaseParser):
"""
Plain text parser.
"""
media_type = 'text/plain'
def parse(self, stream, media_type=None, parser_context=None):
"""
Simply return a string representing the body of the request.
Plain text parser.
"""
return stream.read()
media_type = 'text/plain'
def parse(self, stream, media_type=None, parser_context=None):
"""
Simply return a string representing the body of the request.
"""
return stream.read()
---
@ -175,12 +189,12 @@ Install using pip.
Modify your REST framework settings.
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'DEFAULT_PARSER_CLASSES': [
'rest_framework_yaml.parsers.YAMLParser',
),
'DEFAULT_RENDERER_CLASSES': (
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework_yaml.renderers.YAMLRenderer',
),
],
}
## XML
@ -196,12 +210,12 @@ Install using pip.
Modify your REST framework settings.
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'DEFAULT_PARSER_CLASSES': [
'rest_framework_xml.parsers.XMLParser',
),
'DEFAULT_RENDERER_CLASSES': (
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework_xml.renderers.XMLRenderer',
),
],
}
## MessagePack
@ -212,11 +226,11 @@ Modify your REST framework settings.
[djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy].
[jquery-ajax]: http://api.jquery.com/jQuery.ajax/
[jquery-ajax]: https://api.jquery.com/jQuery.ajax/
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
[upload-handlers]: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#upload-handlers
[rest-framework-yaml]: http://jpadilla.github.io/django-rest-framework-yaml/
[rest-framework-xml]: http://jpadilla.github.io/django-rest-framework-xml/
[upload-handlers]: https://docs.djangoproject.com/en/stable/topics/http/file-uploads/#upload-handlers
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
[yaml]: http://www.yaml.org/
[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
[juanriaza]: https://github.com/juanriaza

View File

@ -1,4 +1,7 @@
source: permissions.py
---
source:
- permissions.py
---
# Permissions
@ -10,9 +13,9 @@ Together with [authentication] and [throttling], permissions determine whether a
Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the `request.user` and `request.auth` properties to determine if the incoming request should be permitted.
Permissions are used to grant or deny access different classes of users to different parts of the API.
Permissions are used to grant or deny access for different classes of users to different parts of the API.
The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds the `IsAuthenticated` class in REST framework.
The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the `IsAuthenticated` class in REST framework.
A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the `IsAuthenticatedOrReadOnly` class in REST framework.
@ -21,9 +24,9 @@ A slightly less strict style of permission would be to allow full access to auth
Permissions in REST framework are always defined as a list of permission classes.
Before running the main body of the view each permission in the list is checked.
If any permission check fails an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run.
If any permission check fails, an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run.
When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
When the permission checks fail, either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
* The request was successfully authenticated, but permission was denied. *&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.*
@ -44,41 +47,56 @@ This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or
For example:
def get_object(self):
obj = get_object_or_404(self.get_queryset())
obj = get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"])
self.check_object_permissions(self.request, obj)
return obj
---
**Note**: With the exception of `DjangoObjectPermissions`, the provided
permission classes in `rest_framework.permissions` **do not** implement the
methods necessary to check object permissions.
If you wish to use the provided permission classes in order to check object
permissions, **you must** subclass them and implement the
`has_object_permission()` method described in the [_Custom
permissions_](#custom-permissions) section (below).
---
#### Limitations of object level permissions
For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.
Often when you're using object level permissions you'll also want to [filter the queryset][filtering] appropriately, to ensure that users only have visibility onto instances that they are permitted to view.
Because the `get_object()` method is not called, object level permissions from the `has_object_permission()` method **are not applied** when creating objects. In order to restrict object creation you need to implement the permission check either in your Serializer class or override the `perform_create()` method of your ViewSet class.
## Setting the permission policy
The default permission policy may be set globally, using the `DEFAULT_PERMISSION_CLASSES` setting. For example.
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
)
]
}
If not specified, this setting defaults to allowing unrestricted access:
'DEFAULT_PERMISSION_CLASSES': (
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
)
]
You can also set the authentication policy on a per-view, or per-viewset basis,
using the `APIView` class based views.
using the `APIView` class-based views.
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
permission_classes = (IsAuthenticated,)
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
content = {
@ -88,14 +106,41 @@ using the `APIView` class based views.
Or, if you're using the `@api_view` decorator with function based views.
@api_view('GET')
@permission_classes((IsAuthenticated, ))
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def example_view(request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
__Note:__ when you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in the __settings.py__ file.
Provided they inherit from `rest_framework.permissions.BasePermission`, permissions can be composed using standard Python bitwise operators. For example, `IsAuthenticatedOrReadOnly` could be written:
from rest_framework.permissions import BasePermission, IsAuthenticated, SAFE_METHODS
from rest_framework.response import Response
from rest_framework.views import APIView
class ReadOnly(BasePermission):
def has_permission(self, request, view):
return request.method in SAFE_METHODS
class ExampleView(APIView):
permission_classes = [IsAuthenticated|ReadOnly]
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
__Note:__ it supports & (and), | (or) and ~ (not).
---
# API Reference
@ -120,28 +165,22 @@ 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 has a `.queryset` property set. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned.
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property or `get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned. The appropriate model is determined by checking `get_queryset().model` or `queryset.model`.
* `POST` requests require the user to have the `add` permission on the model.
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
* `DELETE` requests require the user to have the `delete` permission on the model.
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
The default behavior can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
#### Using with views that do not include a `queryset` attribute.
If you're using this permission with a view that uses an overridden `get_queryset()` method there may not be a `queryset` attribute on the view. In this case we suggest also marking the view with a sential queryset, so that this class can determine the required permissions. For example:
queryset = User.objects.none() # Required for DjangoModelPermissions
## DjangoModelPermissionsOrAnonReadOnly
Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API.
@ -158,13 +197,11 @@ As with `DjangoModelPermissions`, this permission must only be applied to views
Note that `DjangoObjectPermissions` **does not** require the `django-guardian` package, and should support other object-level backends equally well.
As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoModelPermissions` and setting the `.perms_map` property. Refer to the source code for details.
As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoObjectPermissions` and setting the `.perms_map` property. Refer to the source code for details.
---
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests, you'll want to consider also adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions.
---
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian2` package][django-rest-framework-guardian2]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.
---
@ -186,25 +223,35 @@ If you need to test if a request is a read operation or a write operation, you s
---
**Note**: The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default.
**Note**: The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default. (Function-based views will need to check object permissions explicitly, raising `PermissionDenied` on failure.)
---
## Examples
The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted.
Custom permissions will raise a `PermissionDenied` exception if the test fails. To change the error message associated with the exception, implement a `message` attribute directly on your custom permission. Otherwise the `default_detail` attribute from `PermissionDenied` will be used. Similarly, to change the code identifier associated with the exception, implement a `code` attribute directly on your custom permission - otherwise the `default_code` attribute from `PermissionDenied` will be used.
from rest_framework import permissions
class BlacklistPermission(permissions.BasePermission):
class CustomerAccessPermission(permissions.BasePermission):
message = 'Adding customers not allowed.'
def has_permission(self, request, view):
...
## Examples
The following is an example of a permission class that checks the incoming request's IP address against a blocklist, and denies the request if the IP has been blocked.
from rest_framework import permissions
class BlocklistPermission(permissions.BasePermission):
"""
Global permission check for blacklisted IPs.
Global permission check for blocked IPs.
"""
def has_permission(self, request, view):
ip_addr = request.META['REMOTE_ADDR']
blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
return not blacklisted
blocked = Blocklist.objects.filter(ip_addr=ip_addr).exists()
return not blocked
As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example:
@ -227,15 +274,39 @@ Note that the generic views will check the appropriate object level permissions,
Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the [filtering documentation][filtering] for more details.
# Overview of access restriction methods
REST framework offers three different methods to customize access restrictions on a case-by-case basis. These apply in different scenarios and have different effects and limitations.
* `queryset`/`get_queryset()`: Limits the general visibility of existing objects from the database. The queryset limits which objects will be listed and which objects can be modified or deleted. The `get_queryset()` method can apply different querysets based on the current action.
* `permission_classes`/`get_permissions()`: General permission checks based on the current action, request and targeted object. Object level permissions can only be applied to retrieve, modify and deletion actions. Permission checks for list and create will be applied to the entire object type. (In case of list: subject to restrictions in the queryset.)
* `serializer_class`/`get_serializer()`: Instance level restrictions that apply to all objects on input and output. The serializer may have access to the request context. The `get_serializer()` method can apply different serializers based on the current action.
The following table lists the access restriction methods and the level of control they offer over which actions.
| | `queryset` | `permission_classes` | `serializer_class` |
|------------------------------------|------------|----------------------|--------------------|
| Action: list | global | global | object-level* |
| Action: create | no | global | object-level |
| Action: retrieve | global | object-level | object-level |
| Action: update | global | object-level | object-level |
| Action: partial_update | global | object-level | object-level |
| Action: destroy | global | object-level | no |
| Can reference action in decision | no** | yes | no** |
| Can reference request in decision | no** | yes | yes |
\* A Serializer class should not raise PermissionDenied in a list action, or the entire list would not be returned. <br>
\** The `get_*()` methods have access to the current view and can return different Serializer or QuerySet instances based on the request or action.
---
# Third party packages
The following third party packages are also available.
## DRF Any Permissions
## DRF - Access Policy
The [DRF Any Permissions][drf-any-permissions] packages provides a different permission behavior in contrast to REST framework. Instead of all specified permissions being required, only one of the given permissions has to be true in order to get access to the view.
The [Django REST - Access Policy][drf-access-policy] package provides a way to define complex access rules in declarative policy classes that are attached to view sets or function-based views. The policies are defined in JSON in a format similar to AWS' Identity & Access Management policies.
## Composed Permissions
@ -243,18 +314,48 @@ The [Composed Permissions][composed-permissions] package provides a simple way t
## REST Condition
The [REST Condition][rest-condition] package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators.
The [REST Condition][rest-condition] package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators.
## DRY Rest Permissions
The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrieve per user.
## Django Rest Framework Roles
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.
## Django Rest Framework Role Filters
The [Django Rest Framework Role Filters][django-rest-framework-role-filters] package provides simple filtering over multiple types of roles.
## Django Rest Framework PSQ
The [Django Rest Framework PSQ][drf-psq] package is an extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
[authentication]: authentication.md
[throttling]: throttling.md
[filtering]: filtering.md
[contribauth]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#custom-permissions
[objectpermissions]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#handling-object-permissions
[contribauth]: https://docs.djangoproject.com/en/stable/topics/auth/customizing/#custom-permissions
[objectpermissions]: https://docs.djangoproject.com/en/stable/topics/auth/customizing/#handling-object-permissions
[guardian]: https://github.com/lukaszb/django-guardian
[get_objects_for_user]: http://pythonhosted.org/django-guardian/api/guardian.shortcuts.html#get-objects-for-user
[2.2-announcement]: ../topics/2.2-announcement.md
[filtering]: filtering.md
[drf-any-permissions]: https://github.com/kevin-brown/drf-any-permissions
[composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions
[rest-condition]: https://github.com/caxap/rest_condition
[dry-rest-permissions]: https://github.com/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-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

@ -1,12 +1,13 @@
source: relations.py
---
source:
- relations.py
---
# Serializer relations
> Bad programmers worry about the code.
> Good programmers worry about data structures and their relationships.
> Data structures, not algorithms, are central to programming.
>
> &mdash; [Linus Torvalds][cite]
> &mdash; [Rob Pike][cite]
Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
@ -16,7 +17,38 @@ Relational fields are used to represent model relationships. They can be applie
---
#### Inspecting automatically generated relationships.
---
**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.
@ -24,7 +56,7 @@ To do so, open the Django shell, using `python manage.py shell`, then import the
>>> from myapp.serializers import AccountSerializer
>>> serializer = AccountSerializer()
>>> print repr(serializer) # Or `print(repr(serializer))` in Python 3.x.
>>> print(repr(serializer))
AccountSerializer():
id = IntegerField(label='ID', read_only=True)
name = CharField(allow_blank=True, max_length=100, required=False)
@ -39,32 +71,32 @@ In order to explain the various types of relational fields, we'll use a couple o
artist = models.CharField(max_length=100)
class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks')
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()
class Meta:
unique_together = ('album', 'order')
unique_together = ['album', 'order']
ordering = ['order']
def __unicode__(self):
def __str__(self):
return '%d: %s' % (self.order, self.title)
## StringRelatedField
`StringRelatedField` may be used to represent the target of the relationship using its `__unicode__` method.
`StringRelatedField` may be used to represent the target of the relationship using its `__str__` method.
For example, the following serializer.
For example, the following serializer:
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.StringRelatedField(many=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
fields = ['album_name', 'artist', 'tracks']
Would serialize to the following representation.
Would serialize to the following representation:
{
'album_name': 'Things We Lost In The Fire',
@ -94,13 +126,13 @@ For example, the following serializer:
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
fields = ['album_name', 'artist', 'tracks']
Would serialize to a representation like this:
{
'album_name': 'The Roots',
'artist': 'Undun',
'album_name': 'Undun',
'artist': 'The Roots',
'tracks': [
89,
90,
@ -116,6 +148,8 @@ By default this field is read-write, although you can change this behavior using
* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`.
* `many` - If applied to a to-many relationship, you should set this argument to `True`.
* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
* `pk_field` - Set to a field to control serialization/deserialization of the primary key's value. For example, `pk_field=UUIDField(format='hex')` would serialize a UUID primary key into its compact hex representation.
## HyperlinkedRelatedField
@ -132,7 +166,7 @@ For example, the following serializer:
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
fields = ['album_name', 'artist', 'tracks']
Would serialize to a representation like this:
@ -149,6 +183,16 @@ Would serialize to a representation like this:
By default this field is read-write, although you can change this behavior using the `read_only` flag.
---
**Note**: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the `lookup_field` and `lookup_url_kwarg` arguments.
This is suitable for URLs that contain a single primary key or slug argument as part of the URL.
If you require more complex hyperlinked representation you'll need to customize the field, as described in the [custom hyperlinked fields](#custom-hyperlinked-fields) section, below.
---
**Arguments**:
* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `<modelname>-detail`. **required**.
@ -174,7 +218,7 @@ For example, the following serializer:
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
fields = ['album_name', 'artist', 'tracks']
Would serialize to a representation like this:
@ -202,14 +246,14 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e
## HyperlinkedIdentityField
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
class Meta:
model = Album
fields = ('album_name', 'artist', 'track_listing')
fields = ['album_name', 'artist', 'track_listing']
Would serialize to a representation like this:
@ -232,7 +276,9 @@ This field is always read-only.
# Nested relationships
Nested relationships can be expressed by using serializers as fields.
As opposed to previously discussed _references_ to another entity, the referred entity can instead also be embedded or _nested_
in the representation of the object that refers to it.
Such nested relationships can be expressed by using serializers as fields.
If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field.
@ -243,37 +289,92 @@ For example, the following serializer:
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ('order', 'title')
fields = ['order', 'title', 'duration']
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True, read_only=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
fields = ['album_name', 'artist', 'tracks']
Would serialize to a nested representation like this:
>>> album = Album.objects.create(album_name="The Grey Album", artist='Danger Mouse')
>>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)
<Track: Track object>
>>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)
<Track: Track object>
>>> Track.objects.create(album=album, order=3, title='Encore', duration=159)
<Track: Track object>
>>> serializer = AlbumSerializer(instance=album)
>>> serializer.data
{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement'},
{'order': 2, 'title': 'What More Can I Say'},
{'order': 3, 'title': 'Encore'},
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
{'order': 2, 'title': 'What More Can I Say', 'duration': 264},
{'order': 3, 'title': 'Encore', 'duration': 159},
...
],
}
## Writable nested serializers
By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create `create()` and/or `update()` methods in order to explicitly specify how the child relationships should be saved:
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ['order', 'title', 'duration']
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
def create(self, validated_data):
tracks_data = validated_data.pop('tracks')
album = Album.objects.create(**validated_data)
for track_data in tracks_data:
Track.objects.create(album=album, **track_data)
return album
>>> data = {
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
{'order': 2, 'title': 'What More Can I Say', 'duration': 264},
{'order': 3, 'title': 'Encore', 'duration': 159},
],
}
>>> serializer = AlbumSerializer(data=data)
>>> serializer.is_valid()
True
>>> serializer.save()
<Album: Album object>
---
# Custom relational fields
In rare cases where none of the existing relational styles fit the representation you need,
you can implement a completely custom relational field, that describes exactly how the
output representation should be generated from the model instance.
To implement a custom relational field, you should override `RelatedField`, and implement the `.to_representation(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. The `value` argument will typically be a model instance.
If you want to implement a read-write relational field, you must also implement the `.to_internal_value(self, data)` method.
If you want to implement a read-write relational field, you must also implement the [`.to_internal_value(self, data)` method][to_internal_value].
To provide a dynamic queryset based on the `context`, you can also override `.get_queryset(self)` instead of specifying `.queryset` on the class or when initializing the field.
## Example
For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration.
For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration:
import time
@ -287,9 +388,9 @@ For example, we could define a relational field to serialize a track to a custom
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
fields = ['album_name', 'artist', 'tracks']
This custom field would then serialize to the following representation.
This custom field would then serialize to the following representation:
{
'album_name': 'Sometimes I Wish We Were an Eagle',
@ -304,6 +405,65 @@ This custom field would then serialize to the following representation.
---
# Custom hyperlinked fields
In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field.
You can achieve this by overriding `HyperlinkedRelatedField`. There are two methods that may be overridden:
**get_url(self, obj, view_name, request, format)**
The `get_url` method is used to map the object instance to its URL representation.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
**get_object(self, view_name, view_args, view_kwargs)**
If you want to support a writable hyperlinked field then you'll also want to override `get_object`, in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method.
The return value of this method should the object that corresponds to the matched URL conf arguments.
May raise an `ObjectDoesNotExist` exception.
## Example
Say we have a URL for a customer object that takes two keyword arguments, like so:
/api/<organization_slug>/customers/<customer_pk>/
This cannot be represented with the default implementation, which accepts only a single lookup field.
In this case we'd need to override `HyperlinkedRelatedField` to get the behavior we want:
from rest_framework import serializers
from rest_framework.reverse import reverse
class CustomerHyperlink(serializers.HyperlinkedRelatedField):
# We define these as class attributes, so we don't need to pass them as arguments.
view_name = 'customer-detail'
queryset = Customer.objects.all()
def get_url(self, obj, view_name, request, format):
url_kwargs = {
'organization_slug': obj.organization.slug,
'customer_pk': obj.pk
}
return reverse(view_name, kwargs=url_kwargs, request=request, format=format)
def get_object(self, view_name, view_args, view_kwargs):
lookup_kwargs = {
'organization__slug': view_kwargs['organization_slug'],
'pk': view_kwargs['customer_pk']
}
return self.get_queryset().get(**lookup_kwargs)
Note that if you wanted to use this style together with the generic views then you'd also need to override `.get_object` on the view in order to get the correct lookup behavior.
Generally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation.
---
# Further notes
## The `queryset` argument
@ -316,31 +476,62 @@ This behavior is now replaced with *always* using an explicit `queryset` argumen
Doing so reduces the amount of hidden 'magic' that `ModelSerializer` provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the `ModelSerializer` shortcut, or using fully explicit `Serializer` classes.
## Customizing the HTML display
The built-in `__str__` method of the model will be used to generate string representations of the objects used to populate the `choices` property. These choices are used to populate select HTML inputs in the browsable API.
To provide customized representations for such inputs, override `display_value()` of a `RelatedField` subclass. This method will receive a model object, and should return a string suitable for representing it. For example:
class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
def display_value(self, instance):
return 'Track: %s' % (instance.title)
## Select field cutoffs
When rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with "More than 1000 items…" will be displayed.
This behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed.
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…"`
You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`.
In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the `style` keyword argument. For example:
assigned_to = serializers.SlugRelatedField(
queryset=User.objects.all(),
slug_field='username',
style={'base_template': 'input.html'}
)
## Reverse relations
Note that reverse relationships are not automatically included by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you must explicitly add it to the fields list. For example:
class AlbumSerializer(serializers.ModelSerializer):
class Meta:
fields = ('tracks', ...)
fields = ['tracks', ...]
You'll normally want to ensure that you've set an appropriate `related_name` argument on the relationship, that you can use as the field name. For example:
class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks')
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
...
If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the `fields` argument. For example:
class AlbumSerializer(serializers.ModelSerializer):
class Meta:
fields = ('track_set', ...)
fields = ['track_set', ...]
See the Django documentation on [reverse relationships][reverse-relationships] for more details.
## Generic relationships
If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want serialize the targets of the relationship.
If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to serialize the targets of the relationship.
For example, given the following model for a tag, which has a generic relationship with other arbitrary models:
@ -348,17 +539,17 @@ For example, given the following model for a tag, which has a generic relationsh
"""
Tags arbitrary model instances using a generic relation.
See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
See: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/
"""
tag_name = models.SlugField()
content_type = models.ForeignKey(ContentType)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
tagged_object = GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return self.tag
def __str__(self):
return self.tag_name
And the following two models, which may be have associated tags:
And the following two models, which may have associated tags:
class Bookmark(models.Model):
"""
@ -375,7 +566,7 @@ And the following two models, which may be have associated tags:
text = models.CharField(max_length=1000)
tags = GenericRelation(TaggedItem)
We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized.
We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized:
class TaggedObjectRelatedField(serializers.RelatedField):
"""
@ -421,38 +612,7 @@ If you explicitly specify a relational field pointing to a
``ManyToManyField`` with a through model, be sure to set ``read_only``
to ``True``.
## Advanced Hyperlinked fields
If you have very specific requirements for the style of your hyperlinked relationships you can override `HyperlinkedRelatedField`.
There are two methods you'll need to override.
#### get_url(self, obj, view_name, request, format)
This method should return the URL that corresponds to the given object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
#### get_object(self, queryset, view_name, view_args, view_kwargs)
This method should the object that corresponds to the matched URL conf arguments.
May raise an `ObjectDoesNotExist` exception.
### Example
For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this:
class CustomHyperlinkedField(serializers.HyperlinkedRelatedField):
def get_url(self, obj, view_name, request, format):
kwargs = {'account': obj.account, 'slug': obj.slug}
return reverse(view_name, kwargs=kwargs, request=request, format=format)
def get_object(self, queryset, view_name, view_args, view_kwargs):
account = view_kwargs['account']
slug = view_kwargs['slug']
return queryset.get(account=account, slug=slug)
If you wish to represent [extra fields on a through model][django-intermediary-manytomany] then you may serialize the through model as [a nested object][dealing-with-nested-objects].
---
@ -464,9 +624,20 @@ The following third party packages are also available.
The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources.
[cite]: http://lwn.net/Articles/193245/
[reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward
[routers]: http://www.django-rest-framework.org/api-guide/routers#defaultrouter
[generic-relations]: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1
[2.2-announcement]: ../topics/2.2-announcement.md
## Rest Framework Generic Relations
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

@ -1,4 +1,7 @@
source: renderers.py
---
source:
- renderers.py
---
# Renderers
@ -21,14 +24,14 @@ For more information see the documentation on [content negotiation][conneg].
The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would use `JSON` as the main media type and also include the self describing API.
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
)
]
}
You can also set the renderers used for an individual view, or viewset,
using the `APIView` class based views.
using the `APIView` class-based views.
from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer
@ -39,7 +42,7 @@ using the `APIView` class based views.
"""
A view that returns the count of active users in JSON.
"""
renderer_classes = (JSONRenderer, )
renderer_classes = [JSONRenderer]
def get(self, request, format=None):
user_count = User.objects.filter(active=True).count()
@ -49,7 +52,7 @@ using the `APIView` class based views.
Or, if you're using the `@api_view` decorator with function based views.
@api_view(['GET'])
@renderer_classes((JSONRenderer,))
@renderer_classes([JSONRenderer])
def user_count_view(request, format=None):
"""
A view that returns the count of active users in JSON.
@ -89,7 +92,7 @@ The default JSON encoding style can be altered using the `UNICODE_JSON` and `COM
**.media_type**: `application/json`
**.format**: `'.json'`
**.format**: `'json'`
**.charset**: `None`
@ -100,6 +103,16 @@ Unlike other renderers, the data passed to the `Response` does not need to be se
The TemplateHTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context.
---
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the `TemplateHTMLRenderer` to render it. For example:
```
response.data = {'results': response.data}
```
---
The template name is determined by (in order of preference):
1. An explicit `template_name` argument passed to the response.
@ -113,7 +126,7 @@ An example of a view that uses `TemplateHTMLRenderer`:
A view that returns a templated HTML representation of a given user.
"""
queryset = User.objects.all()
renderer_classes = (TemplateHTMLRenderer,)
renderer_classes = [TemplateHTMLRenderer]
def get(self, request, *args, **kwargs):
self.object = self.get_object()
@ -123,9 +136,11 @@ You can use `TemplateHTMLRenderer` either to return regular HTML pages using RES
If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers.
See the [_HTML & Forms_ Topic Page][html-and-forms] for further examples of `TemplateHTMLRenderer` usage.
**.media_type**: `text/html`
**.format**: `'.html'`
**.format**: `'html'`
**.charset**: `utf-8`
@ -137,8 +152,8 @@ A simple renderer that simply returns pre-rendered HTML. Unlike other renderers
An example of a view that uses `StaticHTMLRenderer`:
@api_view(('GET',))
@renderer_classes((StaticHTMLRenderer,))
@api_view(['GET'])
@renderer_classes([StaticHTMLRenderer])
def simple_html_view(request):
data = '<html><body><h1>Hello, world</h1></body></html>'
return Response(data)
@ -147,33 +162,23 @@ You can use `StaticHTMLRenderer` either to return regular HTML pages using REST
**.media_type**: `text/html`
**.format**: `'.html'`
**.format**: `'html'`
**.charset**: `utf-8`
See also: `TemplateHTMLRenderer`
## HTMLFormRenderer
Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing `<form>` tags or an submit actions, as you'll probably need those to include the desired method and URL. Also note that the `HTMLFormRenderer` does not yet support including field error messages.
Note that the template used by the `HTMLFormRenderer` class, and the context submitted to it **may be subject to change**. If you need to use this renderer class it is advised that you either make a local copy of the class and templates, or follow the release note on REST framework upgrades closely.
**.media_type**: `text/html`
**.format**: `'.form'`
**.charset**: `utf-8`
**.template**: `'rest_framework/form.html'`
## BrowsableAPIRenderer
Renders data into HTML for the Browsable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.
Renders data into HTML for the Browsable API:
![The BrowsableAPIRenderer](../img/quickstart.png)
This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.
**.media_type**: `text/html`
**.format**: `'.api'`
**.format**: `'api'`
**.charset**: `utf-8`
@ -181,19 +186,70 @@ Renders data into HTML for the Browsable API. This renderer will determine whic
#### Customizing BrowsableAPIRenderer
By default the response content will be rendered with the highest priority renderer apart from `BrowseableAPIRenderer`. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the `get_default_renderer()` method. For example:
By default the response content will be rendered with the highest priority renderer apart from `BrowsableAPIRenderer`. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the `get_default_renderer()` method. For example:
class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
def get_default_renderer(self, view):
return JSONRenderer()
## AdminRenderer
Renders data into HTML for an admin-like display:
![The AdminRender view](../img/admin.png)
This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data.
Note that views that have nested or list serializers for their input won't work well with the `AdminRenderer`, as the HTML forms are unable to properly support them.
**Note**: The `AdminRenderer` is only able to include links to detail pages when a properly configured `URL_FIELD_NAME` (`url` by default) attribute is present in the data. For `HyperlinkedModelSerializer` this will be the case, but for `ModelSerializer` or plain `Serializer` classes you'll need to make sure to include the field explicitly. For example here we use models `get_absolute_url` method:
class AccountSerializer(serializers.ModelSerializer):
url = serializers.CharField(source='get_absolute_url', read_only=True)
class Meta:
model = Account
**.media_type**: `text/html`
**.format**: `'admin'`
**.charset**: `utf-8`
**.template**: `'rest_framework/admin.html'`
## HTMLFormRenderer
Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing `<form>` tags, a hidden CSRF input or any submit buttons.
This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the `render_form` template tag.
{% load rest_framework %}
<form action="/submit-report/" method="post">
{% csrf_token %}
{% render_form serializer %}
<input type="submit" value="Save" />
</form>
For more information see the [HTML & Forms][html-and-forms] documentation.
**.media_type**: `text/html`
**.format**: `'form'`
**.charset**: `utf-8`
**.template**: `'rest_framework/horizontal/form.html'`
## MultiPartRenderer
This renderer is used for rendering HTML multipart form data. **It is not suitable as a response renderer**, but is instead used for creating test requests, using REST framework's [test client and test request factory][testing].
**.media_type**: `multipart/form-data; boundary=BoUnDaRyStRiNg`
**.format**: `'.multipart'`
**.format**: `'multipart'`
**.charset**: `utf-8`
@ -201,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.
@ -211,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.
@ -227,7 +283,7 @@ By default this will include the following keys: `view`, `request`, `response`,
The following is an example plaintext renderer that will return a response with the `data` parameter as the content of the response.
from django.utils.encoding import smart_unicode
from django.utils.encoding import smart_str
from rest_framework import renderers
@ -235,8 +291,8 @@ The following is an example plaintext renderer that will return a response with
media_type = 'text/plain'
format = 'txt'
def render(self, data, media_type=None, renderer_context=None):
return data.encode(self.charset)
def render(self, data, accepted_media_type=None, renderer_context=None):
return smart_str(data, encoding=self.charset)
## Setting the character set
@ -247,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.
@ -262,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
---
@ -276,14 +332,14 @@ You can do some pretty flexible things using REST framework's renderers. Some e
* Specify multiple types of HTML representation for API clients to use.
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
## Varying behaviour by media type
## Varying behavior by media type
In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
For example:
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
@api_view(['GET'])
@renderer_classes([TemplateHTMLRenderer, JSONRenderer])
def list_users(request):
"""
A view that can return JSON or HTML representations
@ -355,12 +411,12 @@ Install using pip.
Modify your REST framework settings.
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'DEFAULT_PARSER_CLASSES': [
'rest_framework_yaml.parsers.YAMLParser',
),
'DEFAULT_RENDERER_CLASSES': (
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework_yaml.renderers.YAMLRenderer',
),
],
}
## XML
@ -376,12 +432,12 @@ Install using pip.
Modify your REST framework settings.
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'DEFAULT_PARSER_CLASSES': [
'rest_framework_xml.parsers.XMLParser',
),
'DEFAULT_RENDERER_CLASSES': (
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework_xml.renderers.XMLRenderer',
),
],
}
## JSONP
@ -405,22 +461,59 @@ Install using pip.
Modify your REST framework settings.
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'DEFAULT_RENDERER_CLASSES': [
'rest_framework_jsonp.renderers.JSONPRenderer',
),
],
}
## MessagePack
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
## 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-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-excel
Modify your REST framework settings.
REST_FRAMEWORK = {
...
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
'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_excel.mixins import XLSXFileMixin
from drf_excel.renderers import XLSXRenderer
from .models import MyExampleModel
from .serializers import MyExampleSerializer
class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
queryset = MyExampleModel.objects.all()
serializer_class = MyExampleSerializer
renderer_classes = [XLSXRenderer]
filename = 'my_export.xlsx'
## CSV
Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework.
## UltraJSON
[UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Jacob Haslehurst][hzy] maintains the [drf-ujson-renderer][drf-ujson-renderer] package which implements JSON rendering using the UJSON package.
[UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Adam Mertz][Amertz08] maintains [drf_ujson2][drf_ujson2], a fork of the now unmaintained [drf-ujson-renderer][drf-ujson-renderer], which implements JSON rendering using the UJSON package.
## CamelCase JSON
@ -430,37 +523,48 @@ Comma-separated values are a plain-text tabular data format, that can be easily
[Django REST Pandas] provides a serializer and renderers that support additional data processing and output via the [Pandas] DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both `.xls` and `.xlsx`), and a number of [other formats]. It is maintained by [S. Andrew Sheppard][sheppard] as part of the [wq Project][wq].
## LaTeX
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
[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/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
[testing]: testing.md
[HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas
[quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
[application/vnd.github+json]: http://developer.github.com/v3/media/
[quote]: https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
[application/vnd.github+json]: https://developer.github.com/v3/media/
[application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/
[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
[rest-framework-jsonp]: http://jpadilla.github.io/django-rest-framework-jsonp/
[cors]: http://www.w3.org/TR/cors/
[cors-docs]: http://www.django-rest-framework.org/topics/ajax-csrf-cors/
[jsonp-security]: http://stackoverflow.com/questions/613962/is-jsonp-safe-to-use
[rest-framework-yaml]: http://jpadilla.github.io/django-rest-framework-yaml/
[rest-framework-xml]: http://jpadilla.github.io/django-rest-framework-xml/
[messagepack]: http://msgpack.org/
[django-error-views]: https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views
[rest-framework-jsonp]: https://jpadilla.github.io/django-rest-framework-jsonp/
[cors]: https://www.w3.org/TR/cors/
[cors-docs]: https://www.django-rest-framework.org/topics/ajax-csrf-cors/
[jsonp-security]: https://stackoverflow.com/questions/613962/is-jsonp-safe-to-use
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
[messagepack]: https://msgpack.org/
[juanriaza]: https://github.com/juanriaza
[mjumbewu]: https://github.com/mjumbewu
[flipperpa]: https://github.com/flipperpa
[wharton]: https://github.com/wharton
[drf-excel]: https://github.com/wharton/drf-excel
[vbabiy]: https://github.com/vbabiy
[rest-framework-yaml]: http://jpadilla.github.io/django-rest-framework-yaml/
[rest-framework-xml]: http://jpadilla.github.io/django-rest-framework-xml/
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
[yaml]: http://www.yaml.org/
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
[ultrajson]: https://github.com/esnme/ultrajson
[hzy]: https://github.com/hzy
[Amertz08]: https://github.com/Amertz08
[drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer
[drf_ujson2]: https://github.com/Amertz08/drf_ujson2
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
[Django REST Pandas]: https://github.com/wq/django-rest-pandas
[Pandas]: http://pandas.pydata.org/
[Pandas]: https://pandas.pydata.org/
[other formats]: https://github.com/wq/django-rest-pandas#supported-formats
[sheppard]: https://github.com/sheppard
[wq]: https://github.com/wq
[mypebble]: https://github.com/mypebble
[Rest Framework Latex]: https://github.com/mypebble/rest-framework-latex

View File

@ -1,4 +1,7 @@
source: request.py
---
source:
- request.py
---
# Requests
@ -20,7 +23,7 @@ REST framework's Request objects provide flexible request parsing that allows yo
* It includes all parsed content, including *file and non-file* inputs.
* It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests.
* It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.
* It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming [JSON data] similarly to how you handle incoming [form data].
For more details see the [parsers documentation].
@ -30,14 +33,6 @@ For more details see the [parsers documentation].
For clarity inside your code, we recommend using `request.query_params` instead of the Django's standard `request.GET`. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just `GET` requests.
## .DATA and .FILES
The old-style version 2.x `request.DATA` and `request.FILES` attributes are still available, but are now pending deprecation in favor of the unified `request.data` attribute.
## .QUERY_PARAMS
The old-style version 2.x `request.QUERY_PARAMS` attribute is still available, but is now pending deprecation in favor of the more pythonic `request.query_params`.
## .parsers
The `APIView` class or `@api_view` decorator will ensure that this property is automatically set to a list of `Parser` instances, based on the `parser_classes` set on the view or based on the `DEFAULT_PARSER_CLASSES` setting.
@ -54,11 +49,11 @@ If a client sends a request with a content-type that cannot be parsed then a `Un
# Content negotiation
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialisation schemes for different media types.
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behavior such as selecting a different serialization schemes for different media types.
## .accepted_renderer
The renderer instance what was selected by the content negotiation stage.
The renderer instance that was selected by the content negotiation stage.
## .accepted_media_type
@ -98,6 +93,10 @@ You won't typically need to access this property.
---
**Note:** You may see a `WrappedAttributeError` raised when calling the `.user` or `.auth` properties. These errors originate from an authenticator as a standard `AttributeError`, however it's necessary that they be re-raised as a different exception type in order to prevent them from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from the authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. The authenticator will need to be fixed.
---
# Browser enhancements
REST framework supports a few browser enhancements such as browser-based `PUT`, `PATCH` and `DELETE` forms.
@ -126,10 +125,6 @@ For more information see the [browser enhancements documentation].
You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior.
If you do need to access the raw content directly, you should use the `.stream` property in preference to using `request.content`, as it provides transparent support for browser-based non-form content.
For more information see the [browser enhancements documentation].
---
# Standard HttpRequest attributes
@ -141,5 +136,7 @@ Note that due to implementation reasons the `Request` class does not inherit fro
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
[parsers documentation]: parsers.md
[JSON data]: parsers.md#jsonparser
[form data]: parsers.md#formparser
[authentication documentation]: authentication.md
[browser enhancements documentation]: ../topics/browser-enhancements.md

View File

@ -1,4 +1,7 @@
source: response.py
---
source:
- response.py
---
# Responses
@ -42,7 +45,7 @@ Arguments:
## .data
The unrendered content of a `Request` object.
The unrendered, serialized data of the response.
## .status_code
@ -91,5 +94,5 @@ As with any other `TemplateResponse`, this method is called to render the serial
You won't typically need to call `.render()` yourself, as it's handled by Django's standard response cycle.
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/
[cite]: https://docs.djangoproject.com/en/stable/ref/template-response/
[statuscodes]: status-codes.md

View File

@ -1,4 +1,7 @@
source: reverse.py
---
source:
- reverse.py
---
# Returning URLs
@ -23,33 +26,33 @@ There's no requirement for you to use them, but if you do then the self-describi
**Signature:** `reverse(viewname, *args, **kwargs)`
Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port.
Has the same behavior as [`django.urls.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port.
You should **include the request as a keyword argument** to the function, for example:
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
**Signature:** `reverse_lazy(viewname, *args, **kwargs)`
Has the same behavior as [`django.core.urlresolvers.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port.
Has the same behavior as [`django.urls.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port.
As with the `reverse` function, you should **include the request as a keyword argument** to the function, for example:
api_root = reverse_lazy('api-root', request=request)
[cite]: http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5
[reverse]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
[reverse-lazy]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
[cite]: https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5
[reverse]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse
[reverse-lazy]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse-lazy

View File

@ -1,4 +1,7 @@
source: routers.py
---
source:
- routers.py
---
# Routers
@ -28,7 +31,7 @@ There are two mandatory arguments to the `register()` method:
Optionally, you may also specify an additional argument:
* `base_name` - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the `queryset` attribute of the viewset, if it has one. Note that if the viewset does not include a `queryset` attribute then you must set `base_name` when registering the viewset.
* `basename` - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the `queryset` attribute of the viewset, if it has one. Note that if the viewset does not include a `queryset` attribute then you must set `basename` when registering the viewset.
The example above would generate the following URL patterns:
@ -39,13 +42,13 @@ The example above would generate the following URL patterns:
---
**Note**: The `base_name` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part.
**Note**: The `basename` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part.
Typically you won't *need* to specify the `base_name` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this:
Typically you won't *need* to specify the `basename` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this:
'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
This means you'll need to explicitly set the `base_name` argument when registering the viewset, as it could not be automatically determined from the model name.
This means you'll need to explicitly set the `basename` argument when registering the viewset, as it could not be automatically determined from the model name.
---
@ -53,104 +56,135 @@ This means you'll need to explicitly set the `base_name` argument when registeri
The `.urls` attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs.
For example, you can append `router.urls` to a list of existing views
For example, you can append `router.urls` to a list of existing views...
router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
path('forgot-password/', ForgotPasswordFormView.as_view()),
]
urlpatterns += router.urls
Alternatively you can use Django's `include` function, like so
Alternatively you can use Django's `include` function, like so...
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^', include(router.urls)),
path('forgot-password', ForgotPasswordFormView.as_view()),
path('', include(router.urls)),
]
Router URL patterns can also be namespaces.
You may use `include` with an application namespace:
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^api/', include(router.urls, namespace='api')),
path('forgot-password/', ForgotPasswordFormView.as_view()),
path('api/', include((router.urls, 'app_name'))),
]
If using namespacing with hyperlinked serializers you'll also need to ensure that any `view_name` parameters on the serializers correctly reflect the namespace. In the example above you'd need to include a parameter such as `view_name='api:user-detail'` for serializer fields hyperlinked to the user detail view.
Or both an application and instance namespace:
### Extra link and actions
urlpatterns = [
path('forgot-password/', ForgotPasswordFormView.as_view()),
path('api/', include((router.urls, 'app_name'), namespace='instance_name')),
]
Any methods on the viewset decorated with `@detail_route` or `@list_route` will also be routed.
For example, given a method like this on the `UserViewSet` class:
See Django's [URL namespaces docs][url-namespace-docs] and the [`include` API reference][include-api-reference] for more details.
---
**Note**: If using namespacing with hyperlinked serializers you'll also need to ensure that any `view_name` parameters
on the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as
`view_name='app_name:user-detail'` for serializer fields hyperlinked to the user detail view.
The automatic `view_name` generation uses a pattern like `%(model_name)-detail`. Unless your models names actually clash
you may be better off **not** namespacing your Django REST Framework views when using hyperlinked serializers.
---
### Routing for extra actions
A viewset may [mark extra actions for routing][route-decorators] by decorating a method with the `@action` decorator. These extra actions will be included in the generated routes. For example, given the `set_password` method on the `UserViewSet` class:
from myapp.permissions import IsAdminOrIsSelf
from rest_framework.decorators import detail_route
from rest_framework.decorators import action
class UserViewSet(ModelViewSet):
...
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])
@action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
...
The following URL pattern would additionally be generated:
The following route would be generated:
* URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'`
* URL pattern: `^users/{pk}/set_password/$`
* URL name: `'user-set-password'`
If you do not want to use the default URL generated for your custom action, you can instead use the url_path parameter to customize it.
By default, the URL pattern is based on the method name, and the URL name is the combination of the `ViewSet.basename` and the hyphenated method name.
If you don't want to use the defaults for either of these values, you can instead provide the `url_path` and `url_name` arguments to the `@action` decorator.
For example, if you want to change the URL for our custom action to `^users/{pk}/change-password/$`, you could write:
from myapp.permissions import IsAdminOrIsSelf
from rest_framework.decorators import detail_route
from rest_framework.decorators import action
class UserViewSet(ModelViewSet):
...
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf], url_path='change-password')
@action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf],
url_path='change-password', url_name='change_password')
def set_password(self, request, pk=None):
...
The above example would now generate the following URL pattern:
* URL pattern: `^users/{pk}/change-password/$` Name: `'user-change-password'`
* URL path: `^users/{pk}/change-password/$`
* URL name: `'user-change_password'`
For more information see the viewset documentation on [marking extra actions for routing][route-decorators].
### 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
This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@detail_route` or `@list_route` decorators.
This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@action` decorator.
<table border=1>
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
<tr><td rowspan=2>{prefix}/</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
<tr><td>POST</td><td>create</td></tr>
<tr><td>{prefix}/{methodname}/</td><td>GET, or as specified by `methods` argument</td><td>`@list_route` decorated method</td><td>{basename}-{methodname}</td></tr>
<tr><td>{prefix}/{url_path}/</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=False)` decorated method</td><td>{basename}-{url_name}</td></tr>
<tr><td rowspan=4>{prefix}/{lookup}/</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
<tr><td>PUT</td><td>update</td></tr>
<tr><td>PATCH</td><td>partial_update</td></tr>
<tr><td>DELETE</td><td>destroy</td></tr>
<tr><td>{prefix}/{lookup}/{methodname}/</td><td>GET, or as specified by `methods` argument</td><td>`@detail_route` decorated method</td><td>{basename}-{methodname}</td></tr>
<tr><td>{prefix}/{lookup}/{url_path}/</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=True)` decorated method</td><td>{basename}-{url_name}</td></tr>
</table>
By default the URLs created by `SimpleRouter` are appended with a trailing slash.
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.
@ -160,12 +194,12 @@ This router is similar to `SimpleRouter` as above, but additionally includes a d
<tr><td>[.format]</td><td>GET</td><td>automatically generated root view</td><td>api-root</td></tr></tr>
<tr><td rowspan=2>{prefix}/[.format]</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
<tr><td>POST</td><td>create</td></tr>
<tr><td>{prefix}/{methodname}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@list_route` decorated method</td><td>{basename}-{methodname}</td></tr>
<tr><td>{prefix}/{url_path}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=False)` decorated method</td><td>{basename}-{url_name}</td></tr>
<tr><td rowspan=4>{prefix}/{lookup}/[.format]</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
<tr><td>PUT</td><td>update</td></tr>
<tr><td>PATCH</td><td>partial_update</td></tr>
<tr><td>DELETE</td><td>destroy</td></tr>
<tr><td>{prefix}/{lookup}/{methodname}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@detail_route` decorated method</td><td>{basename}-{methodname}</td></tr>
<tr><td>{prefix}/{lookup}/{url_path}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=True)` decorated method</td><td>{basename}-{url_name}</td></tr>
</table>
As with `SimpleRouter` the trailing slashes on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router.
@ -174,7 +208,7 @@ As with `SimpleRouter` the trailing slashes on the URL routes can be removed by
# Custom Routers
Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the your URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.
Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.
The simplest way to implement a custom router is to subclass one of the existing router classes. The `.routes` attribute is used to template the URL patterns that will be mapped to each viewset. The `.routes` attribute is a list of `Route` named tuples.
@ -192,18 +226,18 @@ The arguments to the `Route` named tuple are:
* `{basename}` - The base to use for the URL names that are created.
**initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the `suffix` argument is reserved for identifying the viewset type, used when generating the view name and breadcrumb links.
**initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the `detail`, `basename`, and `suffix` arguments are reserved for viewset introspection and are also used by the browsable API to generate the view name and breadcrumb links.
## Customizing dynamic routes
You can also customize how the `@list_route` and `@detail_route` decorators are routed.
To route either or both of these decorators, include a `DynamicListRoute` and/or `DynamicDetailRoute` named tuple in the `.routes` list.
You can also customize how the `@action` decorator is routed. Include the `DynamicRoute` named tuple in the `.routes` list, setting the `detail` argument as appropriate for the list-based and detail-based routes. In addition to `detail`, the arguments to `DynamicRoute` are:
The arguments to `DynamicListRoute` and `DynamicDetailRoute` are:
**url**: A string representing the URL to be routed. May include the same format strings as `Route`, and additionally accepts the `{url_path}` format string.
**url**: A string representing the URL to be routed. May include the same format strings as `Route`, and additionally accepts the `{methodname}` and `{methodnamehyphen}` format strings.
**name**: The name of the URL as used in `reverse` calls. May include the following format strings:
**name**: The name of the URL as used in `reverse` calls. May include the following format strings: `{basename}`, `{methodname}` and `{methodnamehyphen}`.
* `{basename}` - The base to use for the URL names that are created.
* `{url_name}` - The `url_name` provided to the `@action`.
**initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view.
@ -211,7 +245,7 @@ The arguments to `DynamicListRoute` and `DynamicDetailRoute` are:
The following example will only route to the `list` and `retrieve` actions, and does not use the trailing slash convention.
from rest_framework.routers import Route, DynamicDetailRoute, SimpleRouter
from rest_framework.routers import Route, DynamicRoute, SimpleRouter
class CustomReadOnlyRouter(SimpleRouter):
"""
@ -219,22 +253,25 @@ The following example will only route to the `list` and `retrieve` actions, and
"""
routes = [
Route(
url=r'^{prefix}$',
mapping={'get': 'list'},
name='{basename}-list',
initkwargs={'suffix': 'List'}
url=r'^{prefix}$',
mapping={'get': 'list'},
name='{basename}-list',
detail=False,
initkwargs={'suffix': 'List'}
),
Route(
url=r'^{prefix}/{lookup}$',
mapping={'get': 'retrieve'},
name='{basename}-detail',
initkwargs={'suffix': 'Detail'}
url=r'^{prefix}/{lookup}$',
mapping={'get': 'retrieve'},
name='{basename}-detail',
detail=True,
initkwargs={'suffix': 'Detail'}
),
DynamicDetailRoute(
url=r'^{prefix}/{lookup}/{methodnamehyphen}$',
name='{basename}-{methodnamehyphen}',
initkwargs={}
)
DynamicRoute(
url=r'^{prefix}/{lookup}/{url_path}$',
name='{basename}-{url_name}',
detail=True,
initkwargs={}
)
]
Let's take a look at the routes our `CustomReadOnlyRouter` would generate for a simple viewset.
@ -249,8 +286,8 @@ Let's take a look at the routes our `CustomReadOnlyRouter` would generate for a
serializer_class = UserSerializer
lookup_field = 'username'
@detail_route()
def group_names(self, request):
@action(detail=True)
def group_names(self, request, pk=None):
"""
Returns a list of all the group names that the given
user belongs to.
@ -263,7 +300,7 @@ Let's take a look at the routes our `CustomReadOnlyRouter` would generate for a
router = CustomReadOnlyRouter()
router.register('users', UserViewSet)
urlpatterns = router.urls
urlpatterns = router.urls
The following mappings would be generated...
@ -271,7 +308,7 @@ The following mappings would be generated...
<tr><th>URL</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
<tr><td>/users</td><td>GET</td><td>list</td><td>user-list</td></tr>
<tr><td>/users/{username}</td><td>GET</td><td>retrieve</td><td>user-detail</td></tr>
<tr><td>/users/{username}/group-names</td><td>GET</td><td>group_names</td><td>user-group-names</td></tr>
<tr><td>/users/{username}/group_names</td><td>GET</td><td>group_names</td><td>user-group-names</td></tr>
</table>
For another example of setting the `.routes` attribute, see the source code for the `SimpleRouter` class.
@ -280,7 +317,7 @@ For another example of setting the `.routes` attribute, see the source code for
If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute.
You may also want to override the `get_default_base_name(self, viewset)` method, or else always explicitly set the `base_name` argument when registering your viewsets with the router.
You may also want to override the `get_default_basename(self, viewset)` method, or else always explicitly set the `basename` argument when registering your viewsets with the router.
# Third Party Packages
@ -303,13 +340,16 @@ The [wq.db package][wq.db] provides an advanced [ModelRouter][wq.db-router] clas
The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions-routers] for creating [nested viewsets][drf-extensions-nested-viewsets], [collection level controllers][drf-extensions-collection-level-controllers] with [customizable endpoint names][drf-extensions-customizable-endpoint-names].
[cite]: http://guides.rubyonrails.org/routing.html
[cite]: https://guides.rubyonrails.org/routing.html
[route-decorators]: viewsets.md#marking-extra-actions-for-routing
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
[wq.db]: http://wq.io/wq.db
[wq.db-router]: http://wq.io/docs/router
[drf-extensions]: http://chibisov.github.io/drf-extensions/docs/
[drf-extensions-routers]: http://chibisov.github.io/drf-extensions/docs/#routers
[drf-extensions-nested-viewsets]: http://chibisov.github.io/drf-extensions/docs/#nested-routes
[drf-extensions-collection-level-controllers]: http://chibisov.github.io/drf-extensions/docs/#collection-level-controllers
[drf-extensions-customizable-endpoint-names]: http://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name
[wq.db]: https://wq.io/wq.db
[wq.db-router]: https://wq.io/docs/router
[drf-extensions]: https://chibisov.github.io/drf-extensions/docs/
[drf-extensions-routers]: https://chibisov.github.io/drf-extensions/docs/#routers
[drf-extensions-nested-viewsets]: https://chibisov.github.io/drf-extensions/docs/#nested-routes
[drf-extensions-collection-level-controllers]: https://chibisov.github.io/drf-extensions/docs/#collection-level-controllers
[drf-extensions-customizable-endpoint-names]: https://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name
[url-namespace-docs]: https://docs.djangoproject.com/en/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

465
docs/api-guide/schemas.md Normal file
View File

@ -0,0 +1,465 @@
---
source:
- schemas
---
# Schema
> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.
>
> &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.
Django REST Framework provides support for automatic generation of
[OpenAPI][openapi] schemas.
## Overview
Schema generation has several moving parts. It's worth having an overview:
* `SchemaGenerator` is a top-level class that is responsible for walking your
configured URL patterns, finding `APIView` subclasses, enquiring for their
schema representation, and compiling the final schema object.
* `AutoSchema` encapsulates all the details necessary for per-view schema
introspection. Is attached to each view via the `schema` attribute. You
subclass `AutoSchema` in order to customize your schema.
* The `generateschema` management command allows you to generate a static schema
offline.
* Alternatively, you can route `SchemaView` to dynamically generate and serve
your schema.
* `settings.DEFAULT_SCHEMA_CLASS` allows you to specify an `AutoSchema`
subclass to serve as your project's default.
The following sections explain more.
## Generating an OpenAPI Schema
### Install dependencies
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
If your schema is static, you can use the `generateschema` management command:
```bash
./manage.py generateschema --file openapi-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.
### Generating a dynamic schema with `SchemaView`
If you require a dynamic schema, because foreign key choices depend on database
values, for example, you can route a `SchemaView` that will generate and serve
your schema on demand.
To route a `SchemaView`, use the `get_schema_view()` helper.
In `urls.py`:
```python
from rest_framework.schemas import get_schema_view
urlpatterns = [
# ...
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
# * `title` and `description` parameters are passed to `SchemaGenerator`.
# * Provide view name for use with `reverse()`.
path(
"openapi",
get_schema_view(
title="Your Project", description="API for all things …", version="1.0.0"
),
name="openapi-schema",
),
# ...
]
```
#### `get_schema_view()`
The `get_schema_view()` helper takes the following keyword arguments:
* `title`: May be used to provide a descriptive title for the schema definition.
* `description`: Longer descriptive text.
* `version`: The version of the API.
* `url`: May be used to pass a canonical base URL for the schema.
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/'
)
* `urlconf`: A string representing the import path to the URL conf that you want
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'
)
* `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,
)
* `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`.
* `authentication_classes`: May be used to specify the list of authentication
classes that will apply to the schema endpoint. Defaults to
`settings.DEFAULT_AUTHENTICATION_CLASSES`
* `permission_classes`: May be used to specify the list of permission classes
that will apply to the schema endpoint. Defaults to
`settings.DEFAULT_PERMISSION_CLASSES`.
* `renderer_classes`: May be used to pass the set of renderer classes that can
be used to render the API root endpoint.
## SchemaGenerator
**Schema-level customization**
```python
from rest_framework.schemas.openapi import SchemaGenerator
```
`SchemaGenerator` is a class that walks a list of routed URL patterns, requests
the schema for each view and collates the resulting OpenAPI schema.
Typically you won't need to instantiate `SchemaGenerator` yourself, but you can
do so like so:
generator = SchemaGenerator(title='Stock Prices API')
Arguments:
* `title` **required**: The name of the API.
* `description`: Longer descriptive text.
* `version`: The version of the API. Defaults to `0.1.0`.
* `url`: The root URL of the API schema. This option is not required unless the schema is included under path prefix.
* `patterns`: A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.
* `urlconf`: A URL conf module name to use when generating the schema. Defaults to `settings.ROOT_URLCONF`.
In order to customize the top-level schema, subclass
`rest_framework.schemas.openapi.SchemaGenerator` and provide your subclass
as an argument to the `generateschema` command or `get_schema_view()` helper
function.
### get_schema(self, request=None, public=False)
Returns a dictionary that represents the OpenAPI schema:
generator = SchemaGenerator(title='Stock Prices API')
schema = generator.get_schema()
The `request` argument is optional, and may be used if you want to apply
per-user permissions to the resulting schema generation.
This is a good point to override if you want to customize the generated
dictionary For example you might wish to add terms of service to the [top-level
`info` object][info-object]:
```
class TOSSchemaGenerator(SchemaGenerator):
def get_schema(self, *args, **kwargs):
schema = super().get_schema(*args, **kwargs)
schema["info"]["termsOfService"] = "https://example.com/tos.html"
return schema
```
## AutoSchema
**Per-View Customization**
```python
from rest_framework.schemas.openapi import AutoSchema
```
By default, view introspection is performed by an `AutoSchema` instance
accessible via the `schema` attribute on `APIView`.
auto_schema = some_view.schema
`AutoSchema` provides the OpenAPI elements needed for each view, request method
and path:
* A list of [OpenAPI components][openapi-components]. In DRF terms these are
mappings of serializers that describe request and response bodies.
* The appropriate [OpenAPI operation object][openapi-operation] that describes
the endpoint, including path and query parameters for pagination, filtering,
and so on.
```python
components = auto_schema.get_components(...)
operation = auto_schema.get_operation(...)
```
In compiling the schema, `SchemaGenerator` calls `get_components()` and
`get_operation()` for each view, allowed method, and path.
----
**Note**: The automatic introspection of components, and many operation
parameters relies on the relevant attributes and methods of
`GenericAPIView`: `get_serializer()`, `pagination_class`, `filter_backends`,
etc. For basic `APIView` subclasses, default introspection is essentially limited to
the URL kwarg path parameters for this reason.
----
`AutoSchema` encapsulates the view introspection needed for schema generation.
Because of this all the schema generation logic is kept in a single place,
rather than being spread around the already extensive view, serializer and
field APIs.
Keeping with this pattern, try not to let schema logic leak into your own
views, serializers, or fields when customizing the schema generation. You might
be tempted to do something like this:
```python
class CustomSchema(AutoSchema):
"""
AutoSchema subclass using schema_extra_info on the view.
"""
...
class CustomView(APIView):
schema = CustomSchema()
schema_extra_info = ... # some extra info
```
Here, the `AutoSchema` subclass goes looking for `schema_extra_info` on the
view. This is _OK_ (it doesn't actually hurt) but it means you'll end up with
your schema logic spread out in a number of different places.
Instead try to subclass `AutoSchema` such that the `extra_info` doesn't leak
out into the view:
```python
class BaseSchema(AutoSchema):
"""
AutoSchema subclass that knows how to use extra_info.
"""
...
class CustomSchema(BaseSchema):
extra_info = ... # some extra info
class CustomView(APIView):
schema = CustomSchema()
```
This style is slightly more verbose but maintains the encapsulation of the
schema related code. It's more _cohesive_ in the _parlance_. It'll keep the
rest of your API code more tidy.
If an option applies to many view classes, rather than creating a specific
subclass per-view, you may find it more convenient to allow specifying the
option as an `__init__()` kwarg to your base `AutoSchema` subclass:
```python
class CustomSchema(BaseSchema):
def __init__(self, **kwargs):
# store extra_info for later
self.extra_info = kwargs.pop("extra_info")
super().__init__(**kwargs)
class CustomView(APIView):
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
the more commonly needed options do.
### `AutoSchema` methods
#### `get_components()`
Generates the OpenAPI components that describe request and response bodies,
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
`get_components()` to return multiple pairs if your view uses multiple
serializers.
#### `get_component_name()`
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.
Most serializers should conform to the standard OpenAPI `object` type, but you may
wish to override `map_serializer()` in order to customize this or other
serializer-level fields.
#### `map_field()`
Maps individual serializer fields to their schema representation. The base implementation
will handle the default fields that Django REST Framework provides.
For `SerializerMethodField` instances, for which the schema is unknown, or custom field subclasses you should override `map_field()` to generate the correct schema:
```python
class CustomSchema(AutoSchema):
"""Extension of ``AutoSchema`` to add support for custom field schemas."""
def map_field(self, field):
# Handle SerializerMethodFields or custom fields here...
# ...
return super().map_field(field)
```
Authors of third-party packages should aim to provide an `AutoSchema` subclass,
and a mixin, overriding `map_field()` so that users can easily generate schemas
for their custom fields.
#### `get_tags()`
OpenAPI groups operations by tags. By default tags taken from the first path
segment of the routed URL. For example, a URL like `/users/{id}/` will generate
the tag `users`.
You can pass an `__init__()` kwarg to manually specify tags (see below), or
override `get_tags()` to provide custom logic.
#### `get_operation()`
Returns the [OpenAPI operation object][openapi-operation] that describes the
endpoint, including path and query parameters for pagination, filtering, and so
on.
Together with `get_components()`, this is the main entry point to the view
introspection.
#### `get_operation_id()`
There must be a unique [operationid](openapi-operationid) for each operation.
By default the `operationId` is deduced from the model name, serializer name or
view name. The operationId looks like "listItems", "retrieveItem",
"updateItem", etc. The `operationId` is camelCase by convention.
#### `get_operation_id_base()`
If you have several views with the same model name, you may see duplicate
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
common customizations, if the default generated values are not appropriate.
The available kwargs are:
* `tags`: Specify a list of tags.
* `component_name`: Specify the component name.
* `operation_id_base`: Specify the resource-name part of operation IDs.
You pass the kwargs when declaring the `AutoSchema` instance on your view:
```
class PetDetailView(generics.RetrieveUpdateDestroyAPIView):
schema = AutoSchema(
tags=['Pets'],
component_name='Pet',
operation_id_base='Pet',
)
...
```
Assuming a `Pet` model and `PetSerializer` serializer, the kwargs in this
example are probably not needed. Often, though, you'll need to pass the kwargs
if you have multiple view targeting the same model, or have multiple views with
identically named serializers.
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
[openapi-tags]: https://swagger.io/specification/#tagObject
[openapi-operationid]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#fixed-fields-17
[openapi-components]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#componentsObject
[openapi-reference]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#referenceObject
[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

@ -1,4 +1,7 @@
source: serializers.py
---
source:
- serializers.py
---
# Serializers
@ -18,7 +21,7 @@ Let's start by creating a simple object we can use for example purposes:
from datetime import datetime
class Comment(object):
class Comment:
def __init__(self, email, content, created=None):
self.email = email
self.content = content
@ -43,7 +46,7 @@ We can now use `CommentSerializer` to serialize a comment, or list of comments.
serializer = CommentSerializer(comment)
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}
# {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}
At this point we've translated the model instance into Python native datatypes. To finalise the serialization process we render the data into `json`.
@ -51,16 +54,16 @@ At this point we've translated the model instance into Python native datatypes.
json = JSONRenderer().render(serializer.data)
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
# b'{"email":"leila@example.com","content":"foo bar","created":"2016-01-27T15:17:10.375877"}'
## Deserializing objects
Deserialization is similar. First we parse a stream into Python native datatypes...
from django.utils.six import BytesIO
import io
from rest_framework.parsers import JSONParser
stream = BytesIO(json)
stream = io.BytesIO(json)
data = JSONParser().parse(stream)
...then we restore those native datatypes into a dictionary of validated data.
@ -73,7 +76,7 @@ Deserialization is similar. First we parse a stream into Python native datatypes
## Saving instances
If we want to be able to return complete object instances based on the validated data we need to implement one or both of the `.create()` and `update()` methods. For example:
If we want to be able to return complete object instances based on the validated data we need to implement one or both of the `.create()` and `.update()` methods. For example:
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
@ -113,7 +116,7 @@ Calling `.save()` will either create a new instance, or update an existing insta
# .save() will update the existing `comment` instance.
serializer = CommentSerializer(comment, data=data)
Both the `.create()` and `.update()` methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.
Both the `.create()` and `.update()` methods are optional. You can implement either none, one, or both of them, depending on the use-case for your serializer class.
#### Passing additional attributes to `.save()`
@ -152,13 +155,13 @@ When deserializing data, you always need to call `is_valid()` before attempting
serializer.is_valid()
# False
serializer.errors
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
# {'email': ['Enter a valid e-mail address.'], 'created': ['This field is required.']}
Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The `non_field_errors` key may also be present, and will list any general validation errors. The name of the `non_field_errors` key may be customized using the `NON_FIELD_ERRORS_KEY` REST framework setting.
When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.
#### Raising an exception on invalid data
#### Raising an exception on invalid data
The `.is_valid()` method takes an optional `raise_exception` flag that will cause it to raise a `serializers.ValidationError` exception if there are validation errors.
@ -189,9 +192,15 @@ Your `validate_<field_name>` methods should return the validated value or raise
raise serializers.ValidationError("Blog post is not about Django")
return value
---
**Note:** If your `<field_name>` is declared on your serializer with the parameter `required=False` then this validation step will not take place if the field is not included.
---
#### Object-level validation
To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is a dictionary of field values. It should raise a `ValidationError` if necessary, or just return the validated values. For example:
To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is a dictionary of field values. It should raise a `serializers.ValidationError` if necessary, or just return the validated values. For example:
from rest_framework import serializers
@ -202,7 +211,7 @@ To do any other validation that requires access to multiple fields, add a method
def validate(self, data):
"""
Check that the start is before the stop.
Check that start is before finish.
"""
if data['start'] > data['finish']:
raise serializers.ValidationError("finish must occur after start")
@ -217,22 +226,24 @@ 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:
# Each room only has one event per day.
validators = UniqueTogetherValidator(
queryset=Event.objects.all(),
fields=['room_number', 'date']
)
validators = [
UniqueTogetherValidator(
queryset=Event.objects.all(),
fields=['room_number', 'date']
)
]
For more information see the [validators documentation](validators.md).
@ -240,14 +251,14 @@ For more information see the [validators documentation](validators.md).
When passing an initial object or queryset to a serializer instance, the object will be made available as `.instance`. If no initial object is passed then the `.instance` attribute will be `None`.
When passing data to a serializer instance, the unmodified data will be made available as `.initial_data`. If the data keyword argument is not passed then the `.initial_data` attribute will not exist.
When passing data to a serializer instance, the unmodified data will be made available as `.initial_data`. If the `data` keyword argument is not passed then the `.initial_data` attribute will not exist.
## Partial updates
By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the `partial` argument in order to allow partial updates.
# Update `comment` with partial data
serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)
serializer = CommentSerializer(comment, data={'content': 'foo bar'}, partial=True)
## Dealing with nested objects
@ -271,7 +282,7 @@ If a nested representation may optionally accept the `None` value you should pas
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
Similarly if a nested representation should be a list of items, you should pass the `many=True` flag to the nested serialized.
Similarly if a nested representation should be a list of items, you should pass the `many=True` flag to the nested serializer.
class CommentSerializer(serializers.Serializer):
user = UserSerializer(required=False)
@ -281,13 +292,13 @@ Similarly if a nested representation should be a list of items, you should pass
## Writable nested representations
When dealing with nested representations that support deserializing the data, an errors with nested objects will be nested under the field name of the nested object.
When dealing with nested representations that support deserializing the data, any errors with nested objects will be nested under the field name of the nested object.
serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})
serializer.is_valid()
# False
serializer.errors
# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']}
# {'user': {'email': ['Enter a valid e-mail address.']}, 'created': ['This field is required.']}
Similarly, the `.validated_data` property will include nested data structures.
@ -302,7 +313,7 @@ The following example demonstrates how you might handle creating a user with a n
class Meta:
model = User
fields = ('username', 'email', 'profile')
fields = ['username', 'email', 'profile']
def create(self, validated_data):
profile_data = validated_data.pop('profile')
@ -319,12 +330,12 @@ For updates you'll want to think carefully about how to handle updates to relati
* Ignore the data and leave the instance as it is.
* Raise a validation error.
Here's an example for an `update()` method on our previous `UserSerializer` class.
Here's an example for an `.update()` method on our previous `UserSerializer` class.
def update(self, instance, validated_data):
profile_data = validated_data.pop('profile')
# Unless the application properly enforces that this field is
# always set, the follow could raise a `DoesNotExist`, which
# always set, the following could raise a `DoesNotExist`, which
# would need to be handled.
profile = instance.profile
@ -346,11 +357,11 @@ Here's an example for an `update()` method on our previous `UserSerializer` clas
Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default `ModelSerializer` `.create()` and `.update()` methods do not include support for writable nested representations.
It is possible that a third party package, providing automatic support some kinds of automatic writable nested representations may be released alongside the 3.1 release.
There are however, third-party packages available such as [DRF Writable Nested][thirdparty-writable-nested] that support automatic writable nested representations.
#### Handling saving related instances in model manager classes
An alternative to saving multiple related instances in the serializer is to write custom model manager classes handle creating the correct instances.
An alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances.
For example, suppose we wanted to ensure that `User` instances and `Profile` instances are always created together as a pair. We might write a custom manager class that looks something like this:
@ -373,12 +384,12 @@ This manager class now more nicely encapsulates that user instances and profile
def create(self, validated_data):
return User.objects.create(
username=validated_data['username'],
email=validated_data['email']
is_premium_member=validated_data['profile']['is_premium_member']
email=validated_data['email'],
is_premium_member=validated_data['profile']['is_premium_member'],
has_support_contract=validated_data['profile']['has_support_contract']
)
For more details on this approach see the Django documentation on [model managers](model-managers), and [this blogpost on using model and manager classes](encapsulation-blogpost).
For more details on this approach see the Django documentation on [model managers][model-managers], and [this blogpost on using model and manager classes][encapsulation-blogpost].
## Dealing with multiple objects
@ -399,7 +410,7 @@ To serialize a queryset or list of objects instead of a single object instance,
#### Deserializing multiple objects
The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the [ListSerializer](#ListSerializer) documentation below.
The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the [ListSerializer](#listserializer) documentation below.
## Including extra context
@ -409,7 +420,7 @@ You can provide arbitrary additional context by passing a `context` argument whe
serializer = AccountSerializer(account, context={'request': request})
serializer.data
# {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}
# {'id': 6, 'owner': 'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}
The context dictionary can be used within any serializer field logic, such as a custom `.to_representation()` method, by accessing the `self.context` attribute.
@ -432,10 +443,11 @@ Declaring a `ModelSerializer` looks like this:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['id', 'account_name', 'users', 'created']
By default, all the model fields on the class will be mapped to a corresponding serializer fields.
Any relationships such as foreign keys on the model will be mapped to `PrimaryKeyRelatedField`. Reverse relationships are not included by default unless explicitly included as described below.
Any relationships such as foreign keys on the model will be mapped to `PrimaryKeyRelatedField`. Reverse relationships are not included by default unless explicitly included as specified in the [serializer relations][relations] documentation.
#### Inspecting a `ModelSerializer`
@ -445,7 +457,7 @@ To do so, open the Django shell, using `python manage.py shell`, then import the
>>> from myapp.serializers import AccountSerializer
>>> serializer = AccountSerializer()
>>> print repr(serializer) # Or `print(repr(serializer))` in Python 3.x.
>>> print(repr(serializer))
AccountSerializer():
id = IntegerField(label='ID', read_only=True)
name = CharField(allow_blank=True, max_length=100, required=False)
@ -453,19 +465,41 @@ To do so, open the Django shell, using `python manage.py shell`, then import the
## Specifying which fields to include
If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`.
If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`. It is strongly recommended that you explicitly set all fields that should be serialized using the `fields` attribute. This will make it less likely to result in unintentionally exposing data when your models change.
For example:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
fields = ['id', 'account_name', 'users', 'created']
The names in the `fields` option will normally map to model fields on the model class.
You can also set the `fields` attribute to the special value `'__all__'` to indicate that all fields in the model should be used.
For example:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = '__all__'
You can set the `exclude` attribute to a list of fields to be excluded from the serializer.
For example:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
exclude = ['users']
In the example above, if the `Account` model had 3 fields `account_name`, `users`, and `created`, this will result in the fields `account_name` and `created` to be serialized.
The names in the `fields` and `exclude` attributes will normally map to model fields on the model class.
Alternatively names in the `fields` options can map to properties or methods which take no arguments that exist on the model class.
Since version 3.3.0, it is **mandatory** to provide one of the attributes `fields` or `exclude`.
## Specifying nested serialization
The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option:
@ -473,7 +507,7 @@ The default `ModelSerializer` uses primary keys for relationships, but you can a
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
fields = ['id', 'account_name', 'users', 'created']
depth = 1
The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
@ -490,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.
@ -502,8 +537,8 @@ This option should be a list or tuple of field names, and is declared as follows
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
read_only_fields = ('account_name',)
fields = ['id', 'account_name', 'users', 'created']
read_only_fields = ['account_name']
Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option.
@ -524,14 +559,14 @@ Please review the [Validators Documentation](/api-guide/validators/) for details
## Additional keyword arguments
There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the `extra_kwargs` option. Similarly to `read_only_fields` this means you do not need to explicitly declare the field on the serializer.
There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the `extra_kwargs` option. As in the case of `read_only_fields`, this means you do not need to explicitly declare the field on the serializer.
This option is a dictionary, mapping field names to a dictionary of keyword arguments. For example:
class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email', 'username', 'password')
fields = ['email', 'username', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
@ -543,6 +578,8 @@ This option is a dictionary, mapping field names to a dictionary of keyword argu
user.save()
return user
Please keep in mind that, if the field has already been explicitly declared on the serializer class, then the `extra_kwargs` option will be ignored.
## Relational fields
When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for `ModelSerializer` is to use the primary keys of the related instances.
@ -551,31 +588,21 @@ Alternative representations include serializing using hyperlinks, serializing co
For full details see the [serializer relations][relations] documentation.
## Inheritance of the 'Meta' class
The inner `Meta` class on serializers is not inherited from parent classes by default. This is the same behavior as with Django's `Model` and `ModelForm` classes. If you want the `Meta` class to inherit from a parent class you must do so explicitly. For example:
class AccountSerializer(MyBaseSerializer):
class Meta(MyBaseSerializer.Meta):
model = Account
Typically we would recommend *not* using inheritance on inner Meta classes, but instead declaring all options explicitly.
## Customizing field mappings
The ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer.
Normally if a `ModelSerializer` does not generate the fields you need by default the 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.
Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.
### `.serializer_field_mapping`
### `serializer_field_mapping`
A mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class.
A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
### `.serializer_related_field`
### `serializer_related_field`
This property should be the serializer field class, that is used for relational fields by default.
For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`.
For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`.
For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`.
@ -595,21 +622,21 @@ Defaults to `serializers.ChoiceField`
The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`.
### `.build_standard_field(self, field_name, model_field)`
### `build_standard_field(self, field_name, model_field)`
Called to generate a serializer field that maps to a standard model field.
The default implementation returns a serializer class based on the `serializer_field_mapping` attribute.
### `.build_relational_field(self, field_name, relation_info)`
### `build_relational_field(self, field_name, relation_info)`
Called to generate a serializer field that maps to a relational model field.
The default implementation returns a serializer class based on the `serializer_relational_field` attribute.
The default implementation returns a serializer class based on the `serializer_related_field` attribute.
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
### `.build_nested_field(self, field_name, relation_info, nested_depth)`
### `build_nested_field(self, field_name, relation_info, nested_depth)`
Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set.
@ -619,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.
@ -649,7 +676,26 @@ You can explicitly include the primary key by adding it to the `fields` option,
class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
fields = ('url', 'id', 'account_name', 'users', 'created')
fields = ['url', 'id', 'account_name', 'users', 'created']
## Absolute and relative URLs
When instantiating a `HyperlinkedModelSerializer` you must include the current
`request` in the serializer context, for example:
serializer = AccountSerializer(queryset, context={'request': request})
Doing so will ensure that the hyperlinks can include an appropriate hostname,
so that the resulting representation uses fully qualified URLs, such as:
http://api.example.com/accounts/1/
Rather than relative URLs, such as:
/accounts/1/
If you *do* want to use relative URLs, you should explicitly pass `{'request': None}`
in the serializer context.
## How hyperlinked views are determined
@ -662,9 +708,9 @@ You can override a URL field view name and lookup field by using either, or both
class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
fields = ('account_url', 'account_name', 'users', 'created')
fields = ['account_url', 'account_name', 'users', 'created']
extra_kwargs = {
'url': {'view_name': 'accounts', 'lookup_field': 'account_name'}
'url': {'view_name': 'accounts', 'lookup_field': 'account_name'},
'users': {'lookup_field': 'username'}
}
@ -684,7 +730,7 @@ Alternatively you can set the fields on the serializer explicitly. For example:
class Meta:
model = Account
fields = ('url', 'account_name', 'users', 'created')
fields = ['url', 'account_name', 'users', 'created']
---
@ -704,9 +750,25 @@ The `ListSerializer` class provides the behavior for serializing and validating
When a serializer is instantiated and `many=True` is passed, a `ListSerializer` instance will be created. The serializer class then becomes a child of the parent `ListSerializer`
The following argument can also be passed to a `ListSerializer` field or a serializer that is passed `many=True`:
### `allow_empty`
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:
* You want to provide particular validation of the lists, such as always ensuring that there is at least one element in a list.
* You want to provide particular validation of the lists, such as checking that one element does not conflict with another element in a list.
* You want to customize the create or update behavior of multiple objects.
For these cases you can modify the class that is used when `many=True` is passed, by using the `list_serializer_class` option on the serializer `Meta` class.
@ -748,6 +810,8 @@ To support multiple updates you'll need to do so explicitly. When writing your m
* How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid?
* How should ordering be handled? Does changing the position of two items imply any state change or is it ignored?
You will need to add an explicit `id` field to the instance serializer. The default implicitly-generated `id` field is marked as `read_only`. This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's `update` method.
Here's an example of how you might choose to implement multiple updates:
class BookListSerializer(serializers.ListSerializer):
@ -759,7 +823,7 @@ Here's an example of how you might choose to implement multiple updates:
# Perform creations and updates.
ret = []
for book_id, data in data_mapping.items():
book = book_mapping.get(book_id, None):
book = book_mapping.get(book_id, None)
if book is None:
ret.append(self.child.create(data))
else:
@ -773,12 +837,14 @@ Here's an example of how you might choose to implement multiple updates:
return ret
class BookSerializer(serializers.Serializer):
# We need to identify elements in the list using their primary key,
# so use a writable field here, rather than the default which would be read-only.
id = serializers.IntegerField()
...
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.
@ -805,7 +871,7 @@ This class implements the same basic API as the `Serializer` class:
* `.data` - Returns the outgoing primitive representation.
* `.is_valid()` - Deserializes and validates incoming data.
* `.validated_data` - Returns the validated incoming data.
* `.errors` - Returns an errors during validation.
* `.errors` - Returns any errors during validation.
* `.save()` - Persists the validated data into an object instance.
There are four methods that can be overridden, depending on what functionality you want the serializer class to support:
@ -814,11 +880,11 @@ There are four methods that can be overridden, depending on what functionality y
* `.to_internal_value()` - Override this to support deserialization, for write operations.
* `.create()` and `.update()` - Override either or both of these to support saving instances.
Because this class provides the same interface as the `Serializer` class, you can use it with the existing generic class based views exactly as you would for a regular `Serializer` or `ModelSerializer`.
Because this class provides the same interface as the `Serializer` class, you can use it with the existing generic class-based views exactly as you would for a regular `Serializer` or `ModelSerializer`.
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:
@ -830,10 +896,10 @@ To implement a read-only serializer using the `BaseSerializer` class, we just ne
It's simple to create a read-only serializer for converting `HighScore` instances into primitive data types.
class HighScoreSerializer(serializers.BaseSerializer):
def to_representation(self, obj):
def to_representation(self, instance):
return {
'score': obj.score,
'player_name': obj.player_name
'score': instance.score,
'player_name': instance.player_name
}
We can now use this class to serialize single `HighScore` instances:
@ -842,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:
@ -850,11 +916,11 @@ 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 `ValidationError` if the supplied data is in an incorrect format.
To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `serializers.ValidationError` if the supplied data is in an incorrect format.
Once you've implemented `.to_internal_value()`, the basic validation API will be available on the serializer, and you will be able to use `.is_valid()`, `.validated_data` and `.errors`.
@ -869,29 +935,29 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
# Perform the data validation.
if not score:
raise ValidationError({
raise serializers.ValidationError({
'score': 'This field is required.'
})
if not player_name:
raise ValidationError({
raise serializers.ValidationError({
'player_name': 'This field is required.'
})
if len(player_name) > 10:
raise ValidationError({
raise serializers.ValidationError({
'player_name': 'May not be more than 10 characters.'
})
# Return the validated values. This will be available as
# the `.validated_data` property.
# Return the validated values. This will be available as
# the `.validated_data` property.
return {
'score': int(score),
'player_name': player_name
}
def to_representation(self, obj):
def to_representation(self, instance):
return {
'score': obj.score,
'player_name': obj.player_name
'score': instance.score,
'player_name': instance.player_name
}
def create(self, validated_data):
@ -901,17 +967,18 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.
The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
The following class is an example of a generic serializer that can handle coercing arbitrary complex objects into primitive representations.
class ObjectSerializer(serializers.BaseSerializer):
"""
A read-only serializer that coerces arbitrary complex objects
into primitive representations.
"""
def to_representation(self, obj):
for attribute_name in dir(obj):
attribute = getattr(obj, attribute_name)
if attribute_name('_'):
def to_representation(self, instance):
output = {}
for attribute_name in dir(instance):
attribute = getattr(instance, attribute_name)
if attribute_name.startswith('_'):
# Ignore private attributes.
pass
elif hasattr(attribute, '__call__'):
@ -934,6 +1001,7 @@ The following class is an example of a generic serializer that can handle coerci
else:
# Force anything else to its string representation.
output[attribute_name] = str(attribute)
return output
---
@ -941,7 +1009,7 @@ The following class is an example of a generic serializer that can handle coerci
## Overriding serialization and deserialization behavior
If you need to alter the serialization, deserialization or validation of a serializer class you can do so by overriding the `.to_representation()` or `.to_internal_value()` methods.
If you need to alter the serialization or deserialization behavior of a serializer class, you can do so by overriding the `.to_representation()` or `.to_internal_value()` methods.
Some reasons this might be useful include...
@ -951,18 +1019,60 @@ Some reasons this might be useful include...
The signatures for these methods are as follows:
#### `.to_representation(self, obj)`
#### `to_representation(self, instance)`
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
#### ``.to_internal_value(self, data)``
May be overridden in order to modify the representation style. For example:
def to_representation(self, instance):
"""Convert `username` to lowercase."""
ret = super().to_representation(instance)
ret['username'] = ret['username'].lower()
return ret
#### ``to_internal_value(self, data)``
Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
If any of the validation fails, then the method should raise a `serializers.ValidationError(errors)`. Typically the `errors` argument here will be a dictionary mapping field names to error messages.
If any of the validation fails, then the method should raise a `serializers.ValidationError(errors)`. The `errors` argument should be a dictionary mapping field names (or `settings.NON_FIELD_ERRORS_KEY`) to a list of error messages. If you don't need to alter deserialization behavior and instead want to provide object-level validation, it's recommended that you instead override the [`.validate()`](#object-level-validation) method.
The `data` argument passed to this method will normally be the value of `request.data`, so the datatype it provides will depend on the parser classes you have configured for your API.
## Serializer Inheritance
Similar to Django forms, you can extend and reuse serializers through inheritance. This allows you to declare a common set of fields or methods on a parent class that can then be used in a number of serializers. For example,
class MyBaseSerializer(Serializer):
my_field = serializers.CharField()
def validate_my_field(self, value):
...
class MySerializer(MyBaseSerializer):
...
Like Django's `Model` and `ModelForm` classes, the inner `Meta` class on serializers does not implicitly inherit from it's parents' inner `Meta` classes. If you want the `Meta` class to inherit from a parent class you must do so explicitly. For example:
class AccountSerializer(MyBaseSerializer):
class Meta(MyBaseSerializer.Meta):
model = Account
Typically we would recommend *not* using inheritance on inner Meta classes, but instead declaring all options explicitly.
Additionally, the following caveats apply to serializer inheritance:
* Normal Python name resolution rules apply. If you have multiple base classes that declare a `Meta` inner class, only the first one will be used. This means the childs `Meta`, if it exists, otherwise the `Meta` of the first parent, etc.
* Its possible to declaratively remove a `Field` inherited from a parent class by setting the name to be `None` on the subclass.
class MyBaseSerializer(ModelSerializer):
my_field = serializers.CharField()
class MySerializer(MyBaseSerializer):
my_field = None
However, you can only use this technique to opt out from a field defined declaratively by a parent class; it wont prevent the `ModelSerializer` from generating a default field. To opt-out from default fields, see [Specifying which fields to include](#specifying-which-fields-to-include).
## Dynamically modifying fields
Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the `.fields` attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.
@ -984,12 +1094,12 @@ 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.
allowed = set(fields)
existing = set(self.fields.keys())
existing = set(self.fields)
for field_name in existing - allowed:
self.fields.pop(field_name)
@ -998,12 +1108,12 @@ This would then allow you to do the following:
>>> class UserSerializer(DynamicFieldsModelSerializer):
>>> class Meta:
>>> model = User
>>> fields = ('id', 'username', 'email')
>>> fields = ['id', 'username', 'email']
>>>
>>> print UserSerializer(user)
>>> print(UserSerializer(user))
{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}
>>>
>>> print UserSerializer(user, fields=('id', 'email'))
>>> print(UserSerializer(user, fields=('id', 'email')))
{'id': 2, 'email': 'jon@example.com'}
## Customizing the default fields
@ -1014,14 +1124,20 @@ This API included the `.get_field()`, `.get_pk_field()` and other methods.
Because the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change.
A new interface for controlling this behavior is currently planned for REST framework 3.1.
---
# Third party packages
The following third party packages are also available.
## Django REST marshmallow
The [django-rest-marshmallow][django-rest-marshmallow] package provides an alternative implementation for serializers, using the python [marshmallow][marshmallow] library. It exposes the same API as the REST framework serializers, and can be used as a drop-in replacement in some use-cases.
## Serpy
The [serpy][serpy] package is an alternative implementation for serializers that is built for speed. [Serpy][serpy] serializes complex datatypes to simple native types. The native types can be easily converted to JSON or any other format needed.
## MongoengineModelSerializer
The [django-rest-framework-mongoengine][mongoengine] package provides a `MongoEngineModelSerializer` serializer class that supports using MongoDB as the storage layer for Django REST framework.
@ -1034,11 +1150,65 @@ The [django-rest-framework-gis][django-rest-framework-gis] package provides a `G
The [django-rest-framework-hstore][django-rest-framework-hstore] package provides an `HStoreSerializer` to support [django-hstore][django-hstore] `DictionaryField` model field and its `schema-mode` feature.
## Dynamic REST
The [dynamic-rest][dynamic-rest] package extends the ModelSerializer and ModelViewSet interfaces, adding API query parameters for filtering, sorting, and including / excluding all fields and relationships defined by your serializers.
## Dynamic Fields Mixin
The [drf-dynamic-fields][drf-dynamic-fields] package provides a mixin to dynamically limit the fields per serializer to a subset specified by an URL parameter.
## DRF FlexFields
The [drf-flex-fields][drf-flex-fields] package extends the ModelSerializer and ModelViewSet to provide commonly used functionality for dynamically setting fields and expanding primitive fields to nested models, both from URL parameters and your serializer class definitions.
## Serializer Extensions
The [django-rest-framework-serializer-extensions][drf-serializer-extensions]
package provides a collection of tools to DRY up your serializers, by allowing
fields to be defined on a per-view/request basis. Fields can be whitelisted,
blacklisted and child serializers can be optionally expanded.
## HTML JSON Forms
The [html-json-forms][html-json-forms] package provides an algorithm and serializer for processing `<form>` submissions per the (inactive) [HTML JSON Form specification][json-form-spec]. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, `<input name="items[0][id]" value="5">` will be interpreted as `{"items": [{"id": "5"}]}`.
## DRF-Base64
[DRF-Base64][drf-base64] provides a set of field and model serializers that handles the upload of base64-encoded files.
## QueryFields
[djangorestframework-queryfields][djangorestframework-queryfields] allows API clients to specify which fields will be sent in the response via inclusion/exclusion query parameters.
## DRF Writable Nested
The [drf-writable-nested][drf-writable-nested] package provides writable nested model serializer which allows to create/update models with nested related data.
## DRF Encrypt Content
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
[relations]: relations.md
[model-managers]: https://docs.djangoproject.com/en/dev/topics/db/managers/
[encapsulation-blogpost]: http://www.dabapps.com/blog/django-models-and-encapsulation/
[model-managers]: https://docs.djangoproject.com/en/stable/topics/db/managers/
[encapsulation-blogpost]: https://www.dabapps.com/blog/django-models-and-encapsulation/
[thirdparty-writable-nested]: serializers.md#drf-writable-nested
[django-rest-marshmallow]: https://marshmallow-code.github.io/django-rest-marshmallow/
[marshmallow]: https://marshmallow.readthedocs.io/en/latest/
[serpy]: https://github.com/clarkduvall/serpy
[mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine
[django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis
[django-rest-framework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore
[django-hstore]: https://github.com/djangonauts/django-hstore
[dynamic-rest]: https://github.com/AltSchool/dynamic-rest
[html-json-forms]: https://github.com/wq/html-json-forms
[drf-flex-fields]: https://github.com/rsinger86/drf-flex-fields
[json-form-spec]: https://www.w3.org/TR/html-json-forms/
[drf-dynamic-fields]: https://github.com/dbrgn/drf-dynamic-fields
[drf-base64]: https://bitbucket.org/levit_scs/drf_base64
[drf-serializer-extensions]: https://github.com/evenicoulddoit/django-rest-framework-serializer-extensions
[djangorestframework-queryfields]: https://djangorestframework-queryfields.readthedocs.io/
[drf-writable-nested]: https://github.com/beda-software/drf-writable-nested
[drf-encrypt-content]: https://github.com/oguzhancelikarslan/drf-encrypt-content

View File

@ -1,4 +1,7 @@
source: settings.py
---
source:
- settings.py
---
# Settings
@ -11,12 +14,12 @@ Configuration for REST framework is all namespaced inside a single Django settin
For example your project's `settings.py` file might include something like this:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_PARSER_CLASSES': (
],
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
)
]
}
## Accessing settings
@ -26,7 +29,7 @@ you should use the `api_settings` object. For example.
from rest_framework.settings import api_settings
print api_settings.DEFAULT_AUTHENTICATION_CLASSES
print(api_settings.DEFAULT_AUTHENTICATION_CLASSES)
The `api_settings` object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal.
@ -36,7 +39,7 @@ The `api_settings` object will check for any user-defined settings, and otherwis
## API policy settings
*The following settings control the basic API policies, and are applied to every `APIView` class based view, or `@api_view` function based view.*
*The following settings control the basic API policies, and are applied to every `APIView` class-based view, or `@api_view` function based view.*
#### DEFAULT_RENDERER_CLASSES
@ -44,10 +47,10 @@ A list or tuple of renderer classes, that determines the default set of renderer
Default:
(
[
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
)
]
#### DEFAULT_PARSER_CLASSES
@ -55,11 +58,11 @@ A list or tuple of parser classes, that determines the default set of parsers us
Default:
(
[
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
)
]
#### DEFAULT_AUTHENTICATION_CLASSES
@ -67,10 +70,10 @@ A list or tuple of authentication classes, that determines the default set of au
Default:
(
[
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
)
]
#### DEFAULT_PERMISSION_CLASSES
@ -78,15 +81,15 @@ A list or tuple of permission classes, that determines the default set of permis
Default:
(
[
'rest_framework.permissions.AllowAny',
)
]
#### DEFAULT_THROTTLE_CLASSES
A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.
Default: `()`
Default: `[]`
#### DEFAULT_CONTENT_NEGOTIATION_CLASS
@ -94,64 +97,38 @@ A content negotiation class, that determines how a renderer is selected for the
Default: `'rest_framework.negotiation.DefaultContentNegotiation'`
#### DEFAULT_SCHEMA_CLASS
A view inspector class that will be used for schema generation.
Default: `'rest_framework.schemas.openapi.AutoSchema'`
---
## Generic view settings
*The following settings control the behavior of the generic class based views.*
#### DEFAULT_PAGINATION_SERIALIZER_CLASS
A class the determines the default serialization style for paginated responses.
Default: `rest_framework.pagination.PaginationSerializer`
*The following settings control the behavior of the generic class-based views.*
#### DEFAULT_FILTER_BACKENDS
A list of filter backend classes that should be used for generic filtering.
If set to `None` then generic filtering is disabled.
#### PAGINATE_BY
#### DEFAULT_PAGINATION_CLASS
The default class to use for queryset pagination. If set to `None`, pagination
is disabled by default. See the pagination documentation for further guidance on
[setting](pagination.md#setting-the-pagination-style) and
[modifying](pagination.md#modifying-the-pagination-style) the pagination style.
Default: `None`
#### PAGE_SIZE
The default page size to use for pagination. If set to `None`, pagination is disabled by default.
Default: `None`
#### PAGINATE_BY_PARAM
The name of a query parameter, which can be used by the client to override the default page size to use for pagination. If set to `None`, clients may not override the default page size.
For example, given the following settings:
REST_FRAMEWORK = {
'PAGINATE_BY': 10,
'PAGINATE_BY_PARAM': 'page_size',
}
A client would be able to modify the pagination size by using the `page_size` query parameter. For example:
GET http://example.com/api/accounts?page_size=25
Default: `None`
#### MAX_PAGINATE_BY
The maximum page size to allow when the page size is specified by the client. If set to `None`, then no maximum limit is applied.
For example, given the following settings:
REST_FRAMEWORK = {
'PAGINATE_BY': 10,
'PAGINATE_BY_PARAM': 'page_size',
'MAX_PAGINATE_BY': 100
}
A client request like the following would return a paginated list of up to 100 items.
GET http://example.com/api/accounts?page_size=999
Default: `None`
### SEARCH_PARAM
The name of a query parameter, which can be used to specify the search term used by `SearchFilter`.
@ -180,12 +157,18 @@ If set, this value will restrict the set of versions that may be returned by the
Default: `None`
#### VERSION_PARAMETER
#### VERSION_PARAM
The string that should used for any versioning parameters, such as in the media type or URL query parameters.
Default: `'version'`
#### DEFAULT_VERSIONING_CLASS
The default versioning scheme to use.
Default: `None`
---
## Authentication settings
@ -195,6 +178,8 @@ Default: `'version'`
#### UNAUTHENTICATED_USER
The class that should be used to initialize `request.user` for unauthenticated requests.
(If removing authentication entirely, e.g. by removing `django.contrib.auth` from
`INSTALLED_APPS`, set `UNAUTHENTICATED_USER` to `None`.)
Default: `django.contrib.auth.models.AnonymousUser`
@ -226,52 +211,52 @@ The format of any of these renderer classes may be used when constructing a test
Default:
(
[
'rest_framework.renderers.MultiPartRenderer',
'rest_framework.renderers.JSONRenderer'
)
]
---
## Browser overrides
## Schema generation controls
*The following settings provide URL or form-based overrides of the default browser behavior.*
#### SCHEMA_COERCE_PATH_PK
#### FORM_METHOD_OVERRIDE
If set, this maps the `'pk'` identifier in the URL conf onto the actual field
name when generating a schema path parameter. Typically this will be `'id'`.
This gives a more suitable representation as "primary key" is an implementation
detail, whereas "identifier" is a more general concept.
The name of a form field that may be used to override the HTTP method of the form.
Default: `True`
If the value of this setting is `None` then form method overloading will be disabled.
#### SCHEMA_COERCE_METHOD_NAMES
Default: `'_method'`
If set, this is used to map internal viewset method names onto external action
names used in the schema generation. This allows us to generate names that
are more suitable for an external representation than those that are used
internally in the codebase.
#### FORM_CONTENT_OVERRIDE
Default: `{'retrieve': 'read', 'destroy': 'delete'}`
The name of a form field that may be used to override the content of the form payload. Must be used together with `FORM_CONTENTTYPE_OVERRIDE`.
---
If either setting is `None` then form content overloading will be disabled.
Default: `'_content'`
#### FORM_CONTENTTYPE_OVERRIDE
The name of a form field that may be used to override the content type of the form payload. Must be used together with `FORM_CONTENT_OVERRIDE`.
If either setting is `None` then form content overloading will be disabled.
Default: `'_content_type'`
#### URL_ACCEPT_OVERRIDE
The name of a URL parameter that may be used to override the HTTP `Accept` header.
If the value of this setting is `None` then URL accept overloading will be disabled.
Default: `'accept'`
## Content type controls
#### URL_FORMAT_OVERRIDE
The name of a URL parameter that may be used to override the default `Accept` header based content negotiation.
The name of a URL parameter that may be used to override the default content negotiation `Accept` header behavior, by using a `format=…` query parameter in the request URL.
For example: `http://example.com/organizations/?format=csv`
If the value of this setting is `None` then URL format overrides will be disabled.
Default: `'format'`
#### FORMAT_SUFFIX_KWARG
The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using `format_suffix_patterns` to include suffixed URL patterns.
For example: `http://example.com/organizations.csv/`
Default: `'format'`
@ -361,6 +346,14 @@ The default style is to return minified responses, in line with [Heroku's API de
Default: `True`
#### STRICT_JSON
When set to `True`, JSON rendering and parsing will only observe syntactically valid JSON, raising an exception for the extended float values (`nan`, `inf`, `-inf`) accepted by Python's `json` module. This is the recommended setting, as these values are not generally supported. e.g., neither Javascript's `JSON.Parse` nor PostgreSQL's JSON data type accept these values.
When set to `False`, JSON rendering and parsing will be permissive. However, these values are still invalid and will need to be specially handled in your code.
Default: `True`
#### COERCE_DECIMAL_TO_STRING
When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations.
@ -381,10 +374,15 @@ A string representing the function that should be used when generating view name
This should be a function with the following signature:
view_name(cls, suffix=None)
view_name(self)
* `cls`: The view class. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `cls.__name__`.
* `suffix`: The optional suffix used when differentiating individual views in a viewset.
* `self`: The view instance. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `self.__class__.__name__`.
If the view instance inherits `ViewSet`, it may have been initialized with several optional arguments:
* `name`: A name explicitly provided to a view in the viewset. Typically, this value should be used as-is when provided.
* `suffix`: Text used when differentiating individual views in a viewset. This argument is mutually exclusive to `name`.
* `detail`: Boolean that differentiates an individual view in a viewset as either being a 'list' or 'detail' view.
Default: `'rest_framework.views.get_view_name'`
@ -396,13 +394,33 @@ This setting can be changed to support markup styles other than the default mark
This should be a function with the following signature:
view_description(cls, html=False)
view_description(self, html=False)
* `cls`: The view class. Typically the description function would inspect the docstring of the class when generating a description, by accessing `cls.__doc__`
* `self`: The view instance. Typically the description function would inspect the docstring of the class when generating a description, by accessing `self.__class__.__doc__`
* `html`: A boolean indicating if HTML output is required. `True` when used in the browsable API, and `False` when used in generating `OPTIONS` responses.
If the view instance inherits `ViewSet`, it may have been initialized with several optional arguments:
* `description`: A description explicitly provided to the view in the viewset. Typically, this is set by extra viewset `action`s, and should be used as-is.
Default: `'rest_framework.views.get_view_description'`
## HTML Select Field cutoffs
Global settings for [select field cutoffs for rendering relational fields](relations.md#select-field-cutoffs) in the browsable API.
#### HTML_SELECT_CUTOFF
Global setting for the `html_cutoff` value. Must be an integer.
Default: 1000
#### HTML_SELECT_CUTOFF_TEXT
A string representing a global setting for `html_cutoff_text`.
Default: `"More than {count} items..."`
---
## Miscellaneous settings
@ -433,19 +451,13 @@ A string representing the key that should be used for the URL fields generated b
Default: `'url'`
#### FORMAT_SUFFIX_KWARG
The name of a parameter in the URL conf that may be used to provide a format suffix.
Default: `'format'`
#### NUM_PROXIES
An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to `None` then less strict IP matching will be used by the throttle classes.
Default: `None`
[cite]: http://www.python.org/dev/peps/pep-0020/
[rfc4627]: http://www.ietf.org/rfc/rfc4627.txt
[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]: http://docs.python.org/2/library/time.html#time.strftime
[strftime]: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

View File

@ -1,4 +1,7 @@
source: status.py
---
source:
- status.py
---
# Status Codes
@ -6,7 +9,7 @@ source: status.py
>
> &mdash; [RFC 2324][rfc2324], Hyper Text Coffee Pot Control Protocol
Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make more code more obvious and readable.
Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make your code more obvious and readable.
from rest_framework import status
from rest_framework.response import Response
@ -20,13 +23,13 @@ The full set of HTTP status codes included in the `status` module is listed belo
The module also includes a set of helper functions for testing if a status code is in a given range.
from rest_framework import status
from rest_framework.test import APITestCase
from rest_framework.test import APITestCase
class ExampleTestCase(APITestCase):
def test_url_root(self):
url = reverse('index')
response = self.client.get(url)
self.assertTrue(status.is_success(response.status_code))
class ExampleTestCase(APITestCase):
def test_url_root(self):
url = reverse('index')
response = self.client.get(url)
self.assertTrue(status.is_success(response.status_code))
For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616]
@ -38,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
@ -50,6 +55,9 @@ This class of status code indicates that the client's request was successfully r
HTTP_204_NO_CONTENT
HTTP_205_RESET_CONTENT
HTTP_206_PARTIAL_CONTENT
HTTP_207_MULTI_STATUS
HTTP_208_ALREADY_REPORTED
HTTP_226_IM_USED
## Redirection - 3xx
@ -63,6 +71,7 @@ This class of status code indicates that further action needs to be taken by the
HTTP_305_USE_PROXY
HTTP_306_RESERVED
HTTP_307_TEMPORARY_REDIRECT
HTTP_308_PERMANENT_REDIRECT
## Client Error - 4xx
@ -86,9 +95,16 @@ 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
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS
## Server Error - 5xx
@ -100,6 +116,11 @@ Response status codes beginning with the digit "5" indicate cases in which the s
HTTP_503_SERVICE_UNAVAILABLE
HTTP_504_GATEWAY_TIMEOUT
HTTP_505_HTTP_VERSION_NOT_SUPPORTED
HTTP_506_VARIANT_ALSO_NEGOTIATES
HTTP_507_INSUFFICIENT_STORAGE
HTTP_508_LOOP_DETECTED
HTTP_509_BANDWIDTH_LIMIT_EXCEEDED
HTTP_510_NOT_EXTENDED
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED
## Helper functions
@ -112,6 +133,6 @@ The following helper functions are available for identifying the category of the
is_client_error() # 4xx
is_server_error() # 5xx
[rfc2324]: http://www.ietf.org/rfc/rfc2324.txt
[rfc2616]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
[rfc6585]: http://tools.ietf.org/html/rfc6585
[rfc2324]: https://www.ietf.org/rfc/rfc2324.txt
[rfc2616]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
[rfc6585]: https://tools.ietf.org/html/rfc6585

View File

@ -1,4 +1,7 @@
source: test.py
---
source:
- test.py
---
# Testing
@ -22,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()
@ -38,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
@ -82,7 +88,11 @@ For example, when forcibly authenticating using a token, you might do something
user = User.objects.get(username='olivia')
request = factory.get('/accounts/django-superstars/')
force_authenticate(request, user=user, token=user.token)
force_authenticate(request, user=user, token=user.auth_token)
---
**Note**: `force_authenticate` directly sets `request.user` to the in-memory `user` instance. If you are re-using the same `user` instance across multiple tests that update the saved `user` state, you may need to call [`refresh_from_db()`][refresh_from_db_docs] between tests.
---
@ -115,7 +125,7 @@ Extends [Django's existing `Client` class][client].
## Making requests
The `APIClient` class supports the same request interface as Django's standard `Client` class. This means the that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. For example:
The `APIClient` class supports the same request interface as Django's standard `Client` class. This means that the standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. For example:
from rest_framework.test import APIClient
@ -162,7 +172,7 @@ The `credentials` method is appropriate for testing APIs that require authentica
#### .force_authenticate(user=None, token=None)
Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated.
Sometimes you may want to bypass authentication entirely and force all requests by the test client to be automatically treated as authenticated.
This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.
@ -184,9 +194,115 @@ As usual CSRF validation will only apply to any session authenticated views. Th
---
# Test cases
# RequestsClient
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 also includes a client for interacting with your application
using the popular Python library, `requests`. This may be useful if:
* You are expecting to interface with the API primarily from another Python service,
and want to test the service at the same level as the client will see.
* You want to write tests in such a way that they can also be run against a staging or
live environment. (See "Live tests" below.)
This exposes exactly the same interface as if you were using a requests session
directly.
from rest_framework.test import RequestsClient
client = RequestsClient()
response = client.get('http://testserver/users/')
assert response.status_code == 200
Note that the requests client requires you to pass fully qualified URLs.
## RequestsClient and working with the database
The `RequestsClient` class is useful if you want to write tests that solely interact with the service interface. This is a little stricter than using the standard Django test client, as it means that all interactions should be via the API.
If you're using `RequestsClient` you'll want to ensure that test setup, and results assertions are performed as regular API calls, rather than interacting with the database models directly. For example, rather than checking that `Customer.objects.count() == 3` you would list the customers endpoint, and ensure that it contains three records.
## Headers & Authentication
Custom headers and authentication credentials can be provided in the same way
as [when using a standard `requests.Session` instance][session_objects].
from requests.auth import HTTPBasicAuth
client.auth = HTTPBasicAuth('user', 'pass')
client.headers.update({'x-test': 'true'})
## CSRF
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 CSRF token, then present that
token in the following request.
For example...
client = RequestsClient()
# Obtain a CSRF token.
response = client.get('http://testserver/homepage/')
assert response.status_code == 200
csrftoken = response.cookies['csrftoken']
# Interact with the API.
response = client.post('http://testserver/organisations/', json={
'name': 'MegaCorp',
'status': 'active'
}, headers={'X-CSRFToken': csrftoken})
assert response.status_code == 200
## Live tests
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 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.
---
# CoreAPIClient
The CoreAPIClient allows you to interact with your API using the Python
`coreapi` client library.
# Fetch the API schema
client = CoreAPIClient()
schema = client.get('http://testserver/schema/')
# Create a new organisation
params = {'name': 'MegaCorp', 'status': 'active'}
client.action(schema, ['organisations', 'create'], params)
# Ensure that the organisation exists in the listing
data = client.action(schema, ['organisations', 'list'])
assert(len(data) == 1)
assert(data == [{'name': 'MegaCorp', 'status': 'active'}])
## Headers & Authentication
Custom headers and authentication may be used with `CoreAPIClient` in a
similar way as with `RequestsClient`.
from requests.auth import HTTPBasicAuth
client = CoreAPIClient()
client.session.auth = HTTPBasicAuth('user', 'pass')
client.session.headers.update({'x-test': 'true'})
---
# API Test cases
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`
@ -197,9 +313,10 @@ REST framework includes the following test case classes, that mirror the existin
You can use any of REST framework's test case classes as you would for the regular Django test case classes. The `self.client` attribute will be an `APIClient` instance.
from django.core.urlresolvers import reverse
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from myproject.apps.core.models import Account
class AccountTests(APITestCase):
def test_create_account(self):
@ -210,7 +327,34 @@ You can use any of REST framework's test case classes as you would for the regul
data = {'name': 'DabApps'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data, data)
self.assertEqual(Account.objects.count(), 1)
self.assertEqual(Account.objects.get().name, 'DabApps')
---
# URLPatternsTestCase
REST framework also provides a test case class for isolating `urlpatterns` on a per-class basis. Note that this inherits from Django's `SimpleTestCase`, and will most likely need to be mixed with another test case class.
## Example
from django.urls import include, path, reverse
from rest_framework.test import APITestCase, URLPatternsTestCase
class AccountTests(APITestCase, URLPatternsTestCase):
urlpatterns = [
path('api/', include('api.urls')),
]
def test_create_account(self):
"""
Ensure we can create a new account object.
"""
url = reverse('account-list')
response = self.client.get(url, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)
---
@ -261,14 +405,17 @@ For example, to add support for using `format='html'` in test requests, you migh
REST_FRAMEWORK = {
...
'TEST_REQUEST_RENDERER_CLASSES': (
'TEST_REQUEST_RENDERER_CLASSES': [
'rest_framework.renderers.MultiPartRenderer',
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.TemplateHTMLRenderer'
)
]
}
[cite]: http://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper
[client]: https://docs.djangoproject.com/en/dev/topics/testing/tools/#the-test-client
[requestfactory]: https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.client.RequestFactory
[cite]: https://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper
[client]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#the-test-client
[requestfactory]: https://docs.djangoproject.com/en/stable/topics/testing/advanced/#django.test.client.RequestFactory
[configuration]: #configuration
[refresh_from_db_docs]: https://docs.djangoproject.com/en/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

@ -1,4 +1,7 @@
source: throttling.py
---
source:
- throttling.py
---
# Throttling
@ -16,6 +19,10 @@ Multiple throttles can also be used if you want to impose both burst throttling
Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.
**The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins. In addition to this, the built-in throttling implementations are implemented using Django's cache framework, and use non-atomic operations to determine the request rate, which may sometimes result in some fuzziness.
The application-level throttling provided by REST framework is intended for implementing policies such as different business tiers and basic protections against service over-use.**
## How throttling is determined
As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
@ -28,27 +35,27 @@ If any throttle check fails an `exceptions.Throttled` exception will be raised,
The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_CLASSES` and `DEFAULT_THROTTLE_RATES` settings. For example.
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
),
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '1000/day'
}
}
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.
using the `APIView` class-based views.
from rest_framework.response import Response
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView
from rest_framework.views import APIView
class ExampleView(APIView):
throttle_classes = (UserRateThrottle,)
throttle_classes = [UserRateThrottle]
def get(self, request, format=None):
content = {
@ -56,7 +63,7 @@ using the `APIView` class based views.
}
return Response(content)
Or, if you're using the `@api_view` decorator with function based views.
If you're using the `@api_view` decorator with function based views you can use the following decorator.
@api_view(['GET'])
@throttle_classes([UserRateThrottle])
@ -66,15 +73,25 @@ Or, if you're using the `@api_view` decorator with function based views.
}
return Response(content)
## How clients are identified
It's also possible to set throttle classes for routes that are created using the `@action` decorator.
Throttle classes set in this way will override any viewset level class settings.
The `X-Forwarded-For` and `Remote-Addr` HTTP headers 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` header will be used.
@action(detail=True, methods=["post"], throttle_classes=[UserRateThrottle])
def example_adhoc_method(request, pk=None):
content = {
'status': 'request was permitted'
}
return Response(content)
If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the `NUM_PROXIES` setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the `X-Forwarded-For` header, once any application proxy IP addresses have first been excluded. If set to zero, then the `Remote-Addr` header will always be used as the identifying IP address.
## How clients are identified
It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client.
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.
Further context on how the `X-Forwarded-For` header works, and identifying a remote client IP can be [found here][identifing-clients].
If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the `NUM_PROXIES` setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the `X-Forwarded-For` header, once any application proxy IP addresses have first been excluded. If set to zero, then the `REMOTE_ADDR` value will always be used as the identifying IP address.
It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](https://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client.
Further context on how the `X-Forwarded-For` header works, and identifying a remote client IP can be [found here][identifying-clients].
## Setting up the cache
@ -82,11 +99,19 @@ The throttle classes provided by REST framework use Django's cache backend. You
If you need to use a cache other than `'default'`, you can do so by creating a custom throttle class and setting the `cache` attribute. For example:
from django.core.cache import caches
class CustomAnonRateThrottle(AnonRateThrottle):
cache = get_cache('alternate')
cache = caches['alternate']
You'll need to remember to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute.
## 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
@ -124,10 +149,10 @@ For example, multiple user throttle rates could be implemented by using the foll
...and the following settings.
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'DEFAULT_THROTTLE_CLASSES': [
'example.throttles.BurstRateThrottle',
'example.throttles.SustainedRateThrottle'
),
],
'DEFAULT_THROTTLE_RATES': {
'burst': '60/min',
'sustained': '1000/day'
@ -148,7 +173,7 @@ For example, given the following views...
throttle_scope = 'contacts'
...
class ContactDetailView(ApiView):
class ContactDetailView(APIView):
throttle_scope = 'contacts'
...
@ -159,9 +184,9 @@ For example, given the following views...
...and the following settings.
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.ScopedRateThrottle',
),
],
'DEFAULT_THROTTLE_RATES': {
'contacts': '1000/day',
'uploads': '20/day'
@ -184,12 +209,15 @@ If the `.wait()` method is implemented and the request is throttled, then a `Ret
The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.
class RandomRateThrottle(throttles.BaseThrottle):
def allow_request(self, request, view):
return random.randint(1, 10) == 1
import random
[cite]: https://dev.twitter.com/docs/error-codes-responses
class RandomRateThrottle(throttling.BaseThrottle):
def allow_request(self, request, view):
return random.randint(1, 10) != 1
[cite]: https://developer.twitter.com/en/docs/basics/rate-limiting
[permissions]: permissions.md
[identifing-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster
[cache-setting]: https://docs.djangoproject.com/en/dev/ref/settings/#caches
[cache-docs]: https://docs.djangoproject.com/en/dev/topics/cache/#setting-up-the-cache
[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

@ -1,4 +1,7 @@
source: validators.py
---
source:
- validators.py
---
# Validators
@ -17,10 +20,10 @@ 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 a `Serializer` classes instead, then you need to define the validation rules explicitly.
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.
#### Example
@ -45,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.
---
@ -61,9 +64,12 @@ It takes a single required argument, and an optional `messages` argument:
* `queryset` *required* - This is the queryset against which uniqueness should be enforced.
* `message` - The error message that should be used when validation fails.
* `lookup` - The lookup used to find an existing instance with the value being validated. Defaults to `'exact'`.
This validator should be applied to *serializer fields*, like so:
from rest_framework.validators import UniqueValidator
slug = SlugField(
max_length=100,
validators=[UniqueValidator(queryset=BlogPost.objects.all())]
@ -80,6 +86,8 @@ It has two required arguments, and a single optional `messages` argument:
The validator should be applied to *serializer classes*, like so:
from rest_framework.validators import UniqueTogetherValidator
class ExampleSerializer(serializers.Serializer):
# ...
class Meta:
@ -89,13 +97,13 @@ The validator should be applied to *serializer classes*, like so:
validators = [
UniqueTogetherValidator(
queryset=ToDoItem.objects.all(),
fields=('list', 'position')
fields=['list', 'position']
)
]
---
**Note**: The `UniqueTogetherValidation` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
**Note**: The `UniqueTogetherValidator` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
---
@ -114,6 +122,8 @@ These validators can be used to enforce the `unique_for_date`, `unique_for_month
The validator should be applied to *serializer classes*, like so:
from rest_framework.validators import UniqueForYearValidator
class ExampleSerializer(serializers.Serializer):
# ...
class Meta:
@ -142,28 +152,30 @@ If you want the date field to be visible, but not editable by the user, then set
published = serializers.DateTimeField(read_only=True, default=timezone.now)
The field will not be writable to the user, but the default value will still be passed through to the `validated_data`.
#### Using with a hidden date field.
If you want the date field to be entirely hidden from the user, then use `HiddenField`. This field type does not accept user input, but instead always returns it's default value to the `validated_data` in the serializer.
If you want the date field to be entirely hidden from the user, then use `HiddenField`. This field type does not accept user input, but instead always returns its default value to the `validated_data` in the serializer.
published = serializers.HiddenField(default=timezone.now)
---
**Note**: The `UniqueFor<Range>Validation` classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
**Note**: The `UniqueFor<Range>Validator` classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
---
# Advanced 'default' argument usage
---
**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.
@ -175,19 +187,83 @@ 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.
It takes a single argument, which is the default value or callable that should be used during create operations.
created_at = serializers.DateTimeField(
read_only=True,
default=CreateOnlyDefault(timezone.now)
default=serializers.CreateOnlyDefault(timezone.now)
)
---
# Limitations of validators
There are some ambiguous cases where you'll need to instead handle validation
explicitly, rather than relying on the default serializer classes that
`ModelSerializer` generates.
In these cases you may want to disable the automatically generated validators,
by specifying an empty list for the serializer `Meta.validators` attribute.
## Optional fields
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 behavior
of the validation is ambiguous.
In this case you will typically need to exclude the validator from the
serializer class, and instead write any validation logic explicitly, either
in the `.validate()` method, or else in the view.
For example:
class BillingRecordSerializer(serializers.ModelSerializer):
def validate(self, attrs):
# Apply custom validation either here, or in the view.
class Meta:
fields = ['client', 'date', 'amount']
extra_kwargs = {'client': {'required': False}}
validators = [] # Remove a default "unique together" constraint.
## Updating nested serializers
When applying an update to an existing instance, uniqueness validators will
exclude the current instance from the uniqueness check. The current instance
is available in the context of the uniqueness check, because it exists as
an attribute on the serializer, having initially been passed using
`instance=...` when instantiating the serializer.
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 for the validation constraint
explicitly, in a `.validate()` method, or in the view.
## Debugging complex cases
If you're not sure exactly what behavior a `ModelSerializer` class will
generate it is usually a good idea to run `manage.py shell`, and print
an instance of the serializer, so that you can inspect the fields and
validators that it automatically generates for you.
>>> serializer = MyComplexModelSerializer()
>>> print(serializer)
class MyComplexModelSerializer:
my_fields = ...
Also keep in mind that with complex cases it can often be better to explicitly
define your serializer classes, rather than relying on the default
`ModelSerializer` behavior. This involves a little more code, but ensures
that the resulting behavior is more transparent.
---
# Writing custom validators
You can use any of Django's existing validators, or write your own custom validators.
@ -200,26 +276,37 @@ A validator may be any callable that raises a `serializers.ValidationError` on f
if value % 2 != 0:
raise serializers.ValidationError('This field must be an even number.')
## Class based
#### Field-level validation
To write a class based validator, use the `__call__` method. Class based validators are useful as they allow you to parameterize and reuse behavior.
You can specify custom field-level validation by adding `.validate_<field_name>` methods
to your `Serializer` subclass. This is documented in the
[Serializer docs](https://www.django-rest-framework.org/api-guide/serializers/#field-level-validation)
## Class-based
To write a class-based validator, use the `__call__` method. Class-based validators are useful as they allow you to parameterize and reuse behavior.
class MultipleOf:
def __init__(self, base):
self.base = base
def __call__(self, value):
if value % self.base != 0
if value % self.base != 0:
message = 'This field must be a multiple of %d.' % self.base
raise serializers.ValidationError(message)
#### Using `set_context()`
#### Accessing the context
In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a `set_context` method on a class based validator.
In some advanced cases you might want a validator to be passed the serializer
field it is being used with as additional context. You can do so by setting
a `requires_context = True` attribute on the validator class. The `__call__` method
will then be called with the `serializer_field`
or `serializer` as an additional argument.
def set_context(self, serializer_field):
# Determine if this is an update or a create operation.
# In `__call__` we can then use that information to modify the validation behavior.
self.is_update = serializer_field.parent.instance is not None
class MultipleOf:
requires_context = True
[cite]: https://docs.djangoproject.com/en/dev/ref/validators/
def __call__(self, value, serializer_field):
...
[cite]: https://docs.djangoproject.com/en/stable/ref/validators/

View File

@ -1,9 +1,12 @@
source: versioning.py
---
source:
- versioning.py
---
# Versioning
> Versioning an interface is just a "polite" way to kill deployed clients.
>
>
> &mdash; [Roy Fielding][cite].
API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes.
@ -37,7 +40,7 @@ The `reverse` function included by REST framework ties in with the versioning sc
The above function will apply any URL transformations appropriate to the request version. For example:
* If `NamespacedVersioning` was being used, and the API version was 'v1', then the URL lookup used would be `'v1:bookings-list'`, which might resolve to a URL like `http://example.org/v1/bookings/`.
* If `NamespaceVersioning` was being used, and the API version was 'v1', then the URL lookup used would be `'v1:bookings-list'`, which might resolve to a URL like `http://example.org/v1/bookings/`.
* If `QueryParameterVersioning` was being used, and the API version was `1.0`, then the returned URL might be something like `http://example.org/bookings/?version=1.0`
#### Versioned APIs and hyperlinked serializers
@ -71,8 +74,21 @@ You can also set the versioning scheme on an individual view. Typically you won'
The following settings keys are also used to control versioning:
* `DEFAULT_VERSION`. The value that should be used for `request.version` when no versioning information is present. Defaults to `None`.
* `ALLOWED_VERSIONS`. If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set. Defaults to `None`.
* `VERSION_PARAMETER`. The string that should used for any versioning parameters, such as in the media type or URL query parameters. Defaults to `'version'`.
* `ALLOWED_VERSIONS`. If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version is not in this set. Note that the value used for the `DEFAULT_VERSION` setting is always considered to be part of the `ALLOWED_VERSIONS` set (unless it is `None`). Defaults to `None`.
* `VERSION_PARAM`. The string that should be used for any versioning parameters, such as in the media type or URL query parameters. Defaults to `'version'`.
You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the `default_version`, `allowed_versions` and `version_param` class variables. For example, if you want to use `URLPathVersioning`:
from rest_framework.versioning import URLPathVersioning
from rest_framework.views import APIView
class ExampleVersioning(URLPathVersioning):
default_version = ...
allowed_versions = ...
version_param = ...
class ExampleView(APIVIew):
versioning_class = ExampleVersioning
---
@ -116,13 +132,13 @@ This scheme requires the client to specify the version as part of the URL path.
Your URL conf must include a pattern that matches the version with a `'version'` keyword argument, so that this information is available to the versioning scheme.
urlpatterns = [
url(
r'^(?P<version>{v1,v2})/bookings/$',
re_path(
r'^(?P<version>(v1|v2))/bookings/$',
bookings_list,
name='bookings-list'
),
url(
r'^(?P<version>{v1,v2})/bookings/(?P<pk>[0-9]+)/$',
re_path(
r'^(?P<version>(v1|v2))/bookings/(?P<pk>[0-9]+)/$',
bookings_detail,
name='bookings-detail'
)
@ -130,7 +146,7 @@ Your URL conf must include a pattern that matches the version with a `'version'`
## NamespaceVersioning
To the client, this scheme is the same as `URLParameterVersioning`. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments.
To the client, this scheme is the same as `URLPathVersioning`. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments.
GET /v1/something/ HTTP/1.1
Host: example.com
@ -142,17 +158,17 @@ In the following example we're giving a set of views two different possible URL
# bookings/urls.py
urlpatterns = [
url(r'^$', bookings_list, name='bookings-list'),
url(r'^(?P<pk>[0-9]+)/$', bookings_detail, name='bookings-detail')
re_path(r'^$', bookings_list, name='bookings-list'),
re_path(r'^(?P<pk>[0-9]+)/$', bookings_detail, name='bookings-detail')
]
# urls.py
urlpatterns = [
url(r'^v1/bookings/', include('bookings.urls', namespace='v1')),
url(r'^v2/bookings/', include('bookings.urls', namespace='v2'))
re_path(r'^v1/bookings/', include('bookings.urls', namespace='v1')),
re_path(r'^v2/bookings/', include('bookings.urls', namespace='v2'))
]
Both `URLParameterVersioning` and `NamespaceVersioning` are reasonable if you just need a simple versioning scheme. The `URLParameterVersioning` approach might be better suitable for small ad-hoc projects, and the `NamespaceVersioning` is probably easier to manage for larger projects.
Both `URLPathVersioning` and `NamespaceVersioning` are reasonable if you just need a simple versioning scheme. The `URLPathVersioning` approach might be better suitable for small ad-hoc projects, and the `NamespaceVersioning` is probably easier to manage for larger projects.
## HostNameVersioning
@ -170,7 +186,7 @@ By default this implementation expects the hostname to match this simple regular
Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname.
The `HostNameVersioning` scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as `127.0.0.1`. There are various online services which you to [access localhost with a custom subdomain][lvh] which you may find helpful in this case.
The `HostNameVersioning` scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as `127.0.0.1`. There are various online tutorials on how to [access localhost with a custom subdomain][lvh] which you may find helpful in this case.
Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions.
@ -198,10 +214,10 @@ The following example uses a custom `X-API-Version` header to determine the requ
If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the `.reverse()` method on the class. See the source code for examples.
[cite]: http://www.slideshare.net/evolve_conference/201308-fielding-evolve/31
[roy-fielding-on-versioning]: http://www.infoq.com/articles/roy-fielding-on-versioning
[cite]: https://www.slideshare.net/evolve_conference/201308-fielding-evolve/31
[roy-fielding-on-versioning]: https://www.infoq.com/articles/roy-fielding-on-versioning
[klabnik-guidelines]: http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http#i_want_my_api_to_be_versioned
[heroku-guidelines]: https://github.com/interagent/http-api-design#version-with-accepts-header
[json-parameters]: http://tools.ietf.org/html/rfc4627#section-6
[vendor-media-type]: http://en.wikipedia.org/wiki/Internet_media_type#Vendor_tree
[heroku-guidelines]: https://github.com/interagent/http-api-design/blob/master/en/foundations/require-versioning-in-the-accepts-header.md
[json-parameters]: https://tools.ietf.org/html/rfc4627#section-6
[vendor-media-type]: https://en.wikipedia.org/wiki/Internet_media_type#Vendor_tree
[lvh]: https://reinteractive.net/posts/199-developing-and-testing-rails-applications-with-subdomains

View File

@ -1,9 +1,12 @@
source: decorators.py
views.py
---
source:
- decorators.py
- views.py
---
# Class Based Views
# Class-based Views
> Django's class based views are a welcome departure from the old-style views.
> Django's class-based views are a welcome departure from the old-style views.
>
> &mdash; [Reinout van Rees][cite]
@ -23,6 +26,7 @@ For example:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from django.contrib.auth.models import User
class ListUsers(APIView):
"""
@ -31,8 +35,8 @@ For example:
* Requires token authentication.
* Only admin users are able to access this view.
"""
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAdminUser,)
authentication_classes = [authentication.TokenAuthentication]
permission_classes = [permissions.IsAdminUser]
def get(self, request, format=None):
"""
@ -41,6 +45,13 @@ For example:
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
---
**Note**: The full methods, attributes on, and relations between Django REST Framework's `APIView`, `GenericAPIView`, various `Mixins`, and `Viewsets` can be initially complex. In addition to the documentation here, the [Classy Django REST Framework][classy-drf] resource provides a browsable reference, with full methods and attributes, for each of Django REST Framework's class-based views.
---
## API policy attributes
The following attributes control the pluggable aspects of API views.
@ -73,6 +84,8 @@ The following methods are used by REST framework to instantiate the various plug
### .get_content_negotiator(self)
### .get_exception_handler(self)
## API policy implementation methods
The following methods are called before dispatching to the handler method.
@ -119,7 +132,7 @@ You won't typically need to override this method.
# Function Based Views
> Saying [that Class based views] is always the superior solution is a mistake.
> Saying [that class-based views] is always the superior solution is a mistake.
>
> &mdash; [Nick Coghlan][cite2]
@ -132,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):
@ -147,6 +161,7 @@ By default only `GET` methods will be accepted. Other methods will respond with
return Response({"message": "Got some data!", "data": request.data})
return Response({"message": "Hello, world!"})
## API policy decorators
To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle][throttling] to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
@ -155,7 +170,7 @@ To override the default settings, REST framework provides a set of additional de
from rest_framework.throttling import UserRateThrottle
class OncePerDayUserThrottle(UserRateThrottle):
rate = '1/day'
rate = '1/day'
@api_view(['GET'])
@throttle_classes([OncePerDayUserThrottle])
@ -174,7 +189,39 @@ The available decorators are:
Each of these decorators takes a single argument which must be a list or tuple of classes.
[cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
## View schema decorator
To override the default schema generation for function based views you may use
the `@schema` decorator. This must come *after* (below) the `@api_view`
decorator. For example:
from rest_framework.decorators import api_view, schema
from rest_framework.schemas import AutoSchema
class CustomAutoSchema(AutoSchema):
def get_link(self, path, method, base_url):
# override view introspection here...
@api_view(['GET'])
@schema(CustomAutoSchema())
def view(request):
return Response({"message": "Hello for today! See you tomorrow!"})
This decorator takes a single `AutoSchema` instance, an `AutoSchema` subclass
instance or `ManualSchema` instance as described in the [Schemas documentation][schemas].
You may pass `None` in order to exclude the view from schema generation.
@api_view(['GET'])
@schema(None)
def view(request):
return Response({"message": "Will not appear in schema!"})
[cite]: https://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
[cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html
[settings]: settings.md
[throttling]: throttling.md
[schemas]: schemas.md
[classy-drf]: http://www.cdrf.co

View File

@ -1,4 +1,7 @@
source: viewsets.py
---
source:
- viewsets.py
---
# ViewSets
@ -27,7 +30,7 @@ Let's define a simple viewset that can be used to list or retrieve all the users
class UserViewSet(viewsets.ViewSet):
"""
A simple ViewSet that for listing or retrieving users.
A simple ViewSet for listing or retrieving users.
"""
def list(self, request):
queryset = User.objects.all()
@ -51,7 +54,7 @@ Typically we wouldn't do this, but would instead register the viewset with a rou
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'users', UserViewSet, basename='user')
urlpatterns = router.urls
Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:
@ -70,9 +73,10 @@ There are two main advantages of using a `ViewSet` class over using a `View` cla
Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.
## Marking extra actions for routing
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:
## ViewSet actions
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:
class UserViewSet(viewsets.ViewSet):
"""
@ -101,16 +105,40 @@ The default routers included with REST framework will provide routes for a stand
def destroy(self, request, pk=None):
pass
If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@detail_route` or `@list_route` decorators.
## Introspecting ViewSet actions
The `@detail_route` decorator contains `pk` in its URL pattern and is intended for methods which require a single instance. The `@list_route` decorator is intended for methods which operate on a list of objects.
During dispatch, the following attributes are available on the `ViewSet`.
For example:
* `basename` - the base to use for the URL names that are created.
* `action` - the name of the current action (e.g., `list`, `create`).
* `detail` - boolean indicating if the current action is configured for a list or detail view.
* `suffix` - the display suffix for the viewset type - mirrors the `detail` attribute.
* `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`.
* `description` - the display description for the individual view of a viewset.
You may inspect these attributes to adjust 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):
"""
Instantiates and returns the list of permissions that this view requires.
"""
if self.action == 'list':
permission_classes = [IsAuthenticated]
else:
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.
A more complete example of extra actions:
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from myapp.serializers import UserSerializer, PasswordSerializer
@ -121,21 +149,21 @@ For example:
queryset = User.objects.all()
serializer_class = UserSerializer
@detail_route(methods=['post'])
@action(detail=True, methods=['post'])
def set_password(self, request, pk=None):
user = self.get_object()
serializer = PasswordSerializer(data=request.data)
if serializer.is_valid():
user.set_password(serializer.data['password'])
user.set_password(serializer.validated_data['password'])
user.save()
return Response({'status': 'password set'})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
@list_route()
@action(detail=False)
def recent_users(self, request):
recent_users = User.objects.all().order('-last_login')
recent_users = User.objects.all().order_by('-last_login')
page = self.paginate_queryset(recent_users)
if page is not None:
@ -145,19 +173,69 @@ For example:
serializer = self.get_serializer(recent_users, many=True)
return Response(serializer.data)
The decorators can additionally take extra arguments that will be set for the routed view only. For example...
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
...
The `action` decorator will route `GET` requests by default, but may also accept other HTTP methods by setting the `methods` argument. For example:
These decorators will route `GET` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example:
@detail_route(methods=['post', 'delete'])
@action(detail=True, methods=['post', 'delete'])
def unset_password(self, request, pk=None):
...
The two new actions will then be available at the urls `^users/{pk}/set_password/$` and `^users/{pk}/unset_password/$`
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`...:
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
...
The two new actions will then be available at the urls `^users/{pk}/set_password/$` and `^users/{pk}/unset_password/$`. Use the `url_path` and `url_name` parameters to change the URL segment and the reverse URL name of the action.
To view all extra actions, call the `.get_extra_actions()` method.
### Routing additional HTTP methods for extra actions
Extra actions can map additional HTTP methods to separate `ViewSet` methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments.
```python
@action(detail=True, methods=["put"], name="Change Password")
def password(self, request, pk=None):
"""Update the user's password."""
...
@password.mapping.delete
def delete_password(self, request, pk=None):
"""Delete the user's password."""
...
```
## Reversing action URLs
If you need to get the URL of an action, use the `.reverse_action()` method. This is a convenience wrapper for `reverse()`, automatically passing the view's `request` object and prepending the `url_name` with the `.basename` attribute.
Note that the `basename` is provided by the router during `ViewSet` registration. If you are not using a router, then you must provide the `basename` argument to the `.as_view()` method.
Using the example from the previous section:
```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.
```pycon
>>> view.reverse_action(view.set_password.url_name, args=['1'])
'http://localhost:8000/api/users/1/set_password'
```
The `url_name` argument for `.reverse_action()` should match the same argument to the `@action` decorator. Additionally, this method can be used to reverse the default actions, such as `list` and `create`.
---
@ -179,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()`, and `.destroy()`.
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
#### Example
@ -206,7 +284,7 @@ Note that you can use any of the standard attributes or method overrides provide
def get_queryset(self):
return self.request.user.accounts.all()
Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the base_name of your Model automatically, and so you will have to specify the `base_name` kwarg as part of your [router registration][routers].
Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the basename of your Model automatically, and so you will have to specify the `basename` kwarg as part of your [router registration][routers].
Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.
@ -235,6 +313,8 @@ 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, viewsets
class CreateListRetrieveViewSet(mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
@ -249,5 +329,5 @@ To create a base viewset class that provides `create`, `list` and `retrieve` ope
By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple viewsets across your API.
[cite]: http://guides.rubyonrails.org/routing.html
[cite]: https://guides.rubyonrails.org/action_controller_overview.html
[routers]: routers.md

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.
@ -32,7 +32,7 @@ Significant new functionality continues to be planned for the 3.1 and 3.2 releas
#### REST framework: Under the hood.
This talk from the [Django: Under the Hood](http://www.djangounderthehood.com/) event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.
This talk from the [Django: Under the Hood](https://www.djangounderthehood.com/) event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.
<iframe style="display: block; margin: 0 auto 0 auto" width="560" height="315" src="//www.youtube.com/embed/3cSsbe-tA0E" frameborder="0" allowfullscreen></iframe>
@ -119,7 +119,7 @@ This would now be split out into two separate methods.
instance.save()
return instance
def create(self, validated_data):
def create(self, validated_data):
return Snippet.objects.create(**validated_data)
Note that these methods should return the newly created object instance.
@ -258,13 +258,13 @@ If you try to use a writable nested serializer without writing a custom `create(
>>> class ProfileSerializer(serializers.ModelSerializer):
>>> class Meta:
>>> model = Profile
>>> fields = ('address', 'phone')
>>> fields = ['address', 'phone']
>>>
>>> class UserSerializer(serializers.ModelSerializer):
>>> profile = ProfileSerializer()
>>> class Meta:
>>> model = User
>>> fields = ('username', 'email', 'profile')
>>> fields = ['username', 'email', 'profile']
>>>
>>> data = {
>>> 'username': 'lizzy',
@ -283,7 +283,7 @@ To use writable nested serialization you'll want to declare a nested field on th
class Meta:
model = User
fields = ('username', 'email', 'profile')
fields = ['username', 'email', 'profile']
def create(self, validated_data):
profile_data = validated_data.pop('profile')
@ -327,9 +327,9 @@ The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDe
class MySerializer(serializer.ModelSerializer):
class Meta:
model = MyModel
fields = ('id', 'email', 'notes', 'is_admin')
fields = ['id', 'email', 'notes', 'is_admin']
extra_kwargs = {
'is_admin': {'write_only': True}
'is_admin': {'write_only': True}
}
Alternatively, specify the field explicitly on the serializer class:
@ -339,7 +339,7 @@ Alternatively, specify the field explicitly on the serializer class:
class Meta:
model = MyModel
fields = ('id', 'email', 'notes', 'is_admin')
fields = ['id', 'email', 'notes', 'is_admin']
The `read_only_fields` option remains as a convenient shortcut for the more common case.
@ -350,7 +350,7 @@ The `view_name` and `lookup_field` options have been moved to `PendingDeprecatio
class MySerializer(serializer.HyperlinkedModelSerializer):
class Meta:
model = MyModel
fields = ('url', 'email', 'notes', 'is_admin')
fields = ['url', 'email', 'notes', 'is_admin']
extra_kwargs = {
'url': {'lookup_field': 'uuid'}
}
@ -365,7 +365,7 @@ Alternatively, specify the field explicitly on the serializer class:
class Meta:
model = MyModel
fields = ('url', 'email', 'notes', 'is_admin')
fields = ['url', 'email', 'notes', 'is_admin']
#### Fields for model methods and properties.
@ -384,12 +384,12 @@ You can include `expiry_date` as a field option on a `ModelSerializer` class.
class InvitationSerializer(serializers.ModelSerializer):
class Meta:
model = Invitation
fields = ('to_email', 'message', 'expiry_date')
fields = ['to_email', 'message', 'expiry_date']
These fields will be mapped to `serializers.ReadOnlyField()` instances.
>>> serializer = InvitationSerializer()
>>> print repr(serializer)
>>> print(repr(serializer))
InvitationSerializer():
to_email = EmailField(max_length=75)
message = CharField(max_length=1000)
@ -426,7 +426,7 @@ There are four methods that can be overridden, depending on what functionality y
* `.to_internal_value()` - Override this to support deserialization, for write operations.
* `.create()` and `.update()` - Override either or both of these to support saving instances.
Because this class provides the same interface as the `Serializer` class, you can use it with the existing generic class based views exactly as you would for a regular `Serializer` or `ModelSerializer`.
Because this class provides the same interface as the `Serializer` class, you can use it with the existing generic class-based views exactly as you would for a regular `Serializer` or `ModelSerializer`.
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.
@ -454,7 +454,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:
@ -462,7 +462,7 @@ 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.
@ -493,8 +493,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
@ -523,7 +523,7 @@ The following class is an example of a generic serializer that can handle coerci
def to_representation(self, obj):
for attribute_name in dir(obj):
attribute = getattr(obj, attribute_name)
if attribute_name('_'):
if attribute_name.startswith('_'):
# Ignore private attributes.
pass
elif hasattr(attribute, '__call__'):
@ -632,7 +632,7 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behavior in a way that did not simply lookup the field value from the object. For example...
def field_to_native(self, obj, field_name):
"""A custom read-only field that returns the class name."""
@ -738,7 +738,7 @@ The `UniqueTogetherValidator` should be applied to a serializer, and takes a `qu
class Meta:
validators = [UniqueTogetherValidator(
queryset=RaceResult.objects.all(),
fields=('category', 'position')
fields=['category', 'position']
)]
#### The `UniqueForDateValidator` classes.
@ -801,7 +801,7 @@ This change means that you can now easily customize the style of error responses
## The metadata API
Behavior for dealing with `OPTIONS` requests was previously built directly into the class based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework.
Behavior for dealing with `OPTIONS` requests was previously built directly into the class-based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework.
This makes it far easier to use a different style for `OPTIONS` responses throughout your API, and makes it possible to create third-party metadata policies.
@ -870,7 +870,7 @@ The `COMPACT_JSON` setting has been added, and can be used to revert this behavi
#### File fields as URLs
The `FileField` and `ImageField` classes are now represented as URLs by default. You should ensure you set Django's [standard `MEDIA_URL` setting](https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-MEDIA_URL) appropriately, and ensure your application [serves the uploaded files](https://docs.djangoproject.com/en/dev/howto/static-files/#serving-uploaded-files-in-development).
The `FileField` and `ImageField` classes are now represented as URLs by default. You should ensure you set Django's [standard `MEDIA_URL` setting](https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-MEDIA_URL) appropriately, and ensure your application [serves the uploaded files](https://docs.djangoproject.com/en/stable/howto/static-files/#serving-uploaded-files-in-development).
You can revert this behavior, and display filenames in the representation by using the `UPLOADED_FILES_USE_URL` settings key:
@ -894,11 +894,11 @@ If the request is omitted from the context, the returned URLs will be of the for
The custom `X-Throttle-Wait-Second` header has now been dropped in favor of the standard `Retry-After` header. You can revert this behavior if needed by writing a custom exception handler for your application.
#### Date and time objects as ISO-8859-1 strings in serializer data.
#### Date and time objects as ISO-8601 strings in serializer data.
Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as `Date`, `Time` and `DateTime` objects, and later coerced to strings by the renderer.
You can modify this behavior globally by settings the existing `DATE_FORMAT`, `DATETIME_FORMAT` and `TIME_FORMAT` settings keys. Setting these values to `None` instead of their default value of `'iso-8859-1'` will result in native objects being returned in serializer data.
You can modify this behavior globally by settings the existing `DATE_FORMAT`, `DATETIME_FORMAT` and `TIME_FORMAT` settings keys. Setting these values to `None` instead of their default value of `'iso-8601'` will result in native objects being returned in serializer data.
REST_FRAMEWORK = {
# Return native `Date` and `Time` objects in `serializer.data`
@ -940,7 +940,7 @@ The default JSON renderer will return float objects for un-coerced `Decimal` ins
* The serializer `ChoiceField` does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.
* Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party "autocomplete" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand.
* Some of the default validation error messages were rewritten and might no longer be pre-translated. You can still [create language files with Django][django-localization] if you wish to localize them.
* `APIException` subclasses could previously take could previously take any arbitrary type in the `detail` argument. These exceptions now use translatable text strings, and as a result call `force_text` on the `detail` argument, which *must be a string*. If you need complex arguments to an `APIException` class, you should subclass it and override the `__init__()` method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.
* `APIException` subclasses could previously take any arbitrary type in the `detail` argument. These exceptions now use translatable text strings, and as a result call `force_text` on the `detail` argument, which *must be a string*. If you need complex arguments to an `APIException` class, you should subclass it and override the `__init__()` method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.
---
@ -957,9 +957,9 @@ The 3.1 release is planned to address improvements in the following components:
The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.
You can follow development on the GitHub site, where we use [milestones to indicate planning timescales](https://github.com/tomchristie/django-rest-framework/milestones).
You can follow development on the GitHub site, where we use [milestones to indicate planning timescales](https://github.com/encode/django-rest-framework/milestones).
[kickstarter]: http://kickstarter.com/projects/tomchristie/django-rest-framework-3
[sponsors]: http://www.django-rest-framework.org/topics/kickstarter-announcement/#sponsors
[mixins.py]: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py
[django-localization]: https://docs.djangoproject.com/en/dev/topics/i18n/translation/#localization-how-to-create-language-files
[kickstarter]: https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3
[sponsors]: https://www.django-rest-framework.org/community/kickstarter-announcement/#sponsors
[mixins.py]: https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py
[django-localization]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#localization-how-to-create-language-files

View File

@ -30,7 +30,7 @@ Note that as a result of this work a number of settings keys and generic view at
Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default.
The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for [this blog post](http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api/) on the subject.
The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for [this blog post](https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api) on the subject.
#### Pagination controls in the browsable API.
@ -61,7 +61,7 @@ For example, when using `NamespaceVersioning`, and the following hyperlinked ser
class AccountsSerializer(serializer.HyperlinkedModelSerializer):
class Meta:
model = Accounts
fields = ('account_name', 'users')
fields = ['account_name', 'users']
The output representation would match the version used on the incoming request. Like so:
@ -110,11 +110,11 @@ When per-request internationalization is enabled, client requests will respect t
"detail": "No se ha podido satisfacer la solicitud de cabecera de Accept."
}
Note that the structure of the error responses is still the same. We still have a `details` key in the response. If needed you can modify this behavior too, by using a [custom exception handler][custom-exception-handler].
Note that the structure of the error responses is still the same. We still have a `detail` key in the response. If needed you can modify this behavior too, by using a [custom exception handler][custom-exception-handler].
We include built-in translations both for standard exception cases, and for serializer validation errors.
The full list of supported languages can be found on our [Transifex project page](https://www.transifex.com/projects/p/django-rest-framework/).
The full list of supported languages can be found on our [Transifex project page](https://www.transifex.com/django-rest-framework-1/django-rest-framework/).
If you only wish to support a subset of the supported languages, use Django's standard `LANGUAGES` setting:
@ -123,7 +123,7 @@ If you only wish to support a subset of the supported languages, use Django's st
('en', _('English')),
]
For more details, see the [internationalization documentation](internationalization.md).
For more details, see the [internationalization documentation][internationalization].
Many thanks to [Craig Blaszczyk](https://github.com/jakul) for helping push this through.
@ -153,16 +153,16 @@ For more information, see the documentation on [customizing field mappings][cust
We've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to `pip install` the new packages, and change any import paths.
We're making this change in order to help distribute the maintainance workload, and keep better focus of the core essentials of the framework.
We're making this change in order to help distribute the maintenance workload, and keep better focus of the core essentials of the framework.
The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained [Django OAuth toolkit](https://github.com/evonove/django-oauth-toolkit) has now been promoted as our recommended option for integrating OAuth support.
The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained [Django OAuth toolkit](https://github.com/jazzband/django-oauth-toolkit) has now been promoted as our recommended option for integrating OAuth support.
The following packages are now moved out of core and should be separately installed:
* OAuth - [djangorestframework-oauth](http://jpadilla.github.io/django-rest-framework-oauth/)
* XML - [djangorestframework-xml](http://jpadilla.github.io/django-rest-framework-xml)
* YAML - [djangorestframework-yaml](http://jpadilla.github.io/django-rest-framework-yaml)
* JSONP - [djangorestframework-jsonp](http://jpadilla.github.io/django-rest-framework-jsonp)
* OAuth - [djangorestframework-oauth](https://jpadilla.github.io/django-rest-framework-oauth/)
* XML - [djangorestframework-xml](https://jpadilla.github.io/django-rest-framework-xml/)
* YAML - [djangorestframework-yaml](https://jpadilla.github.io/django-rest-framework-yaml/)
* JSONP - [djangorestframework-jsonp](https://jpadilla.github.io/django-rest-framework-jsonp/)
It's worth reiterating that this change in policy shouldn't mean any work in your codebase other than adding a new requirement and modifying some import paths. For example to install XML rendering, you would now do:
@ -205,5 +205,5 @@ This will either be made as a single 3.2 release, or split across two separate r
[custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling
[pagination]: ../api-guide/pagination.md
[versioning]: ../api-guide/versioning.md
[internationalization]: internationalization.md
[internationalization]: ../topics/internationalization.md
[customizing-field-mappings]: ../api-guide/serializers.md#customizing-field-mappings

View File

@ -0,0 +1,148 @@
<style>
.promo li a {
float: left;
width: 130px;
height: 20px;
text-align: center;
margin: 10px 30px;
padding: 150px 0 0 0;
background-position: 0 50%;
background-size: 130px auto;
background-repeat: no-repeat;
font-size: 120%;
color: black;
}
.promo li {
list-style: none;
}
</style>
# Django REST framework 3.10
The 3.10 release drops support for Python 2.
* Our supported Python versions are now: 3.5, 3.6, and 3.7.
* Our supported Django versions are now: 1.11, 2.0, 2.1, and 2.2.
## OpenAPI Schema Generation
Since we first introduced schema support in Django REST Framework 3.5, OpenAPI has emerged as the widely adopted standard for modeling Web APIs.
This release begins the deprecation process for the CoreAPI based schema generation, and introduces OpenAPI schema generation in its place.
---
## Continuing to use CoreAPI
If you're currently using the CoreAPI schemas, you'll need to make sure to
update your REST framework settings to include `DEFAULT_SCHEMA_CLASS` explicitly.
**settings.py**:
```python
REST_FRAMEWORK = {
...: ...,
"DEFAULT_SCHEMA_CLASS": "rest_framework.schemas.coreapi.AutoSchema",
}
```
You'll still be able to keep using CoreAPI schemas, API docs, and client for the
foreseeable future. We'll aim to ensure that the CoreAPI schema generator remains
available as a third party package, even once it has eventually been removed
from REST framework, scheduled for version 3.12.
We have removed the old documentation for the CoreAPI based schema generation.
You may view the [Legacy CoreAPI documentation here][legacy-core-api-docs].
----
## OpenAPI Quickstart
You can generate a static OpenAPI schema, using the `generateschema` management
command.
Alternately, to have the project serve an API schema, use the `get_schema_view()`
shortcut.
In your `urls.py`:
```python
from rest_framework.schemas import get_schema_view
urlpatterns = [
# ...
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
# * `title` and `description` parameters are passed to `SchemaGenerator`.
# * Provide view name for use with `reverse()`.
path(
"openapi",
get_schema_view(title="Your Project", description="API for all things …"),
name="openapi-schema",
),
# ...
]
```
### Customization
For customizations that you want to apply across the entire API, you can subclass `rest_framework.schemas.openapi.SchemaGenerator` and provide it as an argument
to the `generateschema` command or `get_schema_view()` helper function.
For specific per-view customizations, you can subclass `AutoSchema`,
making sure to set `schema = <YourCustomClass>` on the view.
For more details, see the [API Schema documentation](../api-guide/schemas.md).
### API Documentation
There are some great third party options for documenting your API, based on the
OpenAPI schema.
See the [Documenting you API](../topics/documenting-your-api.md) section for more details.
---
## Feature Roadmap
Given that our OpenAPI schema generation is a new feature, it's likely that there
will still be some iterative improvements for us to make. There will be two
main cases here:
* Expanding the supported range of OpenAPI schemas that are generated by default.
* Improving the ability for developers to customize the output.
We'll aim to bring the first type of change quickly in point releases. For the
second kind we'd like to adopt a slower approach, to make sure we keep the API
simple, and as widely applicable as possible, before we bring in API changes.
It's also possible that we'll end up implementing API documentation and API client
tooling that are driven by the OpenAPI schema. The `apistar` project has a
significant amount of work towards this. However, if we do so, we'll plan
on keeping any tooling outside of the core framework.
---
## Funding
REST framework is a *collaboratively funded project*. If you use
REST framework commercially we strongly encourage you to invest in its
continued development by **[signing up for a paid plan][funding]**.
*Every single sign-up helps us make REST framework long-term financially sustainable.*
<ul class="premium-promo promo">
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
<li><a href="https://software.esg-usa.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/esg-new-logo.png)">ESG</a></li>
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
<li><a href="https://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
<li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless-plus-text.png)">Kloudless</a></li>
<li><a href="https://lightsonsoftware.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/lightson-dark.png)">Lights On Software</a></li>
</ul>
<div style="clear: both; padding-bottom: 20px;"></div>
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), and [Lights On Software](https://lightsonsoftware.com).*
[legacy-core-api-docs]:https://github.com/encode/django-rest-framework/blob/3.14.0/docs/coreapi/index.md
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[funding]: funding.md

View File

@ -0,0 +1,118 @@
<style>
.promo li a {
float: left;
width: 130px;
height: 20px;
text-align: center;
margin: 10px 30px;
padding: 150px 0 0 0;
background-position: 0 50%;
background-size: 130px auto;
background-repeat: no-repeat;
font-size: 120%;
color: black;
}
.promo li {
list-style: none;
}
</style>
# Django REST framework 3.11
The 3.11 release adds support for Django 3.0.
* Our supported Python versions are now: 3.5, 3.6, 3.7, and 3.8.
* Our supported Django versions are now: 1.11, 2.0, 2.1, 2.2, and 3.0.
This release will be the last to support Python 3.5 or Django 1.11.
## OpenAPI Schema Generation Improvements
The OpenAPI schema generation continues to mature. Some highlights in 3.11
include:
* Automatic mapping of Django REST Framework renderers and parsers into OpenAPI
request and response media-types.
* Improved mapping JSON schema mapping types, for example in HStoreFields, and
with large integer values.
* Porting of the old CoreAPI parsing of docstrings to form OpenAPI operation
descriptions.
In this example view operation descriptions for the `get` and `post` methods will
be extracted from the class docstring:
```python
class DocStringExampleListView(APIView):
"""
get: A description of my GET operation.
post: A description of my POST operation.
"""
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get(self, request, *args, **kwargs):
...
def post(self, request, *args, **kwargs):
...
```
## Validator / Default Context
In some circumstances a Validator class or a Default class may need to access the serializer field with which it is called, or the `.context` with which the serializer was instantiated. In particular:
* Uniqueness validators need to be able to determine the name of the field to which they are applied, in order to run an appropriate database query.
* The `CurrentUserDefault` needs to be able to determine the context with which the serializer was instantiated, in order to return the current user instance.
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.
The `__call__` method should then include an additional `serializer_field` argument.
Validator implementations will look like this:
```python
class CustomValidator:
requires_context = True
def __call__(self, value, serializer_field):
...
```
Default implementations will look like this:
```python
class CustomDefault:
requires_context = True
def __call__(self, serializer_field):
...
```
---
## Funding
REST framework is a *collaboratively funded project*. If you use
REST framework commercially we strongly encourage you to invest in its
continued development by **[signing up for a paid plan][funding]**.
*Every single sign-up helps us make REST framework long-term financially sustainable.*
<ul class="premium-promo promo">
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
<li><a href="https://software.esg-usa.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/esg-new-logo.png)">ESG</a></li>
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
<li><a href="https://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
<li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless-plus-text.png)">Kloudless</a></li>
<li><a href="https://lightsonsoftware.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/lightson-dark.png)">Lights On Software</a></li>
<li><a href="https://retool.com/?utm_source=djangorest&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/retool-sidebar.png)">Retool</a></li>
</ul>
<div style="clear: both; padding-bottom: 20px;"></div>
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), and [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship).*
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[funding]: funding.md

View File

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

View File

@ -0,0 +1,55 @@
<style>
.promo li a {
float: left;
width: 130px;
height: 20px;
text-align: center;
margin: 10px 30px;
padding: 150px 0 0 0;
background-position: 0 50%;
background-size: 130px auto;
background-repeat: no-repeat;
font-size: 120%;
color: black;
}
.promo li {
list-style: none;
}
</style>
# Django REST framework 3.13
## Django 4.0 support
The latest release now fully supports Django 4.0.
Our requirements are now:
* Python 3.6+
* Django 4.0, 3.2, 3.1, 2.2 (LTS)
## Fields arguments are now keyword-only
When instantiating fields on serializers, you should always use keyword arguments,
such as `serializers.CharField(max_length=200)`. This has always been the case,
and all the examples that we have in the documentation use keyword arguments,
rather than positional arguments.
From REST framework 3.13 onwards, this is now *explicitly enforced*.
The most feasible cases where users might be accidentally omitting the keyword arguments
are likely in the composite fields, `ListField` and `DictField`. For instance...
```python
aliases = serializers.ListField(serializers.CharField())
```
They must now use the more explicit keyword argument style...
```python
aliases = serializers.ListField(child=serializers.CharField())
```
This change has been made because using positional arguments here *does not* result in the expected behaviour.
See Pull Request [#7632](https://github.com/encode/django-rest-framework/pull/7632) for more details.

View File

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

@ -0,0 +1,113 @@
# Django REST framework 3.2
The 3.2 release is the first version to include an admin interface for the browsable API.
![The AdminRenderer](../img/admin.png)
This interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing `BrowsableAPIRenderer`, or used together with it, allowing you to switch between the two styles as required.
We've also fixed a huge number of issues, and made numerous cleanups and improvements.
Over the course of the 3.1.x series we've [resolved nearly 600 tickets](https://github.com/encode/django-rest-framework/issues?utf8=%E2%9C%93&q=closed%3A%3E2015-03-05) on our GitHub issue tracker. This means we're currently running at a rate of **closing around 100 issues or pull requests per month**.
None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking [a look through our sponsors](https://www.django-rest-framework.org/community/kickstarter-announcement/#sponsors) and finding out who's hiring.
## AdminRenderer
To include `AdminRenderer` simply add it to your settings:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.AdminRenderer',
'rest_framework.renderers.BrowsableAPIRenderer'
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 100
}
There are some limitations to the `AdminRenderer`, in particular it is not yet able to handle list or dictionary inputs, as we do not have any HTML form fields that support those.
Also note that this is an initial release and we do not yet have a public API for modifying the behavior or documentation on overriding the templates.
The idea is to get this released to users early, so we can start getting feedback and release a more fully featured version in 3.3.
## Supported versions
This release drops support for Django 1.4.
Our supported Django versions are now 1.5.6+, 1.6.3+, 1.7 and 1.8.
## Deprecations
There are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy.
* `request.DATA` was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of `request.data` instead.
* `request.QUERY_PARAMS` was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of `request.query_params` instead.
* The following `ModelSerializer.Meta` options have now been removed: `write_only_fields`, `view_name`, `lookup_field`. Use the more general `extra_kwargs` option instead.
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly in 'pending deprecation', and has now escalated to 'deprecated'. They will continue to function but will raise errors.
* `view.paginate_by` - Use `paginator.page_size` instead.
* `view.page_query_param` - Use `paginator.page_query_param` instead.
* `view.paginate_by_param` - Use `paginator.page_size_query_param` instead.
* `view.max_paginate_by` - Use `paginator.max_page_size` instead.
* `settings.PAGINATE_BY` - Use `paginator.page_size` instead.
* `settings.PAGINATE_BY_PARAM` - Use `paginator.page_size_query_param` instead.
* `settings.MAX_PAGINATE_BY` - Use `paginator.max_page_size` instead.
## Modifications to list behaviors
There are a couple of bug fixes that are worth calling out as they introduce differing behavior.
These are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project.
### 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.
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.
Previously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has `blank=True` set.
Here's what the mapping looks like in practice:
* `models.ManyToManyField()``serializers.PrimaryKeyRelatedField(many=True, allow_empty=False)`
* `models.ManyToManyField(blank=True)``serializers.PrimaryKeyRelatedField(many=True)`
The upshot is this: If you have many to many fields in your models, then make sure you've included the argument `blank=True` if you want to allow empty inputs in the equivalent `ModelSerializer` fields.
### List fields and allow_null
When using `allow_null` with `ListField` or a nested `many=True` serializer the previous behavior was to allow `null` values as items in the list. The behavior is now to allow `null` values instead of the list.
For example, take the following field:
NestedSerializer(many=True, allow_null=True)
Previously the validation behavior would be:
* `[{…}, null, {…}]` is **valid**.
* `null` is **invalid**.
Our validation behavior as of 3.2.0 is now:
* `[{…}, null, {…}]` is **invalid**.
* `null` is **valid**.
If you want to allow `null` child items, you'll need to instead specify `allow_null` on the child class, using an explicit `ListField` instead of `many=True`. For example:
ListField(child=NestedSerializer(allow_null=True))
## What's next?
The 3.3 release is currently planned for the start of October, and will be the last Kickstarter-funded release.
This release is planned to include:
* Search and filtering controls in the browsable API and admin interface.
* Improvements and public API for the admin interface.
* Improvements and public API for our templated HTML forms and fields.
* Nested object and list support in HTML forms.
Thanks once again to all our sponsors and supporters.

View File

@ -0,0 +1,60 @@
# Django REST framework 3.3
The 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding **thank you** to all our wonderful sponsors and supporters.
The amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned & refined large parts of the project.
In order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow [@_tomchristie](https://twitter.com/_tomchristie) to keep up to date with these announcements, and be among the first set of sign ups.
We strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished & professional product.
---
## Release notes
Significant new functionality in the 3.3 release includes:
* Filters presented as HTML controls in the browsable API.
* A [forms API][forms-api], allowing serializers to be rendered as HTML forms.
* Django 1.9 support.
* A [`JSONField` serializer field][jsonfield], corresponding to Django 1.9's Postgres `JSONField` model field.
* Browsable API support [via AJAX][ajax-form], rather than server side request overloading.
![Filter Controls](../img/filter-controls.png)
*Example of the new filter controls*
---
## Supported versions
This release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required.
This brings our supported versions into line with Django's [currently supported versions][django-supported-versions]
## Deprecations
The AJAX based support for the browsable API means that there are a number of internal cleanups in the `request` class. For the vast majority of developers this should largely remain transparent:
* To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.
* The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class][accept-headers].
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.
* `view.paginate_by` - Use `paginator.page_size` instead.
* `view.page_query_param` - Use `paginator.page_query_param` instead.
* `view.paginate_by_param` - Use `paginator.page_size_query_param` instead.
* `view.max_paginate_by` - Use `paginator.max_page_size` instead.
* `settings.PAGINATE_BY` - Use `paginator.page_size` instead.
* `settings.PAGINATE_BY_PARAM` - Use `paginator.page_size_query_param` instead.
* `settings.MAX_PAGINATE_BY` - Use `paginator.max_page_size` instead.
The `ModelSerializer` and `HyperlinkedModelSerializer` classes should now include either a `fields` or `exclude` option, although the `fields = '__all__'` shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings `ModelSerializer` more closely in line with Django's `ModelForm` behavior.
[forms-api]: ../topics/html-and-forms.md
[ajax-form]: https://github.com/encode/ajax-form
[jsonfield]: ../api-guide/fields#jsonfield
[accept-headers]: ../topics/browser-enhancements.md#url-based-accept-headers
[method-override]: ../topics/browser-enhancements.md#http-header-based-method-overriding
[django-supported-versions]: https://www.djangoproject.com/download/#supported-versions

View File

@ -0,0 +1,194 @@
<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.4
The 3.4 release is the first in a planned series that will be addressing schema
generation, hypermedia support, API clients, and finally realtime support.
---
## Funding
The 3.4 release has been made possible a recent [Mozilla grant][moss], and by our
[collaborative funding model][funding]. If you use REST framework commercially, and would
like to see this work continue, we strongly encourage you to invest in its
continued development by **[signing up for a paid plan][funding]**.
The initial aim is to provide a single full-time position on REST framework.
Right now we're over 60% of the way towards achieving that.
*Every single sign-up makes a significant impact.*
<ul class="premium-promo promo">
<li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
<li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
<li><a href="https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
</ul>
<div style="clear: both; padding-bottom: 20px;"></div>
*Many thanks to all our [awesome sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), and [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf).*
---
## Schemas & client libraries
REST framework 3.4 brings built-in support for generating API schemas.
We provide this support by using [Core API][core-api], a Document Object Model
for describing APIs.
Because Core API represents the API schema in an format-independent
manner, we're able to render the Core API `Document` object into many different
schema formats, by allowing the renderer class to determine how the internal
representation maps onto the external schema format.
This approach should also open the door to a range of auto-generated API
documentation options in the future, by rendering the `Document` object into
HTML documentation pages.
Alongside the built-in schema support, we're also now providing the following:
* A [command line tool][command-line-client] for interacting with APIs.
* A [Python client library][client-library] for interacting with APIs.
These API clients are dynamically driven, and able to interact with any API
that exposes a supported schema format.
Dynamically driven clients allow you to interact with an API at an application
layer interface, rather than a network layer interface, while still providing
the benefits of RESTful Web API design.
We're expecting to expand the range of languages that we provide client libraries
for over the coming months.
Further work on maturing the API schema support is also planned, including
documentation on supporting file upload and download, and improved support for
documentation generation and parameter annotation.
---
Current support for schema formats is as follows:
Name | Support | PyPI package
---------------------------------|-------------------------------------|--------------------------------
[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.
[API Blueprint][api-blueprint] | Not yet available. | Not yet available.
---
You can read more about any of this new functionality in the following:
* New tutorial section on [schemas & client libraries][tut-7].
* Documentation page on [schema generation][schema-generation].
* Topic page on [API clients][api-clients].
It is also worth noting that Marc Gibbons is currently working towards a 2.0 release of
the popular Django REST Swagger package, which will tie in with our new built-in support.
---
## Supported versions
The 3.4.0 release adds support for Django 1.10.
The following versions of Python and Django are now supported:
* Django versions 1.8, 1.9, and 1.10.
* Python versions 2.7, 3.2(\*), 3.3(\*), 3.4, 3.5.
(\*) Note that Python 3.2 and 3.3 are not supported from Django 1.9 onwards.
---
## Deprecations and changes
The 3.4 release includes very limited deprecation or behavioral changes, and
should present a straightforward upgrade.
### Use fields or exclude on serializer classes.
The following change in 3.3.0 is now escalated from "pending deprecation" to
"deprecated". Its usage will continue to function but will raise warnings:
`ModelSerializer` and `HyperlinkedModelSerializer` should include either a `fields`
option, or an `exclude` option. The `fields = '__all__'` shortcut may be used
to explicitly include all fields.
### Microsecond precision when returning time or datetime.
Using the default JSON renderer and directly returning a `datetime` or `time`
instance will now render with microsecond precision (6 digits), rather than
millisecond precision (3 digits). This makes the output format consistent with the
default string output of `serializers.DateTimeField` and `serializers.TimeField`.
This change *does not affect the default behavior when using serializers*,
which is to serialize `datetime` and `time` instances into strings with
microsecond precision.
The serializer behavior can be modified if needed, using the `DATETIME_FORMAT`
and `TIME_FORMAT` settings.
The renderer behavior can be modified by setting a custom `encoder_class`
attribute on a `JSONRenderer` subclass.
### Relational choices no longer displayed in OPTIONS requests.
Making an `OPTIONS` request to views that have a serializer choice field
will result in a list of the available choices being returned in the response.
In cases where there is a relational field, the previous behavior would be
to return a list of available instances to choose from for that relational field.
In order to minimise exposed information the behavior now is to *not* return
choices information for relational fields.
If you want to override this new behavior you'll need to [implement a custom
metadata class][metadata].
See [issue #3751][gh3751] for more information on this behavioral change.
---
## Other improvements
This release includes further work from a huge number of [pull requests and issues][milestone].
Many thanks to all our contributors who've been involved in the release, either through raising issues, giving feedback, improving the documentation, or suggesting and implementing code changes.
The full set of itemized release notes [are available here][release-notes].
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[moss]: mozilla-grant.md
[funding]: funding.md
[core-api]: https://www.coreapi.org/
[command-line-client]: api-clients#command-line-client
[client-library]: api-clients#python-client-library
[core-json]: https://www.coreapi.org/specification/encoding/#core-json-encoding
[swagger]: https://openapis.org/specification
[hyperschema]: https://json-schema.org/latest/json-schema-hypermedia.html
[api-blueprint]: https://apiblueprint.org/
[tut-7]: ../tutorial/7-schemas-and-client-libraries/
[schema-generation]: ../api-guide/schemas/
[api-clients]: 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
[gh3751]: https://github.com/encode/django-rest-framework/issues/3751

View File

@ -0,0 +1,262 @@
<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.5
The 3.5 release is the second in a planned series that is addressing schema
generation, hypermedia support, API client libraries, and finally realtime support.
---
## Funding
The 3.5 release would not have been possible without our [collaborative funding model][funding].
If you use REST framework commercially and would like to see this work continue,
we strongly encourage you to invest in its continued development by
**[signing up for a paid&nbsp;plan][funding]**.
<ul class="premium-promo promo">
<li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
<li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
<li><a href="https://getstream.io/?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://www.machinalis.com/#services" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</a></li>
</ul>
<div style="clear: both; padding-bottom: 20px;"></div>
*Many thanks to all our [sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), and [Machinalis](https://www.machinalis.com/#services).*
---
## Improved schema generation
Docstrings on views are now pulled through into schema definitions, allowing
you to [use the schema definition to document your&nbsp;API][schema-docs].
There is now also a shortcut function, `get_schema_view()`, which makes it easier to
[adding schema views][schema-view] to your API.
For example, to include a swagger schema to your API, you would do the following:
* Run `pip install django-rest-swagger`.
* Add `'rest_framework_swagger'` to your `INSTALLED_APPS` setting.
* Include the schema view in your URL conf:
```py
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]
)
urlpatterns = [path("swagger/", schema_view), ...]
```
There have been a large number of fixes to the schema generation. These should
resolve issues for anyone using the latest version of the `django-rest-swagger`
package.
Some of these changes do affect the resulting schema structure,
so if you're already using schema generation you should make sure to review
[the deprecation notes](#deprecations), particularly if you're currently using
a dynamic client library to interact with your API.
Finally, we're also now exposing the schema generation as a
[publicly documented API][schema-generation-api], allowing you to more easily
override the behaviour.
## Requests test client
You can now test your project using the `requests` library.
This exposes exactly the same interface as if you were using a standard
requests session instance.
client = RequestsClient()
response = client.get('http://testserver/users/')
assert response.status_code == 200
Rather than sending any HTTP requests to the network, this interface will
coerce all outgoing requests into WSGI, and call into your application directly.
## Core API client
You can also now test your project by interacting with it using the `coreapi`
client library.
# Fetch the API schema
client = CoreAPIClient()
schema = client.get('http://testserver/schema/')
# Create a new organisation
params = {'name': 'MegaCorp', 'status': 'active'}
client.action(schema, ['organisations', 'create'], params)
# Ensure that the organisation exists in the listing
data = client.action(schema, ['organisations', 'list'])
assert(len(data) == 1)
assert(data == [{'name': 'MegaCorp', 'status': 'active'}])
Again, this will call directly into the application using the WSGI interface,
rather than making actual network calls.
This is a good option if you are planning for clients to mainly interact with
your API using the `coreapi` client library, or some other auto-generated client.
## Live tests
One interesting aspect of both the `requests` client and the `coreapi` client
is that they allow you to write tests in such a way that they can also be made
to run against a live service.
By switching the WSGI based client instances to actual instances of `requests.Session`
or `coreapi.Client` you can have the test cases make actual network calls.
Being able to write test cases that can exercise your staging or production
environment is a powerful tool. However in order to do this, you'll need to pay
close attention to how you handle setup and teardown to ensure a strict isolation
of test data from other live or staging data.
## RAML support
We now have preliminary support for [RAML documentation generation][django-rest-raml].
![RAML Example][raml-image]
Further work on the encoding and documentation generation is planned, in order to
make features such as the 'Try it now' support available at a later date.
This work also now means that you can use the Core API client libraries to interact
with APIs that expose a RAML specification. The [RAML codec][raml-codec] gives some examples of
interacting with the Spotify API in this way.
## Validation codes
Exceptions raised by REST framework now include short code identifiers.
When used together with our customizable error handling, this now allows you to
modify the style of API error messages.
As an example, this allows for the following style of error responses:
{
"message": "You do not have permission to perform this action.",
"code": "permission_denied"
}
This is particularly useful with validation errors, which use appropriate
codes to identify differing kinds of failure...
{
"name": {"message": "This field is required.", "code": "required"},
"age": {"message": "A valid integer is required.", "code": "invalid"}
}
## Client upload & download support
The Python `coreapi` client library and the Core API command line tool both
now fully support file [uploads][uploads] and [downloads][downloads].
---
## Deprecations
### Generating schemas from Router
The router arguments for generating a schema view, such as `schema_title`,
are now pending deprecation.
Instead of using `DefaultRouter(schema_title='Example API')`, you should use
the `get_schema_view()` function, and include the view in your URL conf.
Make sure to include the view before your router urls. For example:
from rest_framework.schemas import get_schema_view
from my_project.routers import router
schema_view = get_schema_view(title='Example API')
urlpatterns = [
path('', schema_view),
path('', include(router.urls)),
]
### Schema path representations
The `'pk'` identifier in schema paths is now mapped onto the actually model field
name by default. This will typically be `'id'`.
This gives a better external representation for schemas, with less implementation
detail being exposed. It also reflects the behaviour of using a ModelSerializer
class with `fields = '__all__'`.
You can revert to the previous behaviour by setting `'SCHEMA_COERCE_PATH_PK': False`
in the REST framework settings.
### Schema action name representations
The internal `retrieve()` and `destroy()` method names are now coerced to an
external representation of `read` and `delete`.
You can revert to the previous behaviour by setting `'SCHEMA_COERCE_METHOD_NAMES': {}`
in the REST framework settings.
### DjangoFilterBackend
The functionality of the built-in `DjangoFilterBackend` is now completely
included by the `django-filter` package.
You should change your imports and REST framework filter settings as follows:
* `rest_framework.filters.DjangoFilterBackend` becomes `django_filters.rest_framework.DjangoFilterBackend`.
* `rest_framework.filters.FilterSet` becomes `django_filters.rest_framework.FilterSet`.
The existing imports will continue to work but are now pending deprecation.
### CoreJSON media type
The media type for `CoreJSON` is now `application/json+coreapi`, rather than
the previous `application/vnd.json+coreapi`. This brings it more into line with
other custom media types, such as those used by Swagger and RAML.
The clients currently accept either media type. The old style-media type will
be deprecated at a later date.
### ModelSerializer 'fields' and 'exclude'
ModelSerializer and HyperlinkedModelSerializer must include either a fields
option, or an exclude option. The `fields = '__all__'` shortcut may be used to
explicitly include all fields.
Failing to set either `fields` or `exclude` raised a pending deprecation warning
in version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.
---
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
[funding]: funding.md
[uploads]: https://core-api.github.io/python-client/api-guide/utils/#file
[downloads]: https://core-api.github.io/python-client/api-guide/codecs/#downloadcodec
[schema-generation-api]: ../api-guide/schemas/#schemagenerator
[schema-docs]: ../api-guide/schemas/#schemas-as-documentation
[schema-view]: ../api-guide/schemas/#the-get_schema_view-shortcut
[django-rest-raml]: https://github.com/encode/django-rest-raml
[raml-image]: ../img/raml.png
[raml-codec]: https://github.com/core-api/python-raml-codec

View File

@ -0,0 +1,199 @@
<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.6
The 3.6 release adds two major new features to REST framework.
1. Built-in interactive API documentation support.
2. A new JavaScript client&nbsp;library.
![API Documentation](/img/api-docs.gif)
*Above: The interactive API documentation.*
---
## Funding
The 3.6 release would not have been possible without our [backing from Mozilla](mozilla-grant.md) to the project, and our [collaborative funding&nbsp;model][funding].
If you use REST framework commercially and would like to see this work continue,
we strongly encourage you to invest in its continued development by
**[signing up for a paid&nbsp;plan][funding]**.
<ul class="premium-promo promo">
<li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
<li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
<li><a href="https://machinalis.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</a></li>
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar.png)">Rollbar</a></li>
<li><a href="https://micropyramid.com/django-rest-framework-development-services/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/mp-text-logo.png)">MicroPyramid</a></li>
</ul>
<div style="clear: both; padding-bottom: 20px;"></div>
*Many thanks to all our [sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), [Rollbar](https://rollbar.com), and [MicroPyramid](https://micropyramid.com/django-rest-framework-development-services/).*
---
## Interactive API documentation
REST framework's new API documentation supports a number of features:
* Live API interaction.
* Support for various authentication schemes.
* Code snippets for the Python, JavaScript, and Command Line clients.
The `coreapi` library is required as a dependency for the API docs. Make sure
to install the latest version (2.3.0 or above). The `pygments` and `markdown`
libraries are optional but recommended.
To install the API documentation, you'll need to include it in your projects URLconf:
from rest_framework.documentation import include_docs_urls
API_TITLE = 'API title'
API_DESCRIPTION = '...'
urlpatterns = [
...
path('docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))
]
Once installed you should see something a little like this:
![API Documentation](/img/api-docs.png)
We'll likely be making further refinements to the API documentation over the
coming weeks. Keep in mind that this is a new feature, and please do give
us feedback if you run into any issues or limitations.
For more information on documenting your API endpoints see the ["Documenting your API"][api-docs] section.
---
## JavaScript client library
The JavaScript client library allows you to load an API schema, and then interact
with that API at an application layer interface, rather than constructing fetch
requests explicitly.
Here's a brief example that demonstrates:
* Loading the client library and schema.
* Instantiating an authenticated client.
* Making an API request using the client.
**index.html**
<html>
<head>
<script src="/static/rest_framework/js/coreapi-0.1.0.js"></script>
<script src="/docs/schema.js"></script>
<script>
const coreapi = window.coreapi
const schema = window.schema
// Instantiate a client...
let auth = coreapi.auth.TokenAuthentication({scheme: 'JWT', token: 'xxx'})
let client = coreapi.Client({auth: auth})
// Make an API request...
client.action(schema, ['projects', 'list']).then(function(result) {
alert(result)
})
</script>
</head>
</html>
The JavaScript client library supports various authentication schemes, and can be
used by your project itself, or as an external client interacting with your API.
The client is not limited to usage with REST framework APIs, although it does
currently only support loading CoreJSON API schemas. Support for Swagger and
other API schemas is planned.
For more details see the [JavaScript client library documentation][js-docs].
## Authentication classes for the Python client library
Previous authentication support in the Python client library was limited to
allowing users to provide explicit header values.
We now have better support for handling the details of authentication, with
the introduction of the `BasicAuthentication`, `TokenAuthentication`, and
`SessionAuthentication` schemes.
You can include the authentication scheme when instantiating a new client.
auth = coreapi.auth.TokenAuthentication(scheme='JWT', token='xxx-xxx-xxx')
client = coreapi.Client(auth=auth)
For more information see the [Python client library documentation][py-docs].
---
## Deprecations
### Updating coreapi
If you're using REST framework's schema generation, or want to use the API docs,
then you'll need to update to the latest version of coreapi. (2.3.0)
### Generating schemas from Router
The 3.5 "pending deprecation" of router arguments for generating a schema view, such as `schema_title`, `schema_url` and `schema_renderers`, have now been escalated to a
"deprecated" warning.
Instead of using `DefaultRouter(schema_title='Example API')`, you should use the `get_schema_view()` function, and include the view explicitly in your URL conf.
### DjangoFilterBackend
The 3.5 "pending deprecation" warning of the built-in `DjangoFilterBackend` has now
been escalated to a "deprecated" warning.
You should change your imports and REST framework filter settings as follows:
* `rest_framework.filters.DjangoFilterBackend` becomes `django_filters.rest_framework.DjangoFilterBackend`.
* `rest_framework.filters.FilterSet` becomes `django_filters.rest_framework.FilterSet`.
---
## What's next
There are likely to be a number of refinements to the API documentation and
JavaScript client library over the coming weeks, which could include some of the following:
* Support for private API docs, requiring login.
* File upload and download support in the JavaScript client & API docs.
* Comprehensive documentation for the JavaScript client library.
* Automatically including authentication details in the API doc code snippets.
* Adding authentication support in the command line client.
* Support for loading Swagger and other schemas in the JavaScript client.
* Improved support for documenting parameter schemas and response schemas.
* Refining the API documentation interaction modal.
Once work on those refinements is complete, we'll be starting feature work
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]: 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

@ -0,0 +1,130 @@
<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.7
The 3.7 release focuses on improvements to schema generation and the interactive API documentation.
This release has been made possible by [Bayer](https://www.bayer.com/) who have sponsored the release.
<a href="https://www.bayer.com/"><img src="/img/bayer.png"/></a>
---
## Funding
If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by
**[signing up for a paid&nbsp;plan][funding]**.
<ul class="premium-promo promo">
<li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
<li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
<li><a href="https://machinalis.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</a></li>
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar.png)">Rollbar</a></li>
</ul>
<div style="clear: both; padding-bottom: 20px;"></div>
*As well as our release sponsor, we'd like to say thanks in particular our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), and [Rollbar](https://rollbar.com).*
---
## Customizing API docs & schema generation.
The schema generation introduced in 3.5 and the related API docs generation in 3.6 are both hugely powerful features, however they've been somewhat limited in cases where the view introspection isn't able to correctly identify the schema for a particular view.
In order to try to address this we're now adding the ability for per-view customization of the API schema. The interface that we're adding for this allows either basic manual overrides over which fields should be included on a view, or for more complex programmatic overriding of the schema generation. We believe this release comprehensively addresses some of the existing shortcomings of the schema features.
Let's take a quick look at using the new functionality...
The `APIView` class has a `schema` attribute, that is used to control how the Schema for that particular view is generated. The default behaviour is to use the `AutoSchema` class.
from rest_framework.views import APIView
from rest_framework.schemas import AutoSchema
class CustomView(APIView):
schema = AutoSchema() # Included for demonstration only. This is the default behavior.
We can remove a view from the API schema and docs, like so:
class CustomView(APIView):
schema = None
If we want to mostly use the default behavior, but additionally include some additional fields on a particular view, we can now do so easily...
class CustomView(APIView):
schema = AutoSchema(manual_fields=[
coreapi.Field('search', location='query')
])
To ignore the automatic generation for a particular view, and instead specify the schema explicitly, we use the `ManualSchema` class instead...
class CustomView(APIView):
schema = ManualSchema(fields=[...])
For more advanced behaviors you can subclass `AutoSchema` to provide for customized schema generation, and apply that to particular views.
class CustomView(APIView):
schema = CustomizedSchemaGeneration()
For full details on the new functionality, please see the [Schema Documentation][schema-docs].
---
## Django 2.0 support
REST framework 3.7 supports Django versions 1.10, 1.11, and 2.0 alpha.
---
## Minor fixes and improvements
There are a large number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing.
The number of [open tickets against the project](https://github.com/encode/django-rest-framework/issues) currently at its lowest number in quite some time, and we're continuing to focus on reducing these to a manageable amount.
---
## Deprecations
### `exclude_from_schema`
Both `APIView.exclude_from_schema` and the `exclude_from_schema` argument to the `@api_view` decorator and now `PendingDeprecation`. They will be moved to deprecated in the 3.8 release, and removed entirely in 3.9.
For `APIView` you should instead set a `schema = None` attribute on the view class.
For function based views the `@schema` decorator can be used to exclude the view from the schema, by using `@schema(None)`.
### `DjangoFilterBackend`
The `DjangoFilterBackend` was moved to pending deprecation in 3.5, and deprecated in 3.6. It has now been removed from the core framework.
The functionality remains fully available, but is instead provided in the `django-filter` package.
---
## What's next
We're still planning to work on improving real-time support for REST framework by providing documentation on integrating with Django channels, as well adding support for more easily adding WebSocket support to existing HTTP endpoints.
This will likely be timed so that any REST framework development here ties in with similar work on [API Star][api-star].
[funding]: funding.md
[schema-docs]: ../api-guide/schemas.md
[api-star]: https://github.com/encode/apistar

View File

@ -0,0 +1,97 @@
<style>
.promo li a {
float: left;
width: 130px;
height: 20px;
text-align: center;
margin: 10px 30px;
padding: 150px 0 0 0;
background-position: 0 50%;
background-size: 130px auto;
background-repeat: no-repeat;
font-size: 120%;
color: black;
}
.promo li {
list-style: none;
}
</style>
# Django REST framework 3.8
The 3.8 release is a maintenance focused release resolving a large number of previously outstanding issues and laying
the foundations for future changes.
---
## Funding
If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by
**[signing up for a paid&nbsp;plan][funding]**.
*We'd like to say thanks in particular our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), and [Rollbar](https://rollbar.com).*
---
## Breaking Changes
### Altered the behaviour of `read_only` plus `default` on Field.
[#5886][gh5886] `read_only` fields will now **always** be excluded from writable fields.
Previously `read_only` fields when combined with a `default` value would use the `default` for create and update
operations. This was counter-intuitive in some circumstances and led to difficulties supporting dotted `source`
attributes on nullable relations.
In order to maintain the old behaviour you may need to pass the value of `read_only` fields when calling `save()` in
the view:
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
Alternatively you may override `save()` or `create()` or `update()` on the serializer as appropriate.
---
## Deprecations
### `action` decorator replaces `list_route` and `detail_route`
[#5705][gh5705] `list_route` and `detail_route` have been merge into a single `action` decorator. This improves viewset action introspection, and will allow extra actions to be displayed in the Browsable API in future versions.
Both `list_route` and `detail_route` are now pending deprecation. They will be deprecated in 3.9 and removed entirely
in 3.10.
The new `action` decorator takes a boolean `detail` argument.
* Replace `detail_route` uses with `@action(detail=True)`.
* Replace `list_route` uses with `@action(detail=False)`.
### `exclude_from_schema`
Both `APIView.exclude_from_schema` and the `exclude_from_schema` argument to the `@api_view` decorator are now deprecated. They will be removed entirely in 3.9.
For `APIView` you should instead set a `schema = None` attribute on the view class.
For function based views the `@schema` decorator can be used to exclude the view from the schema, by using `@schema(None)`.
---
## Minor fixes and improvements
There are a large number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page
for a complete listing.
## What's next
We're currently working towards moving to using [OpenAPI][openapi] as our default schema output. We'll also be revisiting our API documentation generation and client libraries.
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
[funding]: funding.md
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886
[gh5705]: https://github.com/encode/django-rest-framework/issues/5705
[openapi]: https://www.openapis.org/

View File

@ -0,0 +1,210 @@
<style>
.promo li a {
float: left;
width: 130px;
height: 20px;
text-align: center;
margin: 10px 30px;
padding: 150px 0 0 0;
background-position: 0 50%;
background-size: 130px auto;
background-repeat: no-repeat;
font-size: 120%;
color: black;
}
.promo li {
list-style: none;
}
</style>
# Django REST framework 3.9
The 3.9 release gives access to _extra actions_ in the Browsable API, introduces composable permissions and built-in [OpenAPI][openapi] schema support. (Formerly known as Swagger)
---
## Funding
If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by
**[signing up for a paid&nbsp;plan][funding]**.
<ul class="premium-promo promo">
<li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
<li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
<li><a href="https://auklet.io" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/auklet-new.png)">Auklet</a></li>
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
<li><a href="https://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
<li><a href="https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/load-impact.png)">Load Impact</a></li>
<li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless.png)">Kloudless</a></li>
</ul>
<div style="clear: both; padding-bottom: 20px;"></div>
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Auklet](https://auklet.io/), [Rollbar](https://rollbar.com), [Cadre](https://cadre.com), [Load Impact](https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf), and [Kloudless](https://hubs.ly/H0f30Lf0).*
---
## Built-in OpenAPI schema support
REST framework now has a first-pass at directly including OpenAPI schema support. (Formerly known as Swagger)
Specifically:
* There are now `OpenAPIRenderer`, and `JSONOpenAPIRenderer` classes that deal with encoding `coreapi.Document` instances into OpenAPI YAML or OpenAPI JSON.
* The `get_schema_view(...)` method now defaults to OpenAPI YAML, with CoreJSON as a secondary
option if it is selected via HTTP content negotiation.
* There is a new management command `generateschema`, which you can use to dump
the schema into your repository.
Here's an example of adding an OpenAPI schema to the URL conf:
```python
from rest_framework.schemas import get_schema_view
from rest_framework.renderers import JSONOpenAPIRenderer
from django.urls import path
schema_view = get_schema_view(
title="Server Monitoring API",
url="https://www.example.org/api/",
renderer_classes=[JSONOpenAPIRenderer],
)
urlpatterns = [path("schema.json", schema_view), ...]
```
And here's how you can use the `generateschema` management command:
```shell
$ python manage.py generateschema --format openapi > schema.yml
```
There's lots of different tooling that you can use for working with OpenAPI
schemas. One option that we're working on is the [API Star](https://docs.apistar.com/)
command line tool.
You can use `apistar` to validate your API schema:
```shell
$ apistar validate --path schema.json --format openapi
✓ Valid OpenAPI schema.
```
Or to build API documentation:
```shell
$ apistar docs --path schema.json --format openapi
✓ Documentation built at "build/index.html".
```
API Star also includes a [dynamic client library](https://docs.apistar.com/client-library/)
that uses an API schema to automatically provide a client library interface for making requests.
## Composable permission classes
You can now compose permission classes using the and/or operators, `&` and `|`.
For example...
```python
permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)]
```
If you're using custom permission classes then make sure that you are subclassing
from `BasePermission` in order to enable this support.
## ViewSet _Extra Actions_ available in the Browsable API
Following the introduction of the `action` decorator in v3.8, _extra actions_ defined on a ViewSet are now available
from the Browsable API.
![Extra Actions displayed in the Browsable API](https://user-images.githubusercontent.com/2370209/32976956-1ca9ab7e-cbf1-11e7-981a-a20cb1e83d63.png)
When defined, a dropdown of "Extra Actions", appropriately filtered to detail/non-detail actions, is displayed.
---
## Supported Versions
REST framework 3.9 supports Django versions 1.11, 2.0, and 2.1.
---
## Deprecations
### `DjangoObjectPermissionsFilter` moved to third-party package.
The `DjangoObjectPermissionsFilter` class is pending deprecation, will be deprecated in 3.10 and removed entirely in 3.11.
It has been moved to the third-party [`djangorestframework-guardian`](https://github.com/rpkilby/django-rest-framework-guardian)
package. Please use this instead.
### Router argument/method renamed to use `basename` for consistency.
* The `Router.register` `base_name` argument has been renamed in favor of `basename`.
* The `Router.get_default_base_name` method has been renamed in favor of `Router.get_default_basename`. [#5990][gh5990]
See [#5990][gh5990].
[gh5990]: https://github.com/encode/django-rest-framework/pull/5990
`base_name` and `get_default_base_name()` are pending deprecation. They will be deprecated in 3.10 and removed entirely in 3.11.
### `action` decorator replaces `list_route` and `detail_route`
Both `list_route` and `detail_route` are now deprecated in favour of the single `action` decorator.
They will be removed entirely in 3.10.
The `action` decorator takes a boolean `detail` argument.
* Replace `detail_route` uses with `@action(detail=True)`.
* Replace `list_route` uses with `@action(detail=False)`.
### `exclude_from_schema`
Both `APIView.exclude_from_schema` and the `exclude_from_schema` argument to the `@api_view` have now been removed.
For `APIView` you should instead set a `schema = None` attribute on the view class.
For function-based views the `@schema` decorator can be used to exclude the view from the schema, by using `@schema(None)`.
---
## Minor fixes and improvements
There are a large number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing.
## What's next
We're planning to iteratively work towards OpenAPI becoming the standard schema
representation. This will mean that the `coreapi` dependency will gradually become
removed, and we'll instead generate the schema directly, rather than building
a CoreAPI `Document` object.
OpenAPI has clearly become the standard for specifying Web APIs, so there's not
much value any more in our schema-agnostic document model. Making this change
will mean that we'll more easily be able to take advantage of the full set of
OpenAPI functionality.
This will also make a wider range of tooling available.
We'll focus on continuing to develop the [API Star](https://docs.apistar.com/)
library and client tool into a recommended option for generating API docs,
validating API schemas, and providing a dynamic client library.
There's also a huge amount of ongoing work on maturing the ASGI landscape,
with the possibility that some of this work will eventually [feed back into
Django](https://www.aeracode.org/2018/06/04/django-async-roadmap/).
There will be further work on the [Uvicorn](https://www.uvicorn.org/)
web server, as well as lots of functionality planned for the [Starlette](https://www.starlette.io/)
web framework, which is building a foundational set of tooling for working with
ASGI.
[funding]: funding.md
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886
[gh5705]: https://github.com/encode/django-rest-framework/issues/5705
[openapi]: https://www.openapis.org/
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors

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,41 +28,39 @@ 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
To start developing on Django REST framework, clone the repo:
To start developing on Django REST framework, first create a Fork from the
[Django REST Framework repo][repo] on GitHub.
git clone git@github.com:tomchristie/django-rest-framework.git
Then clone your fork. The clone command will look like this, with your GitHub
username instead of YOUR-USERNAME:
git clone https://github.com/YOUR-USERNAME/django-rest-framework
See GitHub's [_Fork a Repo_][how-to-fork] Guide for more help.
Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.
You can check your contributions against these conventions each time you commit using the [pre-commit](https://pre-commit.com/) hooks, which we also run on CI.
To set them up, first ensure you have the pre-commit tool installed, for example:
python -m pip install pre-commit
Then run:
pre-commit install
## Testing
To run the tests, clone the repository, and then:
# Setup the virtual environment
virtualenv env
python3 -m venv env
source env/bin/activate
pip install -e .
pip install -r requirements.txt
# Run the tests
@ -72,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
@ -114,13 +102,13 @@ It's also useful to remember that if you have an outstanding pull request then p
GitHub's documentation for working on pull requests is [available here][pull-requests].
Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django.
Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible on all supported versions of Python and Django.
Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect.
Once you've made a pull request take a look at the build status in the GitHub interface and make sure the tests are running as you'd expect.
![Travis status][travis-status]
![Build status][build-status]
*Above: Travis build notifications*
*Above: build notifications*
## Managing compatibility issues
@ -197,15 +185,16 @@ If you want to draw attention to a note or warning, use a pair of enclosing line
---
[cite]: http://www.w3.org/People/Berners-Lee/FAQ.html
[cite]: https://www.w3.org/People/Berners-Lee/FAQ.html
[code-of-conduct]: https://www.djangoproject.com/conduct/
[google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[so-filter]: http://stackexchange.com/filters/66475/rest-framework
[issues]: https://github.com/tomchristie/django-rest-framework/issues?state=open
[pep-8]: http://www.python.org/dev/peps/pep-0008/
[travis-status]: ../img/travis-status.png
[so-filter]: https://stackexchange.com/filters/66475/rest-framework
[pep-8]: https://www.python.org/dev/peps/pep-0008/
[build-status]: ../img/build-status.png
[pull-requests]: https://help.github.com/articles/using-pull-requests
[tox]: http://tox.readthedocs.org/en/latest/
[markdown]: http://daringfireball.net/projects/markdown/basics
[docs]: https://github.com/tomchristie/django-rest-framework/tree/master/docs
[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/
[repo]: https://github.com/encode/django-rest-framework
[how-to-fork]: https://help.github.com/articles/fork-a-repo/

388
docs/community/funding.md Normal file
View File

@ -0,0 +1,388 @@
<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 keeping the package up to date.
* 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 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
Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.
---
## 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>

43
docs/community/jobs.md Normal file
View File

@ -0,0 +1,43 @@
# Jobs
Looking for a new Django REST Framework related role? On this site we provide a list of job resources that may be helpful. It's also worth checking out if any of [our sponsors are hiring][drf-funding].
## Places to look for Django REST Framework Jobs
* [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/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.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].
Wonder how else you can help? One of the best ways you can help Django REST Framework is to ask interviewers if their company is signed up for [REST Framework sponsorship][drf-funding] yet.
[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/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-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

@ -47,8 +47,8 @@ Our platinum sponsors have each made a hugely substantial contribution to the fu
</ul>
<ul class="sponsor platinum">
<li><a href="https://www.divio.ch/" rel="nofollow" style="background-image:url(../../img/sponsors/1-divio.png);">Divio</a></li>
<li><a href="http://company.onlulu.com/en/" rel="nofollow" style="background-image:url(../../img/sponsors/1-lulu.png);">Lulu</a></li>
<li><a href="https://www.divio.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-divio.png);">Divio</a></li>
<li><a href="https://onlulu.com" rel="nofollow" style="background-image:url(../../img/sponsors/1-lulu.png);">Lulu</a></li>
<li><a href="https://p.ota.to/" rel="nofollow" style="background-image:url(../../img/sponsors/1-potato.png);">Potato</a></li>
<li><a href="http://www.wiredrive.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-wiredrive.png);">Wiredrive</a></li>
<li><a href="http://www.cyaninc.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-cyan.png);">Cyan</a></li>
@ -72,27 +72,27 @@ Our gold sponsors include companies large and small. Many thanks for their signi
<li><a href="https://www.schubergphilis.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-schuberg_philis.png);">Schuberg Philis</a></li>
<li><a href="http://prorenata.se/" rel="nofollow" style="background-image:url(../../img/sponsors/2-prorenata.png);">ProReNata AB</a></li>
<li><a href="https://www.sgawebsites.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-sga.png);">SGA Websites</a></li>
<li><a href="http://www.sirono.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-sirono.png);">Sirono</a></li>
<li><a href="http://www.vinta.com.br/" rel="nofollow" style="background-image:url(../../img/sponsors/2-vinta.png);">Vinta Software Studio</a></li>
<li><a href="http://www.rapasso.nl/index.php/en" rel="nofollow" style="background-image:url(../../img/sponsors/2-rapasso.png);">Rapasso</a></li>
<li><a href="https://www.sirono.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-sirono.png);">Sirono</a></li>
<li><a href="https://www.vinta.com.br/" rel="nofollow" style="background-image:url(../../img/sponsors/2-vinta.png);">Vinta Software Studio</a></li>
<li><a href="https://www.rapasso.nl/" rel="nofollow" style="background-image:url(../../img/sponsors/2-rapasso.png);">Rapasso</a></li>
<li><a href="https://mirusresearch.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-mirus_research.png);">Mirus Research</a></li>
<li><a href="http://hipolabs.com" rel="nofollow" style="background-image:url(../../img/sponsors/2-hipo.png);">Hipo</a></li>
<li><a href="http://www.byte.nl" rel="nofollow" style="background-image:url(../../img/sponsors/2-byte.png);">Byte</a></li>
<li><a href="http://lightningkite.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-lightning_kite.png);">Lightning Kite</a></li>
<li><a href="https://hipolabs.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-hipo.png);">Hipo</a></li>
<li><a href="https://www.byte.nl/" rel="nofollow" style="background-image:url(../../img/sponsors/2-byte.png);">Byte</a></li>
<li><a href="https://www.lightningkite.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-lightning_kite.png);">Lightning Kite</a></li>
<li><a href="https://opbeat.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-opbeat.png);">Opbeat</a></li>
<li><a href="https://koordinates.com" rel="nofollow" style="background-image:url(../../img/sponsors/2-koordinates.png);">Koordinates</a></li>
<li><a href="http://pulsecode.ca" rel="nofollow" style="background-image:url(../../img/sponsors/2-pulsecode.png);">Pulsecode Inc.</a></li>
<li><a href="http://singinghorsestudio.com" rel="nofollow" style="background-image:url(../../img/sponsors/2-singing-horse.png);">Singing Horse Studio Ltd.</a></li>
<li><a rel="nofollow" style="background-image:url(../../img/sponsors/2-pulsecode.png);">Pulsecode Inc.</a></li>
<li><a rel="nofollow" style="background-image:url(../../img/sponsors/2-singing-horse.png);">Singing Horse Studio Ltd.</a></li>
<li><a href="https://www.heroku.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-heroku.png);">Heroku</a></li>
<li><a href="https://www.rheinwerk-verlag.de/" rel="nofollow" style="background-image:url(../../img/sponsors/2-rheinwerk_verlag.png);">Rheinwerk Verlag</a></li>
<li><a href="http://www.securitycompass.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-security_compass.png);">Security Compass</a></li>
<li><a href="https://www.securitycompass.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-security_compass.png);">Security Compass</a></li>
<li><a href="https://www.djangoproject.com/foundation/" rel="nofollow" style="background-image:url(../../img/sponsors/2-django.png);">Django Software Foundation</a></li>
<li><a href="http://www.hipflaskapp.com" rel="nofollow" style="background-image:url(../../img/sponsors/2-hipflask.png);">Hipflask</a></li>
<li><a href="http://www.crate.io/" rel="nofollow" style="background-image:url(../../img/sponsors/2-crate.png);">Crate</a></li>
<li><a href="http://crypticocorp.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-cryptico.png);">Cryptico Corp</a></li>
<li><a href="http://www.nexthub.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-nexthub.png);">NextHub</a></li>
<li><a rel="nofollow" style="background-image:url(../../img/sponsors/2-nexthub.png);">NextHub</a></li>
<li><a href="https://www.compile.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-compile.png);">Compile</a></li>
<li><a href="http://wusawork.org" rel="nofollow" style="background-image:url(../../img/sponsors/2-wusawork.png);">WusaWork</a></li>
<li><a rel="nofollow" style="background-image:url(../../img/sponsors/2-wusawork.png);">WusaWork</a></li>
<li><a href="http://envisionlinux.org/blog" rel="nofollow">Envision Linux</a></li>
</ul>
@ -102,41 +102,41 @@ Our gold sponsors include companies large and small. Many thanks for their signi
### Silver sponsors
The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank&nbsp;you to individuals who have choosen to privately support the project at this level.
The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank&nbsp;you to individuals who have chosen to privately support the project at this level.
<ul class="sponsor silver">
<li><a href="http://www.imtapps.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-imt_computer_services.png);">IMT Computer Services</a></li>
<li><a href="http://wildfish.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-wildfish.png);">Wildfish</a></li>
<li><a href="http://www.thermondo.de/" rel="nofollow" style="background-image:url(../../img/sponsors/3-thermondo-gmbh.png);">Thermondo GmbH</a></li>
<li><a href="http://providenz.fr/" rel="nofollow" style="background-image:url(../../img/sponsors/3-providenz.png);">Providenz</a></li>
<li><a href="https://www.imtapps.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-imt_computer_services.png);">IMT Computer Services</a></li>
<li><a href="https://wildfish.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-wildfish.png);">Wildfish</a></li>
<li><a href="https://www.thermondo.de/" rel="nofollow" style="background-image:url(../../img/sponsors/3-thermondo-gmbh.png);">Thermondo GmbH</a></li>
<li><a href="https://providenz.fr/" rel="nofollow" style="background-image:url(../../img/sponsors/3-providenz.png);">Providenz</a></li>
<li><a href="https://www.alwaysdata.com" rel="nofollow" style="background-image:url(../../img/sponsors/3-alwaysdata.png);">alwaysdata.com</a></li>
<li><a href="http://www.triggeredmessaging.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-triggered_messaging.png);">Triggered Messaging</a></li>
<li><a href="https://www.freshrelevance.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-triggered_messaging.png);">Triggered Messaging</a></li>
<li><a href="https://www.ipushpull.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-ipushpull.png);">PushPull Technology Ltd</a></li>
<li><a href="http://www.transcode.de/" rel="nofollow" style="background-image:url(../../img/sponsors/3-transcode.png);">Transcode</a></li>
<li><a href="https://garfo.io/" rel="nofollow" style="background-image:url(../../img/sponsors/3-garfo.png);">Garfo</a></li>
<li><a href="https://goshippo.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-shippo.png);">Shippo</a></li>
<li><a href="http://www.gizmag.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-gizmag.png);">Gizmag</a></li>
<li><a href="http://www.tivix.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-tivix.png);">Tivix</a></li>
<li><a href="http://www.safaribooksonline.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-safari.png);">Safari</a></li>
<li><a href="https://www.tivix.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-tivix.png);">Tivix</a></li>
<li><a href="https://www.safaribooksonline.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-safari.png);">Safari</a></li>
<li><a href="http://brightloop.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-brightloop.png);">Bright Loop</a></li>
<li><a href="http://www.aba-systems.com.au/" rel="nofollow" style="background-image:url(../../img/sponsors/3-aba.png);">ABA Systems</a></li>
<li><a href="http://beefarm.ru/" rel="nofollow" style="background-image:url(../../img/sponsors/3-beefarm.png);">beefarm.ru</a></li>
<li><a href="http://www.vzzual.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-vzzual.png);">Vzzual.com</a></li>
<li><a href="http://infinite-code.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-infinite_code.png);">Infinite Code</a></li>
<li><a href="http://crosswordtracker.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-crosswordtracker.png);">Crossword Tracker</a></li>
<li><a href="https://crosswordtracker.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-crosswordtracker.png);">Crossword Tracker</a></li>
<li><a href="https://www.pkgfarm.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-pkgfarm.png);">PkgFarm</a></li>
<li><a href="http://life.tl/" rel="nofollow" style="background-image:url(../../img/sponsors/3-life_the_game.png);">Life. The Game.</a></li>
<li><a href="http://blimp.io/" rel="nofollow" style="background-image:url(../../img/sponsors/3-blimp.png);">Blimp</a></li>
<li><a href="http://pathwright.com" rel="nofollow" style="background-image:url(../../img/sponsors/3-pathwright.png);">Pathwright</a></li>
<li><a href="http://fluxility.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-fluxility.png);">Fluxility</a></li>
<li><a href="http://teonite.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-teonite.png);">Teonite</a></li>
<li><a href="http://trackmaven.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-trackmaven.png);">TrackMaven</a></li>
<li><a href="http://www.phurba.net/" rel="nofollow" style="background-image:url(../../img/sponsors/3-phurba.png);">Phurba</a></li>
<li><a href="http://www.nephila.co.uk/" rel="nofollow" style="background-image:url(../../img/sponsors/3-nephila.png);">Nephila</a></li>
<li><a href="https://www.pathwright.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-pathwright.png);">Pathwright</a></li>
<li><a href="https://fluxility.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-fluxility.png);">Fluxility</a></li>
<li><a href="https://teonite.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-teonite.png);">Teonite</a></li>
<li><a href="https://trackmaven.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-trackmaven.png);">TrackMaven</a></li>
<li><a href="https://www.phurba.net/" rel="nofollow" style="background-image:url(../../img/sponsors/3-phurba.png);">Phurba</a></li>
<li><a href="https://www.nephila.it/it/" rel="nofollow" style="background-image:url(../../img/sponsors/3-nephila.png);">Nephila</a></li>
<li><a href="http://www.aditium.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-aditium.png);">Aditium</a></li>
<li><a href="http://www.eyesopen.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-openeye.png);">OpenEye Scientific Software</a></li>
<li><a href="https://www.eyesopen.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-openeye.png);">OpenEye Scientific Software</a></li>
<li><a href="https://holvi.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-holvi.png);">Holvi</a></li>
<li><a href="http://cantemo.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-cantemo.gif);">Cantemo</a></li>
<li><a href="https://www.cantemo.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-cantemo.gif);">Cantemo</a></li>
<li><a href="https://www.makespace.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-makespace.png);">MakeSpace</a></li>
<li><a href="https://www.ax-semantics.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-ax_semantics.png);">AX Semantics</a></li>
<li><a href="http://istrategylabs.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-isl.png);">ISL</a></li>
@ -144,7 +144,7 @@ The serious financial contribution that our silver sponsors have made is very mu
<div style="clear: both; padding-bottom: 40px;"></div>
**Individual backers**: Paul Hallett, <a href="http://www.paulwhippconsulting.com/">Paul Whipp</a>, Dylan Roy, Jannis Leidel, <a href="https://linovia.com/en/">Xavier Ordoquy</a>, <a href="http://spielmannsolutions.com/">Johannes Spielmann</a>, <a href="http://brooklynhacker.com/">Rob Spectre</a>, <a href="http://chrisheisel.com/">Chris Heisel</a>, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.
**Individual backers**: Paul Hallett, <a href="http://www.paulwhippconsulting.com/">Paul Whipp</a>, Dylan Roy, Jannis Leidel, <a href="https://linovia.com/en/">Xavier Ordoquy</a>, <a href="http://spielmannsolutions.com/">Johannes Spielmann</a>, <a href="http://brooklynhacker.com/">Rob Spectre</a>, <a href="https://chrisheisel.com/">Chris Heisel</a>, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.
---

View File

@ -0,0 +1,67 @@
# Mozilla Grant
We have recently been [awarded a Mozilla grant](https://blog.mozilla.org/blog/2016/04/13/mozilla-open-source-support-moss-update-q1-2016/), in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with.
Additionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications.
The [Core API](https://www.coreapi.org/) project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with *any* API that exposes a supported schema or hypermedia format.
Specifically, the work includes:
## Client libraries
This work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation.
* Client library support in REST framework.
* Schema & hypermedia support for REST framework APIs.
* A test client, allowing you to write tests that emulate a client library interacting with your API.
* New tutorial sections on using client libraries to interact with REST framework APIs.
* Python client library.
* JavaScript client library.
* Command line client.
## Realtime APIs
The next goal is to build on the realtime support offered by Django Channels, adding support & documentation for building realtime API endpoints.
* Support for API subscription endpoints, using REST framework and Django Channels.
* New tutorial section on building realtime API endpoints with REST framework.
* Realtime support in the Python & Javascript client libraries.
## Accountability
In order to ensure that I can be fully focused on trying to secure a sustainable
& well-funded open source business I will be leaving my current role at [DabApps](https://www.dabapps.com/)
at the end of May 2016.
I have formed a UK limited company, [Encode](https://www.encode.io/), which will
act as the business entity behind REST framework. I will be issuing monthly reports
from Encode on progress both towards the Mozilla grant, and for development time
funded via the [REST framework paid plans](funding.md).
<!-- 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-->

View File

@ -6,62 +6,20 @@
This document outlines our project management processes for REST framework.
The aim is to ensure that the project has a high
The aim is to ensure that the project has a high
["bus factor"][bus-factor], and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome.
---
## 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 Q1 2015](https://github.com/tomchristie/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/tomchristie/)
* [@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](http://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](http://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.
@ -97,10 +50,24 @@ The following template should be used for the description of the issue, and serv
Release manager is @***.
Pull request is #***.
During development cycle:
- [ ] Upload the new content to be translated to [transifex](https://www.django-rest-framework.org/topics/project-management/#translations).
Checklist:
- [ ] Create pull request for [release notes](https://github.com/tomchristie/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/tomchristie/django-rest-framework/milestones/***).
- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/__init__.py).
- [ ] Create pull request for [release notes](https://github.com/encode/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/encode/django-rest-framework/milestones/***).
- [ ] Update supported versions:
- [ ] `setup.py` `python_requires` list
- [ ] `setup.py` Python & Django version trove classifiers
- [ ] `README` Python & Django versions
- [ ] `docs` Python & Django versions
- [ ] Update the translations from [transifex](https://www.django-rest-framework.org/topics/project-management/#translations).
- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/__init__.py).
- [ ] 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.
@ -110,8 +77,8 @@ The following template should be used for the description of the issue, and serv
- [ ] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).
- [ ] Make a release announcement on twitter.
- [ ] Close the milestone on GitHub.
To modify this process for future releases make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation.
To modify this process for future releases make a pull request to the [project management](https://www.django-rest-framework.org/topics/project-management/) documentation.
When pushing the release to PyPI ensure that your environment has been installed from our development `requirement.txt`, so that documentation and PyPI installs are consistently being built against a pinned set of packages.
@ -141,7 +108,7 @@ When any user visible strings are changed, they should be uploaded to Transifex
# 1. Update the source django.po file, which is the US English version.
cd rest_framework
django-admin.py makemessages -l en_US
django-admin makemessages -l en_US
# 2. Push the source django.po file to Transifex.
cd ..
tx push -s
@ -159,10 +126,10 @@ Here's how differences between the old and new source files will be handled:
When a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run:
# 3. Pull the translated django.po files from Transifex.
tx pull -a
tx pull -a --minimum-perc 10
cd rest_framework
# 4. Compile the binary .mo files for all supported languages.
django-admin.py compilemessages
django-admin compilemessages
---
@ -184,17 +151,12 @@ If `@tomchristie` ceases to participate in the project then `@j4mie` has respons
The following issues still need to be addressed:
* [Consider moving the repo into a proper GitHub organization][github-org].
* Ensure `@jamie` has back-up access to the `django-rest-framework.org` domain setup and admin.
* Document ownership of the [live example][sandbox] API.
* 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]: http://en.wikipedia.org/wiki/Bus_factor
[un-triaged]: https://github.com/tomchristie/django-rest-framework/issues?q=is%3Aopen+no%3Alabel
[bus-factor]: https://en.wikipedia.org/wiki/Bus_factor
[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/
[transifex-client]: https://pypi.python.org/pypi/transifex-client
[transifex-client]: https://pypi.org/project/transifex-client/
[translation-memory]: http://docs.transifex.com/guides/tm#let-tm-automatically-populate-translations
[github-org]: https://github.com/tomchristie/django-rest-framework/issues/2162
[sandbox]: http://restframework.herokuapp.com/
[mailing-list]: https://groups.google.com/forum/#!forum/django-rest-framework

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,261 @@
# Third Party Packages
> Software ecosystems […] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.
>
> &mdash; [Jan Bosch][cite].
## About Third Party Packages
Third Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.
We **support**, **encourage** and **strongly favor** the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.
We aim to make creating third party packages as easy as possible, whilst keeping a **simple** and **well maintained** core API. By promoting third party packages we ensure that the responsibility for a package remains with its author. If a package proves suitably popular it can always be considered for inclusion into the core REST framework.
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].
## Creating a Third Party Package
### 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.
Check out Django REST framework's [compat.py][drf-compat] for an example.
### Once your package is available
Once your package is decently documented and available on PyPI, you might want share it with others that might find it useful.
#### Adding to the Django REST framework grid
We suggest adding your package to the [REST Framework][rest-framework-grid] grid on Django Packages.
#### Adding to the Django REST framework docs
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.
You can also let others know about your package through the [discussion group][discussion-group].
## Existing Third Party Packages
Django REST Framework has a growing community of developers, packages, and resources.
Check out a grid detailing all the packages and ecosystem around Django REST Framework at [Django Packages][rest-framework-grid].
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
* [djangorestframework-digestauth][djangorestframework-digestauth] - Provides Digest Access Authentication support.
* [django-oauth-toolkit][django-oauth-toolkit] - Provides OAuth 2.0 support.
* [djangorestframework-simplejwt][djangorestframework-simplejwt] - Provides JSON Web Token Authentication support.
* [hawkrest][hawkrest] - Provides Hawk HTTP Authorization.
* [djangorestframework-httpsignature][djangorestframework-httpsignature] - Provides an easy to use HTTP Signature Authentication mechanism.
* [djoser][djoser] - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.
* [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
* [drf-any-permissions][drf-any-permissions] - Provides alternative permission handling.
* [djangorestframework-composed-permissions][djangorestframework-composed-permissions] - Provides a simple way to define complex permissions.
* [rest_condition][rest-condition] - Another extension for building complex permissions in a simple and convenient way.
* [dry-rest-permissions][dry-rest-permissions] - Provides a simple way to define permissions for individual api actions.
* [drf-access-policy][drf-access-policy] - Declarative and flexible permissions inspired by AWS' IAM policies.
* [drf-psq][drf-psq] - An extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules.
### Serializers
* [django-rest-framework-mongoengine][django-rest-framework-mongoengine] - Serializer class that supports using MongoDB as the storage layer for Django REST framework.
* [djangorestframework-gis][djangorestframework-gis] - Geographic add-ons
* [djangorestframework-hstore][djangorestframework-hstore] - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.
* [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.
* [html-json-forms][html-json-forms] - Provides an algorithm and serializer to process HTML JSON Form submissions per the (inactive) spec.
* [django-rest-framework-serializer-extensions][drf-serializer-extensions] -
Enables black/whitelisting fields, and conditionally expanding child serializers on a per-view/request basis.
* [djangorestframework-queryfields][djangorestframework-queryfields] - Serializer mixin allowing clients to control which fields will be sent in the API response.
* [drf-flex-fields][drf-flex-fields] - Serializer providing dynamic field expansion and sparse field sets via URL parameters.
* [drf-action-serializer][drf-action-serializer] - Serializer providing per-action fields config for use with ViewSets to prevent having to write multiple serializers.
* [djangorestframework-dataclasses][djangorestframework-dataclasses] - Serializer providing automatic field generation for Python dataclasses, like the built-in ModelSerializer does for models.
* [django-restql][django-restql] - Turn your REST API into a GraphQL like API(It allows clients to control which fields will be sent in a response, uses GraphQL like syntax, supports read and write on both flat and nested fields).
* [graphwrap][graphwrap] - Transform your REST API into a fully compliant GraphQL API with just two lines of code. Leverages [Graphene-Django](https://docs.graphene-python.org/projects/django/en/latest/) to dynamically build, at runtime, a GraphQL ObjectType for each view in your API.
### Serializer fields
* [drf-compound-fields][drf-compound-fields] - Provides "compound" serializer fields, such as lists of simple values.
* [drf-extra-fields][drf-extra-fields] - Provides extra serializer fields.
* [django-versatileimagefield][django-versatileimagefield] - Provides a drop-in replacement for Django's stock `ImageField` that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, [click here][django-versatileimagefield-drf-docs].
### Views
* [django-rest-multiple-models][django-rest-multiple-models] - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
* [drf-typed-views][drf-typed-views] - Use Python type annotations to validate/deserialize request parameters. Inspired by API Star, Hug and FastAPI.
* [rest-framework-actions][rest-framework-actions] - Provides control over each action in ViewSets. Serializers per action, method.
### Routers
* [drf-nested-routers][drf-nested-routers] - Provides routers and relationship fields for working with nested resources.
* [wq.db.rest][wq.db.rest] - Provides an admin-style model registration API with reasonable default URLs and viewsets.
### Parsers
* [djangorestframework-msgpack][djangorestframework-msgpack] - Provides MessagePack renderer and parser support.
* [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
* [djangorestframework-camel-case][djangorestframework-camel-case] - Provides camel case JSON renderers and parsers.
* [nested-multipart-parser][nested-multipart-parser] - Provides nested parser for http multipart request
### Renderers
* [djangorestframework-csv][djangorestframework-csv] - Provides CSV renderer support.
* [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
* [drf_ujson2][drf_ujson2] - Implements JSON rendering using the UJSON package.
* [rest-pandas][rest-pandas] - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.
* [djangorestframework-rapidjson][djangorestframework-rapidjson] - Provides rapidjson support with parser and renderer.
### Filtering
* [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-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.
* [gaiarestframework][gaiarestframework] - Utils for django-rest-framework
* [drf-extensions][drf-extensions] - A collection of custom extensions
* [ember-django-adapter][ember-django-adapter] - An adapter for working with Ember.js
* [django-versatileimagefield][django-versatileimagefield] - Provides a drop-in replacement for Django's stock `ImageField` that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, [click here][django-versatileimagefield-drf-docs].
* [drf-tracking][drf-tracking] - Utilities to track requests to DRF API views.
* [drf_tweaks][drf_tweaks] - Serializers with one-step validation (and more), pagination without counts and other tweaks.
* [django-rest-framework-braces][django-rest-framework-braces] - Collection of utilities for working with Django Rest Framework. The most notable ones are [FormSerializer](https://django-rest-framework-braces.readthedocs.io/en/latest/overview.html#formserializer) and [SerializerForm](https://django-rest-framework-braces.readthedocs.io/en/latest/overview.html#serializerform), which are adapters between DRF serializers and Django forms.
* [drf-haystack][drf-haystack] - Haystack search for Django Rest Framework
* [django-rest-framework-version-transforms][django-rest-framework-version-transforms] - Enables the use of delta transformations for versioning of DRF resource representations.
* [django-rest-messaging][django-rest-messaging], [django-rest-messaging-centrifugo][django-rest-messaging-centrifugo] and [django-rest-messaging-js][django-rest-messaging-js] - A real-time pluggable messaging service using DRM.
* [djangorest-alchemy][djangorest-alchemy] - SQLAlchemy support for REST framework.
* [djangorestframework-datatables][djangorestframework-datatables] - Seamless integration between Django REST framework and [Datatables](https://datatables.net).
* [django-rest-framework-condition][django-rest-framework-condition] - Decorators for managing HTTP cache headers for Django REST framework (ETag and Last-modified).
* [django-rest-witchcraft][django-rest-witchcraft] - Provides DRF integration with SQLAlchemy with SQLAlchemy model serializers/viewsets and a bunch of other goodies
* [djangorestframework-mvt][djangorestframework-mvt] - An extension for creating views that serve Postgres data as Map Box Vector Tiles.
* [drf-viewset-profiler][drf-viewset-profiler] - Lib to profile all methods from a viewset line by line.
* [djangorestframework-features][djangorestframework-features] - Advanced schema generation and more based on named features.
* [django-elasticsearch-dsl-drf][django-elasticsearch-dsl-drf] - Integrate Elasticsearch DSL with Django REST framework. Package provides views, serializers, filter backends, pagination and other handy add-ons.
* [django-api-client][django-api-client] - DRF client that groups the Endpoint response, for use in CBVs and FBV as if you were working with Django's Native Models..
* [fast-drf] - A model based library for making API development faster and easier.
* [django-requestlogs] - Providing middleware and other helpers for audit logging for REST framework.
* [drf-standardized-errors][drf-standardized-errors] - DRF exception handler to standardize error responses for all API endpoints.
* [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/
[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
[authentication]: ../api-guide/authentication.md
[permissions]: ../api-guide/permissions.md
[third-party-packages]: ../topics/third-party-packages/#existing-third-party-packages
[discussion-group]: https://groups.google.com/forum/#!forum/django-rest-framework
[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
[django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
[djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt
[djangorestframework-simplejwt]: https://github.com/davesque/django-rest-framework-simplejwt
[hawkrest]: https://github.com/kumar303/hawkrest
[djangorestframework-httpsignature]: https://github.com/etoccalino/django-rest-framework-httpsignature
[djoser]: https://github.com/sunscrapers/djoser
[drf-any-permissions]: https://github.com/kevin-brown/drf-any-permissions
[djangorestframework-composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions
[rest-condition]: https://github.com/caxap/rest_condition
[django-rest-framework-mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine
[djangorestframework-gis]: https://github.com/djangonauts/django-rest-framework-gis
[djangorestframework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore
[drf-compound-fields]: https://github.com/estebistec/drf-compound-fields
[drf-extra-fields]: https://github.com/Hipo/drf-extra-fields
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
[wq.db.rest]: https://wq.io/docs/about-rest
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
[nested-multipart-parser]: https://github.com/remigermain/nested-multipart-parser
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
[drf_ujson2]: https://github.com/Amertz08/drf_ujson2
[rest-pandas]: https://github.com/wq/django-rest-pandas
[djangorestframework-rapidjson]: https://github.com/allisson/django-rest-framework-rapidjson
[djangorestframework-chain]: https://github.com/philipn/django-rest-framework-chain
[djangorestrelationalhyperlink]: https://github.com/fredkingham/django_rest_model_hyperlink_serializers_project
[django-rest-framework-proxy]: https://github.com/eofs/django-rest-framework-proxy
[gaiarestframework]: https://github.com/AppsFuel/gaiarestframework
[drf-extensions]: https://github.com/chibisov/drf-extensions
[ember-django-adapter]: https://github.com/dustinfarris/ember-django-adapter
[dj-rest-auth]: https://github.com/iMerica/dj-rest-auth
[django-versatileimagefield]: https://github.com/WGBH/django-versatileimagefield
[django-versatileimagefield-drf-docs]:https://django-versatileimagefield.readthedocs.io/en/latest/drf_integration.html
[drf-tracking]: https://github.com/aschn/drf-tracking
[django-rest-framework-braces]: https://github.com/dealertrack/django-rest-framework-braces
[dry-rest-permissions]: https://github.com/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
[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
[html-json-forms]: https://github.com/wq/html-json-forms
[django-rest-messaging]: https://github.com/raphaelgyory/django-rest-messaging
[django-rest-messaging-centrifugo]: https://github.com/raphaelgyory/django-rest-messaging-centrifugo
[django-rest-messaging-js]: https://github.com/raphaelgyory/django-rest-messaging-js
[drf_tweaks]: https://github.com/ArabellaTech/drf_tweaks
[drf-oidc-auth]: https://github.com/ByteInternet/drf-oidc-auth
[drf-serializer-extensions]: https://github.com/evenicoulddoit/django-rest-framework-serializer-extensions
[djangorestframework-queryfields]: https://github.com/wimglenn/djangorestframework-queryfields
[drfpasswordless]: https://github.com/aaronn/django-rest-framework-passwordless
[djangorest-alchemy]: https://github.com/dealertrack/djangorest-alchemy
[djangorestframework-datatables]: https://github.com/izimobil/django-rest-framework-datatables
[django-rest-framework-condition]: https://github.com/jozo/django-rest-framework-condition
[django-rest-witchcraft]: https://github.com/shosca/django-rest-witchcraft
[drf-access-policy]: https://github.com/rsinger86/drf-access-policy
[drf-flex-fields]: https://github.com/rsinger86/drf-flex-fields
[drf-typed-views]: https://github.com/rsinger86/drf-typed-views
[drf-action-serializer]: https://github.com/gregschmit/drf-action-serializer
[djangorestframework-dataclasses]: https://github.com/oxan/djangorestframework-dataclasses
[django-restql]: https://github.com/yezyilomo/django-restql
[djangorestframework-mvt]: https://github.com/corteva/djangorestframework-mvt
[django-rest-framework-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
[django-api-client]: https://github.com/rhenter/django-api-client
[drf-psq]: https://github.com/drf-psq/drf-psq
[django-rest-authemail]: https://github.com/celiao/django-rest-authemail
[graphwrap]: https://github.com/PaulGilmartin/graph_wrap
[rest-framework-actions]: https://github.com/AlexisMunera98/rest-framework-actions
[fast-drf]: https://github.com/iashraful/fast-drf
[django-requestlogs]: https://github.com/Raekkeri/django-requestlogs
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors
[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

@ -0,0 +1,140 @@
# Tutorials and Resources
There are a wide range of resources available for learning and using Django REST framework. We try to keep a comprehensive list available here.
## Books
<div class="book-covers">
<a class="book-cover" href="https://hellowebapp.com/order/">
<img src="../../img/books/hwa-cover.png"/>
</a>
<a class="book-cover" href="https://www.twoscoopspress.com/products/two-scoops-of-django-1-11">
<img src="../../img/books/tsd-cover.png"/>
</a>
<a class="book-cover" href="https://djangoforapis.com">
<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]
* [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]
* [Start Your API - Django REST Framework Part 1][start-your-api-django-rest-framework-part-1]
* [Permissions & Authentication - Django REST Framework Part 2][permissions-authentication-django-rest-framework-part-2]
* [ViewSets and Routers - Django REST Framework Part 3][viewsets-and-routers-django-rest-framework-part-3]
* [Django REST Framework User Endpoint][django-rest-framework-user-endpoint]
* [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]
* [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]
## Videos
### 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-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
* [Django REST Framework Part 1][django-rest-framework-part-1-video]
* [Django REST Framework in Your PJ's!][drf-in-your-pjs]
* [Building a REST API Using Django & Django REST Framework][building-a-rest-api-using-django-and-drf]
* [Blog API with Django REST Framework][blog-api-with-drf]
* [Ember and Django Part 1][ember-and-django-part 1-video]
* [Django REST Framework Image Upload Tutorial (with AngularJS)][drf-image-upload-tutorial-with-angularjs]
* [Django REST Framework Tutorials][drf-tutorials]
## Articles
* [Web API performance: Profiling Django REST Framework][web-api-performance-profiling-django-rest-framework]
* [API Development with Django and Django REST Framework][api-development-with-django-and-django-rest-framework]
* [Integrating Pandas, Django REST Framework and Bokeh][integrating-pandas-drf-and-bokeh]
* [Controlling Uncertainty on Web Applications and APIs][controlling-uncertainty-on-web-apps-and-apis]
* [Full Text Search in Django REST Framework with Database Backends][full-text-search-in-drf]
* [OAuth2 Authentication with Django REST Framework and Custom Third-Party OAuth2 Backends][oauth2-authentication-with-drf]
* [Nested Resources with Django REST Framework][nested-resources-with-drf]
* [Image Fields with Django REST Framework][image-fields-with-drf]
* [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]
* [DRF-schema-adapter][drf-schema]
Want your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please [submit a pull request][submit-pr] or [email us][anna-email]!
[beginners-guide-to-the-django-rest-framework]: https://code.tutsplus.com/tutorials/beginners-guide-to-the-django-rest-framework--cms-19786
[getting-started-with-django-rest-framework-and-angularjs]: https://blog.kevinastone.com/django-rest-framework-and-angular-js
[end-to-end-web-app-with-django-rest-framework-angularjs]: https://mourafiq.com/2013/07/01/end-to-end-web-app-with-django-angular-1.html
[start-your-api-django-rest-framework-part-1]: https://www.youtube.com/watch?v=hqo2kk91WpE
[permissions-authentication-django-rest-framework-part-2]: https://www.youtube.com/watch?v=R3xvUDUZxGU
[viewsets-and-routers-django-rest-framework-part-3]: https://www.youtube.com/watch?v=2d6w4DGQ4OU
[django-rest-framework-user-endpoint]: https://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/
[check-credentials-using-django-rest-framework]: https://richardtier.com/2014/03/06/110/
[ember-and-django-part 1-video]: http://www.neckbeardrepublic.com/screencasts/ember-and-django-part-1
[django-rest-framework-part-1-video]: http://www.neckbeardrepublic.com/screencasts/django-rest-framework-part-1
[web-api-performance-profiling-django-rest-framework]: https://www.dabapps.com/blog/api-performance-profiling-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
[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/
[controlling-uncertainty-on-web-apps-and-apis]: https://web.archive.org/web/20180104205043/https://machinalis.com/blog/controlling-uncertainty-on-web-applications-and-apis/
[full-text-search-in-drf]: https://web.archive.org/web/20180104205059/http://machinalis.com/blog/full-text-search-on-django-rest-framework/
[oauth2-authentication-with-drf]: https://web.archive.org/web/20180104205054/http://machinalis.com/blog/oauth2-authentication/
[nested-resources-with-drf]: https://web.archive.org/web/20180104205109/http://machinalis.com/blog/nested-resources-with-django/
[image-fields-with-drf]: https://web.archive.org/web/20180104205048/http://machinalis.com/blog/image-fields-with-django-rest-framework/
[chatbot-using-drf-part1]: https://chatbotslife.com/chatbot-using-django-rest-framework-api-ai-slack-part-1-3-69c7e38b7b1e#.g2aceuncf
[new-django-admin-with-drf-and-emberjs]: https://blog.levit.be/new-django-admin-with-emberjs-what-are-the-news/
[drf-schema]: https://drf-schema-adapter.readthedocs.io/en/latest/
[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-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
[drf-image-upload-tutorial-with-angularjs]: https://www.youtube.com/watch?v=hMiNTCIY7dw&list=PLUe5s-xycYk_X0vDjYBmKuIya2a2myF8O
[blog-api-with-drf]: https://www.youtube.com/watch?v=XMu0T6L2KRQ&list=PLEsfXFp6DpzTOcOVdZF-th7BS_GYGguAS
[drf-an-intro]: https://realpython.com/blog/python/django-rest-framework-quick-start/
[drf-tutorial]: https://tests4geeks.com/django-rest-framework-tutorial/
[building-a-restful-api-with-drf]: https://agiliq.com/blog/2014/12/building-a-restful-api-with-django-rest-framework/
[submit-pr]: https://github.com/encode/django-rest-framework
[anna-email]: mailto:anna@django-rest-framework.org
[pycon-us-2017]: https://www.youtube.com/watch?v=Rk6MHZdust4
[django-rest-react-valentinog]: https://www.valentinog.com/blog/tutorial-api-django-rest-react/
[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

BIN
docs/img/admin.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

BIN
docs/img/api-docs.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 MiB

BIN
docs/img/api-docs.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

BIN
docs/img/bayer.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 755 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

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

BIN
docs/img/drf-yasg.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

BIN
docs/img/horizontal.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
docs/img/inline.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

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