Commit Graph

995 Commits

Author SHA1 Message Date
Carlton Gibson
f54a220d8f
Corrected coreapi CLI code example generation. (#6428)
Remove “> “ when rendering template.
Closes #6333.
2019-01-31 11:36:40 +01: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
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
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
Alf
963ce306f3 Added "allow_unicode" to generated kwargs for ModelSerializer SlugField (#6315) 2018-12-19 15:37:52 +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
Mark Davidoff
1f13b6f6b2 use actual user instead of fake user in permission composition test 2018-10-29 10:45:40 -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
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
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
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
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
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
Ryan P Kilby
7f77340b33
Add Python 3.7 support (#6141) 2018-09-10 21:44:23 -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
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
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
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
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
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
Ryan P Kilby
1a170438d2 Add "optionals not required" build (#6047) 2018-06-22 10:16:57 +02:00
Daniel Hahler
a44cb67988 tests: fix usage of transaction.non_atomic_requests (#6043) 2018-06-21 14:44:58 -04: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
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
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
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
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
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
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
Ryan P Kilby
7078afa42c Change ISO 8601 date format to exclude year/month (#5936) 2018-04-14 05:23:31 +01: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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
06e2ad0b7d Remove unused compat._resolve_model() (#5733)
Last use removed in c674687782.
2018-01-08 09:19:08 +00: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
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
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
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
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
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
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
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
Ryan P Kilby
5c19652080 Fix whitespace in imports 2017-11-25 21:10:30 -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
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
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
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
Ryan P Kilby
ca341ef705 Add compat import test 2017-11-06 09:56:57 -05: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
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
Vasyl Dizhak
5d71d8d4b8 Increase test coverage for drf_create_token command (#5550) 2017-11-02 10:26:42 +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
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
91fa8b923a Stop JSONBoundField mangling invalid JSON (#5526) (#5527) 2017-10-25 10:54:38 +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
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
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
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
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
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
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
Kris Dorosz
60b9e58a12 Add support for page_size parameter in CursorPaginator class 2017-09-25 11:25:51 +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
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
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
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
Sergei Azarkin
9aaea2586b Fix authtoken managment command (#5415)
* Fix authtoken managment command username param
2017-09-12 14:03:29 +01:00
Ryan P Kilby
ae95ed1ec2 Add repr(value) to the assert msg in FieldValues 2017-09-11 05:18:39 -04: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
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
bc49746dd3 Fix test name 2017-08-31 08:26:14 -04: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
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
Ryan P Kilby
eb88687e28 Test RequestFactory with empty body 2017-08-22 15:02:18 -04: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