repo
stringclasses 856
values | pull_number
int64 3
127k
| instance_id
stringlengths 12
58
| issue_numbers
sequencelengths 1
5
| base_commit
stringlengths 40
40
| patch
stringlengths 67
1.54M
| test_patch
stringlengths 0
107M
| problem_statement
stringlengths 3
307k
| hints_text
stringlengths 0
908k
| created_at
timestamp[s] |
---|---|---|---|---|---|---|---|---|---|
encode/django-rest-framework | 5,833 | encode__django-rest-framework-5833 | [
"5821"
] | 2854679f563252f3ad398133bf16159049a4f0b3 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1212,8 +1212,9 @@ def to_representation(self, value):
if output_format is None or isinstance(value, six.string_types):
return value
+ value = self.enforce_timezone(value)
+
if output_format.lower() == ISO_8601:
- value = self.enforce_timezone(value)
value = value.isoformat()
if value.endswith('+00:00'):
value = value[:-6] + 'Z'
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -9,7 +9,7 @@
from django.http import QueryDict
from django.test import TestCase, override_settings
from django.utils import six
-from django.utils.timezone import activate, deactivate, utc
+from django.utils.timezone import activate, deactivate, override, utc
import rest_framework
from rest_framework import compat, serializers
@@ -1296,6 +1296,27 @@ def test_current_timezone(self):
assert self.field.default_timezone() == utc
[email protected](pytz is None, reason='pytz not installed')
+@override_settings(TIME_ZONE='UTC', USE_TZ=True)
+class TestCustomTimezoneForDateTimeField(TestCase):
+
+ @classmethod
+ def setup_class(cls):
+ cls.kolkata = pytz.timezone('Asia/Kolkata')
+ cls.date_format = '%d/%m/%Y %H:%M'
+
+ def test_should_render_date_time_in_default_timezone(self):
+ field = serializers.DateTimeField(default_timezone=self.kolkata, format=self.date_format)
+ dt = datetime.datetime(2018, 2, 8, 14, 15, 16, tzinfo=pytz.utc)
+
+ with override(self.kolkata):
+ rendered_date = field.to_representation(dt)
+
+ rendered_date_in_timezone = dt.astimezone(self.kolkata).strftime(self.date_format)
+
+ assert rendered_date == rendered_date_in_timezone
+
+
class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues):
"""
Invalid values for `DateTimeField` with datetime in DST shift (non-existing or ambiguous) and timezone with DST.
| Add failing test for to_representation with explicit default timezone
See discussion here:
https://github.com/encode/django-rest-framework/pull/5435#issuecomment-364054509
*Note*: Before submitting this pull request, please review our [contributing guidelines](https://github.com/encode/django-rest-framework/blob/master/CONTRIBUTING.md#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.
| 2018-02-16T14:30:29 |
|
encode/django-rest-framework | 5,849 | encode__django-rest-framework-5849 | [
"5848"
] | 6c0c69ed6546d24cf68edaecd5a8698553bfbe6a | diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -174,7 +174,7 @@ def get_attribute(self, instance):
pass
# Standard case, return the object instance.
- return get_attribute(instance, self.source_attrs)
+ return super(RelatedField, self).get_attribute(instance)
def get_choices(self, cutoff=None):
queryset = self.get_queryset()
| diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py
--- a/tests/test_model_serializer.py
+++ b/tests/test_model_serializer.py
@@ -23,6 +23,8 @@
from rest_framework import serializers
from rest_framework.compat import postgres_fields, unicode_repr
+from .models import NestedForeignKeySource
+
def dedent(blocktext):
return '\n'.join([line[12:] for line in blocktext.splitlines()[1:-1]])
@@ -1164,6 +1166,25 @@ class Meta:
class TestFieldSource(TestCase):
+ def test_traverse_nullable_fk(self):
+ """
+ A dotted source with nullable elements uses default when any item in the chain is None. #5849.
+
+ Similar to model example from test_serializer.py `test_default_for_multiple_dotted_source` method,
+ but using RelatedField, rather than CharField.
+ """
+ class TestSerializer(serializers.ModelSerializer):
+ target = serializers.PrimaryKeyRelatedField(
+ source='target.target', read_only=True, allow_null=True, default=None
+ )
+
+ class Meta:
+ model = NestedForeignKeySource
+ fields = ('target', )
+
+ model = NestedForeignKeySource.objects.create()
+ assert TestSerializer(model).data['target'] is None
+
def test_named_field_source(self):
class TestSerializer(serializers.ModelSerializer):
| RelatedField (and their subclasses) do not support traversing relationships that can be null
This was introduced by #5518, and while the solutions there work on normal fields, RelatedField behaves differently:
https://github.com/encode/django-rest-framework/blob/da535d31dd93dbb1d650e2e92bd0910ca8eb4ea4/rest_framework/fields.py#L440-L442
vs
https://github.com/encode/django-rest-framework/blob/da535d31dd93dbb1d650e2e92bd0910ca8eb4ea4/rest_framework/relations.py#L177
An example of the problem can be reproduced with https://gist.github.com/gcbirzan/a968facbaf0969f4a9616942de7022dc
A `Model1` instance with `None` for `model2` will produce an exception.
I believe that the correct behaviour is for `RelatedField.get_attribute` to call super.
As a side note, this is very hacky to work around, you'll need to copy paste the code from `RelatedField.get_attribute` in your class, then call the `Field.get_attribute`, since obviously super won't work.
If there's some agreement that this is the solution, I can fix it, but I'm not 100% sure (given the reaction on the original ticket) if this is considered a bug.
| 2018-02-23T13:57:51 |
|
encode/django-rest-framework | 5,872 | encode__django-rest-framework-5872 | [
"5871"
] | e3544f999e972188712b1e61ef01b22b1b815155 | diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py
--- a/rest_framework/metadata.py
+++ b/rest_framework/metadata.py
@@ -40,6 +40,7 @@ class SimpleMetadata(BaseMetadata):
serializers.BooleanField: 'boolean',
serializers.NullBooleanField: 'boolean',
serializers.CharField: 'string',
+ serializers.UUIDField: 'string',
serializers.URLField: 'url',
serializers.EmailField: 'email',
serializers.RegexField: 'regex',
| diff --git a/tests/test_metadata.py b/tests/test_metadata.py
--- a/tests/test_metadata.py
+++ b/tests/test_metadata.py
@@ -84,6 +84,7 @@ class ExampleSerializer(serializers.Serializer):
)
)
nested_field = NestedField()
+ uuid_field = serializers.UUIDField(label="UUID field")
class ExampleView(views.APIView):
"""Example view."""
@@ -172,7 +173,13 @@ def get_serializer(self):
'label': 'B'
}
}
- }
+ },
+ 'uuid_field': {
+ "type": "string",
+ "required": True,
+ "read_only": False,
+ "label": "UUID field",
+ },
}
}
}
| wrong schema generation for UUIDField
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
create model including UUIDField
models.py:
class Planning(models.Model):
uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False, verbose_name="UUID")
middleware = models.ForeignKey(Middleware, to_field='name',
verbose_name='Middleware', on_delete=models.CASCADE)
serializers.py:
class PlanningSerializer(serializers.ModelSerializer):
class Meta:
model = Planning
fields = '__all__'
## Expected behavior
meta for serializer should return
"actions": {
"POST": {
"uuid": {
"type": "string",
"required": true,
"read_only": false,
"label": "UUID"
},
## Actual behavior
meta for serializer returns
"actions": {
"POST": {
"uuid": {
"type": "field",
"required": false,
"read_only": true,
"label": "UUID"
},
| 2018-03-10T17:08:30 |
|
encode/django-rest-framework | 5,878 | encode__django-rest-framework-5878 | [
"5873"
] | 0da461710ad552c401a47b29b93e829ce879a696 | diff --git a/rest_framework/schemas/inspectors.py b/rest_framework/schemas/inspectors.py
--- a/rest_framework/schemas/inspectors.py
+++ b/rest_framework/schemas/inspectors.py
@@ -95,6 +95,8 @@ def field_to_schema(field):
description=description,
format='date-time'
)
+ elif isinstance(field, serializers.JSONField):
+ return coreschema.Object(title=title, description=description)
if field.style.get('base_template') == 'textarea.html':
return coreschema.String(
@@ -102,6 +104,7 @@ def field_to_schema(field):
description=description,
format='textarea'
)
+
return coreschema.String(title=title, description=description)
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -17,6 +17,7 @@
AutoSchema, ManualSchema, SchemaGenerator, get_schema_view
)
from rest_framework.schemas.generators import EndpointEnumerator
+from rest_framework.schemas.inspectors import field_to_schema
from rest_framework.schemas.utils import is_list_view
from rest_framework.test import APIClient, APIRequestFactory
from rest_framework.utils import formatting
@@ -763,6 +764,46 @@ class CustomView(APIView):
link = view.schema.get_link(path, method, base_url)
assert link == expected
+ def test_field_to_schema(self):
+ label = 'Test label'
+ help_text = 'This is a helpful test text'
+
+ cases = [
+ # tuples are ([field], [expected schema])
+ # TODO: Add remaining cases
+ (
+ serializers.BooleanField(label=label, help_text=help_text),
+ coreschema.Boolean(title=label, description=help_text)
+ ),
+ (
+ serializers.DecimalField(1000, 1000, label=label, help_text=help_text),
+ coreschema.Number(title=label, description=help_text)
+ ),
+ (
+ serializers.FloatField(label=label, help_text=help_text),
+ coreschema.Number(title=label, description=help_text)
+ ),
+ (
+ serializers.IntegerField(label=label, help_text=help_text),
+ coreschema.Integer(title=label, description=help_text)
+ ),
+ (
+ serializers.DateField(label=label, help_text=help_text),
+ coreschema.String(title=label, description=help_text, format='date')
+ ),
+ (
+ serializers.DateTimeField(label=label, help_text=help_text),
+ coreschema.String(title=label, description=help_text, format='date-time')
+ ),
+ (
+ serializers.JSONField(label=label, help_text=help_text),
+ coreschema.Object(title=label, description=help_text)
+ ),
+ ]
+
+ for case in cases:
+ self.assertEqual(field_to_schema(case[0]), case[1])
+
def test_docstring_is_not_stripped_by_get_description():
class ExampleDocstringAPIView(APIView):
| docs: JSON input to JSONField is not parsed correctly
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [ ] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
1. Create a JSONField on a serializer
2. Submit `{"a": "test"}` to the field through docs
3. Breakpoint at the return of `JSONField.to_internal_value()`
## Expected behavior
The returned data is a dictionary with a single key `a` that has a value which is string `test`.
## Actual behavior
The returned data is the string `{"a": "test"}`
| This verified on release version 3.7.7.
I have narrowed this down to the point where I am confident to conclude that the issue is that the `data-type` attribute is set to `string` on the input element of the `JSONField`. Setting `data-type` to `object` produce the desired behaviour. Now I just need to figure out how to do just that.
Hey @beruic. Thanks for the report.
Sounds like this will be coming out of `coreschema`. I'm just in the process of pulling that into DRF for v3.8 now. (#5855)
There issue will be here:
https://github.com/core-api/python-coreschema/blob/494435d8fbaff12285094e99c54c38f5a1434afb/coreschema/encodings/html.py#L54-L74
I'll see if I can close this whilst I'm porting this to DRF.
You are right that this is related to `coreschema`, but the fix lies in `rest_framework.schemas.inspectors.field_to_schema()`. I have solved this just now in DRF. Expect a pull request soon.
I cannot however fix it for `DictField`, which has the same problem with input, because `coreschema.schema.Object` does not have an `items` argument for child schema like `coreschema.schema.Array` does. I think that a `coreschema.schema.Dictionary` is needed because, while `coreschema.schema.Object` has a `properties` argument, it seems to validate per key. I was considering making a feature request for `coreschema`, but if I understand you correctly, that is not going to be necessary, but we have to fix it in DRF.
Thoughts? | 2018-03-13T15:12:59 |
encode/django-rest-framework | 5,888 | encode__django-rest-framework-5888 | [
"5708"
] | 12569f83c98004d9b254dc4c2f9f36ab8c479aec | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -442,10 +442,10 @@ def get_attribute(self, instance):
except (KeyError, AttributeError) as exc:
if self.default is not empty:
return self.get_default()
- if not self.required:
- raise SkipField()
if self.allow_null:
return None
+ if not self.required:
+ raise SkipField()
msg = (
'Got {exc_type} when attempting to get a value for field '
'`{field}` on serializer `{serializer}`.\nThe serializer '
| diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -384,14 +384,6 @@ def create(self, validated_data):
serializer.save()
assert serializer.data == {'included': 'abc'}
- def test_not_required_output_for_allow_null_field(self):
- class ExampleSerializer(serializers.Serializer):
- omitted = serializers.CharField(required=False, allow_null=True)
- included = serializers.CharField()
-
- serializer = ExampleSerializer({'included': 'abc'})
- assert 'omitted' not in serializer.data
-
class TestDefaultOutput:
def setup(self):
@@ -486,12 +478,16 @@ class Serializer(serializers.Serializer):
assert Serializer({'nested': {'a': '3', 'b': {'c': '4'}}}).data == {'nested': {'a': '3', 'c': '4'}}
def test_default_for_allow_null(self):
- # allow_null=True should imply default=None
+ """
+ Without an explicit default, allow_null implies default=None when serializing. #5518 #5708
+ """
class Serializer(serializers.Serializer):
foo = serializers.CharField()
bar = serializers.CharField(source='foo.bar', allow_null=True)
+ optional = serializers.CharField(required=False, allow_null=True)
- assert Serializer({'foo': None}).data == {'foo': None, 'bar': None}
+ # allow_null=True should imply default=None when serialising:
+ assert Serializer({'foo': None}).data == {'foo': None, 'bar': None, 'optional': None, }
class TestCacheSerializerData:
| not required read_only Fields with allow_null
## Description
Since #5639 we are unable to render fields that were rendered previously with `allow_null=True`.
Backward compatibility is not preserved, because `required=True` and `read_only=True` are conflicting, so in our case, some fields just disappeared and it seems there is no way to get them back.
I'm not sure about the fix, but the regression test is probably right.
| In hindsight, I think the behavior in #5639 is not correct. Fields with `required=False` and no explicit `default` are omitted from the serialized output, however, `allow_null` does imply a default *serialization* value, so it should be present in the output.
To reiterate, I'd argue that it's not correct for `allow_null` to imply a default for `required` fields, but not for non-required fields. Having this distinction makes the serialization model a little more difficult to reason about, and having an additional check for read-only fields would only make this more complicated.
Barring some reason for the distinction, I'm inclined to partially revert #5639.
@ticosax What was the behaviour before the 3.7.2 version? I've opened the #5639 because the #5518 brought backwards incompatible changes that broke code in an application of mine.
I'm not sure if the compatibility was broken at #5639 or it's a confusion with implicit values, but if it was broken at it, I think it is ok to reversed it.
I've provided more details of the why [here](https://github.com/encode/django-rest-framework/pull/5639#issuecomment-353984956).
@RomuloOliveira After #5639 we are unable include fields with `nullable=True`, because they are also `read-only`.
@ticosax Are these fields automatically generated by a `ModelSerializer`, or are you manually declaring these fields? If declared, I think you should be able to leave off `allow_null` on the `read_only` field. That said, It would help if you could provide an example serializer and initial data/instance.
> Are these fields automatically generated by a `ModelSerializer`, or are you manually declaring these fields?
declared.
> If declared, I think you should be able to leave off `allow_null` on the `read_only` field.
eventually. it doesn't change anything though. `SkipField()` is still raised.
> It would help if you could provide an example serializer and initial data/instance.
Sorry, I don't see how I could do better than the regression test this PR is adding. IMO there is everything you ask.
@rpkilby We've had a sequence of little changes here. Each time it's not been **exactly** clear what the supported use-cases and behaviours are. I think we need to review the history, write it up in black and white (for us and the docs) and make at most one more change to resolve this.
Do you have capacity to go over the history here and draw up an overview? If so that would be awesome. If not I'm happy to take that on.
@carltongibson Yep, I'd be happy to take that on.
Some findings in this regard:
1. `_writable_fields` includes fields which have a non-`empty` default (this is different from `None`): https://github.com/encode/django-rest-framework/blob/522d45354633f080288f82ebe1535ef4abbf0b6e/rest_framework/serializers.py#L367-L372
This causes a problem with a field like the following, where `allow_null` and `default` are added for recent changes in DRF to keep the field showing up:
```python
class Serializer(DefaultBaseHyperlinkedModelSerializer):
phone_numbers = serializers.JSONField(
source='profile.phone_numbers',
read_only=True,
# Because of https://github.com/encode/django-rest-framework/pull/5518
allow_null=True,
# XXX: causes field to show up in _writable_fields.
default=None,
)
```
e37619f7 added tests for this, but changed something else.
It basically causes `serializer.data['phone_numbers'] = None` to be turned into
`('profile', {'phone_numbers': None})` with `serializer.validated_data`.
The error then is:
```
File "…/Vcs/django-rest-framework/rest_framework/serializers.py", line 210, in save
self.instance = self.update(self.instance, validated_data)
File "…/app/serializers.py", line 195, in update
instance = super().update(instance, validated_data)
File "…/Vcs/django-rest-framework/rest_framework/serializers.py", line 958, in update
setattr(instance, attr, value)
File "…/Vcs/django/django/db/models/fields/related_descriptors.py", line 216, in __set__
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "{'phone_numbers': None}": "User.profile" must be a "UserProfile" instance.
```
Not having read_only fields in `_writable_fields` seems like a sensible thing to change?!
2. I've found a fix for our use case by changing `fields.get_attribute` to return `None` if a FK lookup fails (similar to when ObjectDoesNotExist would be raised for m2m). See https://github.com/encode/django-rest-framework/pull/5727.
Thanks for the writeup @blueyed.
I think this can be skipped/closed in favor of https://github.com/encode/django-rest-framework/pull/5727 - at least that's what is working for us now.
Thanks again @blueyed.
I'm leaving this to @rpkilby at the moment, as he's looking into the wider issue as per the discussion above. We'll resolve shortly. | 2018-03-20T13:00:16 |
encode/django-rest-framework | 5,904 | encode__django-rest-framework-5904 | [
"4556"
] | a95cffc73e1e88324cf451f884859d18867cce1b | diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py
--- a/rest_framework/exceptions.py
+++ b/rest_framework/exceptions.py
@@ -8,6 +8,7 @@
import math
+from django.http import JsonResponse
from django.utils import six
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
@@ -235,3 +236,23 @@ def __init__(self, wait=None, detail=None, code=None):
wait))))
self.wait = wait
super(Throttled, self).__init__(detail, code)
+
+
+def server_error(request, *args, **kwargs):
+ """
+ Generic 500 error handler.
+ """
+ data = {
+ 'error': 'Server Error (500)'
+ }
+ return JsonResponse(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+
+def bad_request(request, exception, *args, **kwargs):
+ """
+ Generic 400 error handler.
+ """
+ data = {
+ 'error': 'Bad Request (400)'
+ }
+ return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST)
| diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py
--- a/tests/test_exceptions.py
+++ b/tests/test_exceptions.py
@@ -1,11 +1,13 @@
+# -*- coding: utf-8 -*-
from __future__ import unicode_literals
-from django.test import TestCase
+from django.test import RequestFactory, TestCase
from django.utils import six, translation
from django.utils.translation import ugettext_lazy as _
from rest_framework.exceptions import (
- APIException, ErrorDetail, Throttled, _get_error_details
+ APIException, ErrorDetail, Throttled, _get_error_details, bad_request,
+ server_error
)
@@ -87,3 +89,18 @@ def test_message(self):
# this test largely acts as a sanity test to ensure the translation files are present.
self.assertEqual(_('A server error occurred.'), 'Une erreur du serveur est survenue.')
self.assertEqual(six.text_type(APIException()), 'Une erreur du serveur est survenue.')
+
+
+def test_server_error():
+ request = RequestFactory().get('/')
+ response = server_error(request)
+ assert response.status_code == 500
+ assert response["content-type"] == 'application/json'
+
+
+def test_bad_request():
+ request = RequestFactory().get('/')
+ exception = Exception('Something went wrong — Not used')
+ response = bad_request(request, exception)
+ assert response.status_code == 400
+ assert response["content-type"] == 'application/json'
| Technical error handlers
The default 404 and 500 error handlers return HTML. It'd be nice if we provided alternative error handlers that'd respond with either JSON or HTML as appropriate.
| I'm going to de-milestone this for now. It's clear enough. Happy to take a PR. etc. | 2018-03-27T10:09:33 |
encode/django-rest-framework | 5,921 | encode__django-rest-framework-5921 | [
"5918"
] | ffac61c6fe0f5b7054b803e919399d681aea674e | diff --git a/rest_framework/authtoken/views.py b/rest_framework/authtoken/views.py
--- a/rest_framework/authtoken/views.py
+++ b/rest_framework/authtoken/views.py
@@ -1,8 +1,7 @@
-import coreapi
-import coreschema
from rest_framework import parsers, renderers
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer
+from rest_framework.compat import coreapi, coreschema
from rest_framework.response import Response
from rest_framework.schemas import ManualSchema
from rest_framework.views import APIView
@@ -14,29 +13,30 @@ class ObtainAuthToken(APIView):
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
serializer_class = AuthTokenSerializer
- schema = ManualSchema(
- fields=[
- coreapi.Field(
- name="username",
- required=True,
- location='form',
- schema=coreschema.String(
- title="Username",
- description="Valid username for authentication",
+ if coreapi is not None and coreschema is not None:
+ schema = ManualSchema(
+ fields=[
+ coreapi.Field(
+ name="username",
+ required=True,
+ location='form',
+ schema=coreschema.String(
+ title="Username",
+ description="Valid username for authentication",
+ ),
),
- ),
- coreapi.Field(
- name="password",
- required=True,
- location='form',
- schema=coreschema.String(
- title="Password",
- description="Valid password for authentication",
+ coreapi.Field(
+ name="password",
+ required=True,
+ location='form',
+ schema=coreschema.String(
+ title="Password",
+ description="Valid password for authentication",
+ ),
),
- ),
- ],
- encoding="application/json",
- )
+ ],
+ encoding="application/json",
+ )
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
| diff --git a/tests/test_renderers.py b/tests/test_renderers.py
--- a/tests/test_renderers.py
+++ b/tests/test_renderers.py
@@ -14,8 +14,8 @@
from django.utils.safestring import SafeText
from django.utils.translation import ugettext_lazy as _
-import coreapi
from rest_framework import permissions, serializers, status
+from rest_framework.compat import coreapi
from rest_framework.renderers import (
AdminRenderer, BaseRenderer, BrowsableAPIRenderer, DocumentationRenderer,
HTMLFormRenderer, JSONRenderer, SchemaJSRenderer, StaticHTMLRenderer
| import coreapi failure since version 3.8.0
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Install django 2.0 with latest version of django-rest-framework via pip, and activate in settings.py
Try to open a shell and/or do:
`from rest_framework.authtoken import views`
## Expected behavior
Should just load the views module.
## Actual behavior
`ModuleNotFoundError: No module named 'coreapi'`
## Suggested fix
It seems like the `coreapi` module should no longer be optional, but should be a dependency that installs with a pip install -
https://github.com/encode/django-rest-framework/blob/2709de1310f35dda97fad28ccf555878f5646b17/requirements/requirements-optionals.txt#L7
| i have the same issue
Regression in 0d5a3a00b0465a27ecfa6947478cbd57ac2432f2. Ref #5676
Installing `coreapi` will work, but making it non-optional was not intended.
The import here should be from `compat`
https://github.com/encode/django-rest-framework/blob/bc353452f4a69304faf84e04f4cfaf827655f1f3/rest_framework/authtoken/views.py#L1-L39
And the `schema` declaration (ln17) needs to be only `if coreapi is not None:`
I'd take a PR on this very happily! 🙂
I'll supply a PR soon (in the next hour, hopefully). | 2018-04-05T12:51:11 |
encode/django-rest-framework | 5,927 | encode__django-rest-framework-5927 | [
"5807"
] | 7078afa42c1916823227287f6a6f60c104ebe3cd | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1614,7 +1614,8 @@ def get_value(self, dictionary):
if len(val) > 0:
# Support QueryDict lists in HTML input.
return val
- return html.parse_html_list(dictionary, prefix=self.field_name)
+ return html.parse_html_list(dictionary, prefix=self.field_name, default=empty)
+
return dictionary.get(self.field_name, empty)
def to_internal_value(self, data):
@@ -1622,7 +1623,7 @@ def to_internal_value(self, data):
List of dicts of native values <- List of dicts of primitive datatypes.
"""
if html.is_html_input(data):
- data = html.parse_html_list(data)
+ data = html.parse_html_list(data, default=[])
if isinstance(data, type('')) or isinstance(data, collections.Mapping) or not hasattr(data, '__iter__'):
self.fail('not_a_list', input_type=type(data).__name__)
if not self.allow_empty and len(data) == 0:
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -607,7 +607,7 @@ def get_value(self, dictionary):
# We override the default field access in order to support
# lists in HTML forms.
if html.is_html_input(dictionary):
- return html.parse_html_list(dictionary, prefix=self.field_name)
+ return html.parse_html_list(dictionary, prefix=self.field_name, default=empty)
return dictionary.get(self.field_name, empty)
def run_validation(self, data=empty):
@@ -635,7 +635,7 @@ def to_internal_value(self, data):
List of dicts of native values <- List of dicts of primitive datatypes.
"""
if html.is_html_input(data):
- data = html.parse_html_list(data)
+ data = html.parse_html_list(data, default=[])
if not isinstance(data, list):
message = self.error_messages['not_a_list'].format(
diff --git a/rest_framework/utils/html.py b/rest_framework/utils/html.py
--- a/rest_framework/utils/html.py
+++ b/rest_framework/utils/html.py
@@ -12,7 +12,7 @@ def is_html_input(dictionary):
return hasattr(dictionary, 'getlist')
-def parse_html_list(dictionary, prefix=''):
+def parse_html_list(dictionary, prefix='', default=None):
"""
Used to support list values in HTML forms.
Supports lists of primitives and/or dictionaries.
@@ -44,6 +44,8 @@ def parse_html_list(dictionary, prefix=''):
{'foo': 'abc', 'bar': 'def'},
{'foo': 'hij', 'bar': 'klm'}
]
+
+ :returns a list of objects, or the value specified in ``default`` if the list is empty
"""
ret = {}
regex = re.compile(r'^%s\[([0-9]+)\](.*)$' % re.escape(prefix))
@@ -59,7 +61,9 @@ def parse_html_list(dictionary, prefix=''):
ret[index][key] = value
else:
ret[index] = MultiValueDict({key: [value]})
- return [ret[item] for item in sorted(ret)]
+
+ # return the items of the ``ret`` dict, sorted by key, or ``default`` if the dict is empty
+ return [ret[item] for item in sorted(ret)] if ret else default
def parse_html_dict(dictionary, prefix=''):
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -466,6 +466,55 @@ class TestSerializer(serializers.Serializer):
assert serializer.is_valid()
assert serializer.validated_data == {'scores': [1]}
+ def test_querydict_list_input_no_values_uses_default(self):
+ """
+ When there are no values passed in, and default is set
+ The field should return the default value
+ """
+ class TestSerializer(serializers.Serializer):
+ a = serializers.IntegerField(required=True)
+ scores = serializers.ListField(default=lambda: [1, 3])
+
+ serializer = TestSerializer(data=QueryDict('a=1&'))
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'a': 1, 'scores': [1, 3]}
+
+ def test_querydict_list_input_supports_indexed_keys(self):
+ """
+ When data is passed in the format `scores[0]=1&scores[1]=3`
+ The field should return the correct list, ignoring the default
+ """
+ class TestSerializer(serializers.Serializer):
+ scores = serializers.ListField(default=lambda: [1, 3])
+
+ serializer = TestSerializer(data=QueryDict("scores[0]=5&scores[1]=6"))
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'scores': ['5', '6']}
+
+ def test_querydict_list_input_no_values_no_default_and_not_required(self):
+ """
+ When there are no keys passed, there is no default, and required=False
+ The field should be skipped
+ """
+ class TestSerializer(serializers.Serializer):
+ scores = serializers.ListField(required=False)
+
+ serializer = TestSerializer(data=QueryDict(''))
+ assert serializer.is_valid()
+ assert serializer.validated_data == {}
+
+ def test_querydict_list_input_posts_key_but_no_values(self):
+ """
+ When there are no keys passed, there is no default, and required=False
+ The field should return an array of 1 item, blank
+ """
+ class TestSerializer(serializers.Serializer):
+ scores = serializers.ListField(required=False)
+
+ serializer = TestSerializer(data=QueryDict('scores=&'))
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'scores': ['']}
+
class TestCreateOnlyDefault:
def setup(self):
diff --git a/tests/test_serializer_lists.py b/tests/test_serializer_lists.py
--- a/tests/test_serializer_lists.py
+++ b/tests/test_serializer_lists.py
@@ -1,3 +1,4 @@
+from django.http import QueryDict
from django.utils.datastructures import MultiValueDict
from rest_framework import serializers
@@ -532,3 +533,32 @@ class Serializer(serializers.Serializer):
assert value == updated_data_list[index][key]
assert serializer.errors == {}
+
+
+class TestEmptyListSerializer:
+ """
+ Tests the behaviour of ListSerializers when there is no data passed to it
+ """
+
+ def setup(self):
+ class ExampleListSerializer(serializers.ListSerializer):
+ child = serializers.IntegerField()
+
+ self.Serializer = ExampleListSerializer
+
+ def test_nested_serializer_with_list_json(self):
+ # pass an empty array to the serializer
+ input_data = []
+
+ serializer = self.Serializer(data=input_data)
+
+ assert serializer.is_valid()
+ assert serializer.validated_data == []
+
+ def test_nested_serializer_with_list_multipart(self):
+ # pass an "empty" QueryDict to the serializer (should be the same as an empty array)
+ input_data = QueryDict('')
+ serializer = self.Serializer(data=input_data)
+
+ assert serializer.is_valid()
+ assert serializer.validated_data == []
diff --git a/tests/test_serializer_nested.py b/tests/test_serializer_nested.py
--- a/tests/test_serializer_nested.py
+++ b/tests/test_serializer_nested.py
@@ -202,3 +202,42 @@ def test_nested_serializer_with_list_multipart(self):
assert serializer.is_valid()
assert serializer.validated_data['nested']['example'] == {1, 2}
+
+
+class TestNotRequiredNestedSerializerWithMany:
+ def setup(self):
+ class NestedSerializer(serializers.Serializer):
+ one = serializers.IntegerField(max_value=10)
+
+ class TestSerializer(serializers.Serializer):
+ nested = NestedSerializer(required=False, many=True)
+
+ self.Serializer = TestSerializer
+
+ def test_json_validate(self):
+ input_data = {}
+ serializer = self.Serializer(data=input_data)
+
+ # request is empty, therefor 'nested' should not be in serializer.data
+ assert serializer.is_valid()
+ assert 'nested' not in serializer.validated_data
+
+ input_data = {'nested': [{'one': '1'}, {'one': 2}]}
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert 'nested' in serializer.validated_data
+
+ def test_multipart_validate(self):
+ # leave querydict empty
+ input_data = QueryDict('')
+ serializer = self.Serializer(data=input_data)
+
+ # the querydict is empty, therefor 'nested' should not be in serializer.data
+ assert serializer.is_valid()
+ assert 'nested' not in serializer.validated_data
+
+ input_data = QueryDict('nested[0]one=1&nested[1]one=2')
+
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert 'nested' in serializer.validated_data
| ListField default values not honored in multipart/form-data mode
When sending a `multipart/form-data` request to a serializer with a `ListField`, the default value returned for the field is always the empty list `[]`. Any `default=` passed to field will be ignored due to the way html input is handled in the `get_value()` function.
* This functionality works properly when posting `json` data
* May be related to #5807 but I don't think so.
## Steps to reproduce
```python
class SimpleSerializer(Serializer):
a = IntegerField(required=True)
c = ListField(default=lambda: [1, 2, 3])
# simulate a multipart/form-data post (querydict is a confusing name here)
s1 = SimpleSerializer(data=QueryDict("a=3"))
s1.is_valid(raise_exception=True)
print("html:", s1.validated_data)
# simulate a JSON post
s2 = SimpleSerializer(data={'a': 3})
s2.is_valid(raise_exception=True)
print("json:", s2.validated_data)
>>> html: OrderedDict([(u'a', 3), (u'c', [])])
>>> json: OrderedDict([(u'a', 3), (u'c', [1, 2, 3])])
```
## Expected behavior
* Default value should be honored in HTML mode
## Actual behavior
* Default value is always returned as `[]`
## Explanation and Workaround
The `ListField.get_value()` function **always** returns the value of `html.parse_html_list` from get_value when that field_name was not passed. There is a check at the top for a missing key, but that only affects `partial` posts. Missing keys on regular POSTs will still be processed normally and return `[]`.
I'm not sure if it is OK to just *remove* that check for partial and always return `empty`, but that is what I have done for this version of my workaround. The list fields I use this way are in pure serializers and are only used for validating input. They are not used in `ModelSerializers` so for my case this is ok.
## Initial Workaround
```python
class ListFieldWithSaneDefault(ListField):
"""
This is used ONLY as a base class for other fields. When using it, please ensure that you
always provide a default value (at least `default=lambda: []`) if the field is not required.
Your derived class should take no parameters to __init__, it should be self contained
"""
def get_value(self, dictionary):
"""
When handling html multipart forms input (as opposed to json, which works properly)
the base list field returns `[]` for _missing_ keys. This override checks for that specific
case and returns `empty` so that standard default-value processing takes over
"""
if self.field_name not in dictionary:
return empty
return super(ListFieldWithSaneDefault, self).get_value(dictionary)
```
| Okay. One sensible thing to do would be to try that in the repo, and see which (if any) tests fail,
and then take things from there.
| 2018-04-09T09:24:51 |
encode/django-rest-framework | 5,932 | encode__django-rest-framework-5932 | [
"5919"
] | 1c53fd32125b4742cdb95246523f1cd0c41c497c | diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py
--- a/rest_framework/exceptions.py
+++ b/rest_framework/exceptions.py
@@ -91,6 +91,9 @@ def __repr__(self):
self.code,
))
+ def __hash__(self):
+ return hash(str(self))
+
class APIException(Exception):
"""
| diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py
--- a/tests/test_exceptions.py
+++ b/tests/test_exceptions.py
@@ -81,6 +81,10 @@ def test_str(self):
assert str(ErrorDetail('msg1')) == 'msg1'
assert str(ErrorDetail('msg1', 'code')) == 'msg1'
+ def test_hash(self):
+ assert hash(ErrorDetail('msg')) == hash('msg')
+ assert hash(ErrorDetail('msg', 'code')) == hash('msg')
+
class TranslationTests(TestCase):
| rest_framework.exceptions.ErrorDetail is unhashable after commit #5787
Commit #5787 makes class rest_framework.exceptions.ErrorDetail unhashable. This breaks functionality of some third-party libraries (like https://github.com/FutureMind/drf-friendly-errors).
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
from rest_framework.exceptions import ErrorDetail
err = ErrorDetail('error', code=1)
hash(err)
## Expected behavior
valid hash
## Actual behavior
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'ErrorDetail'
| OK. Yes. Since we added `__eq__()` it would be worth adding `__hash__()` | 2018-04-11T13:49:01 |
encode/django-rest-framework | 5,936 | encode__django-rest-framework-5936 | [
"5933"
] | 1c53fd32125b4742cdb95246523f1cd0c41c497c | diff --git a/rest_framework/utils/humanize_datetime.py b/rest_framework/utils/humanize_datetime.py
--- a/rest_framework/utils/humanize_datetime.py
+++ b/rest_framework/utils/humanize_datetime.py
@@ -13,7 +13,7 @@ def datetime_formats(formats):
def date_formats(formats):
- format = ', '.join(formats).replace(ISO_8601, 'YYYY[-MM[-DD]]')
+ format = ', '.join(formats).replace(ISO_8601, 'YYYY-MM-DD')
return humanize_strptime(format)
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -1122,8 +1122,10 @@ class TestDateField(FieldValues):
datetime.date(2001, 1, 1): datetime.date(2001, 1, 1),
}
invalid_inputs = {
- 'abc': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]].'],
- '2001-99-99': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]].'],
+ 'abc': ['Date has wrong format. Use one of these formats instead: YYYY-MM-DD.'],
+ '2001-99-99': ['Date has wrong format. Use one of these formats instead: YYYY-MM-DD.'],
+ '2001-01': ['Date has wrong format. Use one of these formats instead: YYYY-MM-DD.'],
+ '2001': ['Date has wrong format. Use one of these formats instead: YYYY-MM-DD.'],
datetime.datetime(2001, 1, 1, 12, 00): ['Expected a date but got a datetime.'],
}
outputs = {
| DateField does not admit formats error message says are supported
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [ ] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
```
>>> class S(serializers.Serializer):
... d = serializers.DateField()
```
## Expected behaviour
```
>>> S(data={'d': '2018'}).is_valid()
True
```
Based on the error message:
> 'Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]].'
## Actual behaviour
```
>>> S(data={'d': '2018'}).is_valid()
True
```
Note that optional month/days are not being tested:
https://github.com/encode/django-rest-framework/blob/c2b24f83a3d552845e29b7e3d39acf50beba1b5c/tests/test_fields.py#L1120-L1123
I think what I'd _actually_ expect is the current behaviour, in which case it's the error message that's incorrect. But I don't know which is intended.
| Agree that we should change the error message. | 2018-04-13T21:15:36 |
encode/django-rest-framework | 5,988 | encode__django-rest-framework-5988 | [
"3338"
] | c5ab65923f8bb1156ed5ebb1032ac0cf2c176121 | diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py
--- a/rest_framework/renderers.py
+++ b/rest_framework/renderers.py
@@ -18,6 +18,7 @@
from django.http.multipartparser import parse_header
from django.template import engines, loader
from django.test.client import encode_multipart
+from django.urls import NoReverseMatch
from django.utils import six
from django.utils.html import mark_safe
@@ -808,6 +809,12 @@ def get_context(self, data, accepted_media_type, renderer_context):
columns = [key for key in header if key != 'url']
details = [key for key in header if key != 'url']
+ if isinstance(results, list) and 'view' in renderer_context:
+ for result in results:
+ url = self.get_result_url(result, context['view'])
+ if url is not None:
+ result.setdefault('url', url)
+
context['style'] = style
context['columns'] = columns
context['details'] = details
@@ -816,6 +823,26 @@ def get_context(self, data, accepted_media_type, renderer_context):
context['error_title'] = getattr(self, 'error_title', None)
return context
+ def get_result_url(self, result, view):
+ """
+ Attempt to reverse the result's detail view URL.
+
+ This only works with views that are generic-like (has `.lookup_field`)
+ and viewset-like (has `.basename` / `.reverse_action()`).
+ """
+ if not hasattr(view, 'reverse_action') or \
+ not hasattr(view, 'lookup_field'):
+ return
+
+ lookup_field = view.lookup_field
+ lookup_url_kwarg = getattr(view, 'lookup_url_kwarg', None) or lookup_field
+
+ try:
+ kwargs = {lookup_url_kwarg: result[lookup_field]}
+ return view.reverse_action('detail', kwargs=kwargs)
+ except (KeyError, NoReverseMatch):
+ return
+
class DocumentationRenderer(BaseRenderer):
media_type = 'text/html'
| diff --git a/tests/test_renderers.py b/tests/test_renderers.py
--- a/tests/test_renderers.py
+++ b/tests/test_renderers.py
@@ -708,6 +708,75 @@ def get(self, request):
response.render()
self.assertContains(response, '<tr><th>Iteritems</th><td>a string</td></tr>', html=True)
+ def test_get_result_url(self):
+ factory = APIRequestFactory()
+
+ class DummyGenericViewsetLike(APIView):
+ lookup_field = 'test'
+
+ def reverse_action(view, *args, **kwargs):
+ self.assertEqual(kwargs['kwargs']['test'], 1)
+ return '/example/'
+
+ # get the view instance instead of the view function
+ view = DummyGenericViewsetLike.as_view()
+ request = factory.get('/')
+ response = view(request)
+ view = response.renderer_context['view']
+
+ self.assertEqual(self.renderer.get_result_url({'test': 1}, view), '/example/')
+ self.assertIsNone(self.renderer.get_result_url({}, view))
+
+ def test_get_result_url_no_result(self):
+ factory = APIRequestFactory()
+
+ class DummyView(APIView):
+ lookup_field = 'test'
+
+ # get the view instance instead of the view function
+ view = DummyView.as_view()
+ request = factory.get('/')
+ response = view(request)
+ view = response.renderer_context['view']
+
+ self.assertIsNone(self.renderer.get_result_url({'test': 1}, view))
+ self.assertIsNone(self.renderer.get_result_url({}, view))
+
+ def test_get_context_result_urls(self):
+ factory = APIRequestFactory()
+
+ class DummyView(APIView):
+ lookup_field = 'test'
+
+ def reverse_action(view, url_name, args=None, kwargs=None):
+ return '/%s/%d' % (url_name, kwargs['test'])
+
+ # get the view instance instead of the view function
+ view = DummyView.as_view()
+ request = factory.get('/')
+ response = view(request)
+
+ data = [
+ {'test': 1},
+ {'url': '/example', 'test': 2},
+ {'url': None, 'test': 3},
+ {},
+ ]
+ context = {
+ 'view': DummyView(),
+ 'request': Request(request),
+ 'response': response
+ }
+
+ context = self.renderer.get_context(data, None, context)
+ results = context['results']
+
+ self.assertEqual(len(results), 4)
+ self.assertEqual(results[0]['url'], '/detail/1')
+ self.assertEqual(results[1]['url'], '/example')
+ self.assertEqual(results[2]['url'], None)
+ self.assertNotIn('url', results[3])
+
@pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
class TestDocumentationRenderer(TestCase):
| AdminRenderer does not correctly link to detail page if Serializer is not HyperlinkedModelSerializer
If the `Serializer` in the view is `ModelSerializer` rather than a `HyperlinkedModelSerializer`, the arrow link to the detail page does not work (it just points to the list page).

| Milestoning to consider. May well be that we _only_ support the admin fully with hyperlinks, since we're need them when rendering the interface.
I'm going to de-milestone for now. We can reassess after 3.7 | 2018-05-15T18:28:36 |
encode/django-rest-framework | 5,992 | encode__django-rest-framework-5992 | [
"5995"
] | d9f541836b243ef94c8df616a0d5b683414547f7 | diff --git a/rest_framework/schemas/generators.py b/rest_framework/schemas/generators.py
--- a/rest_framework/schemas/generators.py
+++ b/rest_framework/schemas/generators.py
@@ -218,6 +218,10 @@ def should_include_endpoint(self, path, callback):
if callback.cls.schema is None:
return False
+ if 'schema' in callback.initkwargs:
+ if callback.initkwargs['schema'] is None:
+ return False
+
if path.endswith('.{format}') or path.endswith('.{format}/'):
return False # Ignore .json style URLs.
@@ -365,9 +369,7 @@ def create_view(self, callback, method, request=None):
"""
Given a callback, return an actual view instance.
"""
- view = callback.cls()
- for attr, val in getattr(callback, 'initkwargs', {}).items():
- setattr(view, attr, val)
+ view = callback.cls(**getattr(callback, 'initkwargs', {}))
view.args = ()
view.kwargs = {}
view.format_kwarg = None
diff --git a/rest_framework/schemas/inspectors.py b/rest_framework/schemas/inspectors.py
--- a/rest_framework/schemas/inspectors.py
+++ b/rest_framework/schemas/inspectors.py
@@ -7,6 +7,7 @@
import re
import warnings
from collections import OrderedDict
+from weakref import WeakKeyDictionary
from django.db import models
from django.utils.encoding import force_text, smart_text
@@ -128,6 +129,10 @@ class ViewInspector(object):
Provide subclass for per-view schema generation
"""
+
+ def __init__(self):
+ self.instance_schemas = WeakKeyDictionary()
+
def __get__(self, instance, owner):
"""
Enables `ViewInspector` as a Python _Descriptor_.
@@ -144,9 +149,17 @@ def __get__(self, instance, owner):
See: https://docs.python.org/3/howto/descriptor.html for info on
descriptor usage.
"""
+ if instance in self.instance_schemas:
+ return self.instance_schemas[instance]
+
self.view = instance
return self
+ def __set__(self, instance, other):
+ self.instance_schemas[instance] = other
+ if other is not None:
+ other.view = instance
+
@property
def view(self):
"""View property."""
@@ -189,6 +202,7 @@ def __init__(self, manual_fields=None):
* `manual_fields`: list of `coreapi.Field` instances that
will be added to auto-generated fields, overwriting on `Field.name`
"""
+ super(AutoSchema, self).__init__()
if manual_fields is None:
manual_fields = []
self._manual_fields = manual_fields
@@ -455,6 +469,7 @@ def __init__(self, fields, description='', encoding=None):
* `fields`: list of `coreapi.Field` instances.
* `descripton`: String description for view. Optional.
"""
+ super(ManualSchema, self).__init__()
assert all(isinstance(f, coreapi.Field) for f in fields), "`fields` must be a list of coreapi.Field instances"
self._fields = fields
self._description = description
@@ -474,9 +489,13 @@ def get_link(self, path, method, base_url):
)
-class DefaultSchema(object):
+class DefaultSchema(ViewInspector):
"""Allows overriding AutoSchema using DEFAULT_SCHEMA_CLASS setting"""
def __get__(self, instance, owner):
+ result = super(DefaultSchema, self).__get__(instance, owner)
+ if not isinstance(result, DefaultSchema):
+ return result
+
inspector_class = api_settings.DEFAULT_SCHEMA_CLASS
assert issubclass(inspector_class, ViewInspector), "DEFAULT_SCHEMA_CLASS must be set to a ViewInspector (usually an AutoSchema) subclass"
inspector = inspector_class()
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -99,6 +99,10 @@ def custom_list_action(self, request):
def custom_list_action_multiple_methods(self, request):
return super(ExampleViewSet, self).list(self, request)
+ @action(detail=False, schema=None)
+ def excluded_action(self, request):
+ pass
+
def get_serializer(self, *args, **kwargs):
assert self.request
assert self.action
@@ -720,6 +724,45 @@ class CustomView(APIView):
assert len(fields) == 2
assert "my_extra_field" in [f.name for f in fields]
+ @pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
+ def test_viewset_action_with_schema(self):
+ class CustomViewSet(GenericViewSet):
+ @action(detail=True, schema=AutoSchema(manual_fields=[
+ coreapi.Field(
+ "my_extra_field",
+ required=True,
+ location="path",
+ schema=coreschema.String()
+ ),
+ ]))
+ def extra_action(self, pk, **kwargs):
+ pass
+
+ router = SimpleRouter()
+ router.register(r'detail', CustomViewSet, base_name='detail')
+
+ generator = SchemaGenerator()
+ view = generator.create_view(router.urls[0].callback, 'GET')
+ link = view.schema.get_link('/a/url/{id}/', 'GET', '')
+ fields = link.fields
+
+ assert len(fields) == 2
+ assert "my_extra_field" in [f.name for f in fields]
+
+ @pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
+ def test_viewset_action_with_null_schema(self):
+ class CustomViewSet(GenericViewSet):
+ @action(detail=True, schema=None)
+ def extra_action(self, pk, **kwargs):
+ pass
+
+ router = SimpleRouter()
+ router.register(r'detail', CustomViewSet, base_name='detail')
+
+ generator = SchemaGenerator()
+ view = generator.create_view(router.urls[0].callback, 'GET')
+ assert view.schema is None
+
@pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
def test_view_with_manual_schema(self):
| detail_route/list_route doesn't allow to disable schema generation
Would be nice if `detail_route` or `list_route` woudl allow to disable schema generation
by setting arg `schema=None`.
```
@detail_route(
methods=['get', ],
schema=None,
...
)
```
At the moment I have to build separate view
```
class MyViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
...
schema = None
...
```
| 2018-05-17T06:08:48 |
|
encode/django-rest-framework | 6,028 | encode__django-rest-framework-6028 | [
"6025"
] | 9b8af04e7fe532d0bd373d0d1875cf1748bdadf5 | diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -1,6 +1,7 @@
# coding: utf-8
from __future__ import unicode_literals
+import sys
from collections import OrderedDict
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
@@ -31,6 +32,20 @@ def method_overridden(method_name, klass, instance):
return default_method is not getattr(instance, method_name).__func__
+class ObjectValueError(ValueError):
+ """
+ Raised when `queryset.get()` failed due to an underlying `ValueError`.
+ Wrapping prevents calling code conflating this with unrelated errors.
+ """
+
+
+class ObjectTypeError(TypeError):
+ """
+ Raised when `queryset.get()` failed due to an underlying `TypeError`.
+ Wrapping prevents calling code conflating this with unrelated errors.
+ """
+
+
class Hyperlink(six.text_type):
"""
A string like object that additionally has an associated name.
@@ -296,7 +311,16 @@ def get_object(self, view_name, view_args, view_kwargs):
"""
lookup_value = view_kwargs[self.lookup_url_kwarg]
lookup_kwargs = {self.lookup_field: lookup_value}
- return self.get_queryset().get(**lookup_kwargs)
+ queryset = self.get_queryset()
+
+ try:
+ return queryset.get(**lookup_kwargs)
+ except ValueError:
+ exc = ObjectValueError(str(sys.exc_info()[1]))
+ six.reraise(type(exc), exc, sys.exc_info()[2])
+ except TypeError:
+ exc = ObjectTypeError(str(sys.exc_info()[1]))
+ six.reraise(type(exc), exc, sys.exc_info()[2])
def get_url(self, obj, view_name, request, format):
"""
@@ -346,7 +370,7 @@ def to_internal_value(self, data):
try:
return self.get_object(match.view_name, match.args, match.kwargs)
- except (ObjectDoesNotExist, TypeError, ValueError):
+ except (ObjectDoesNotExist, ObjectValueError, ObjectTypeError):
self.fail('does_not_exist')
def to_representation(self, value):
| diff --git a/tests/test_relations.py b/tests/test_relations.py
--- a/tests/test_relations.py
+++ b/tests/test_relations.py
@@ -197,6 +197,36 @@ def test_hyperlinked_related_lookup_does_not_exist(self):
msg = excinfo.value.detail[0]
assert msg == 'Invalid hyperlink - Object does not exist.'
+ def test_hyperlinked_related_internal_type_error(self):
+ class Field(serializers.HyperlinkedRelatedField):
+ def get_object(self, incorrect, signature):
+ raise NotImplementedError()
+
+ field = Field(view_name='example', queryset=self.queryset)
+ with pytest.raises(TypeError):
+ field.to_internal_value('http://example.org/example/doesnotexist/')
+
+ def hyperlinked_related_queryset_error(self, exc_type):
+ class QuerySet:
+ def get(self, *args, **kwargs):
+ raise exc_type
+
+ field = serializers.HyperlinkedRelatedField(
+ view_name='example',
+ lookup_field='name',
+ queryset=QuerySet(),
+ )
+ with pytest.raises(serializers.ValidationError) as excinfo:
+ field.to_internal_value('http://example.org/example/doesnotexist/')
+ msg = excinfo.value.detail[0]
+ assert msg == 'Invalid hyperlink - Object does not exist.'
+
+ def test_hyperlinked_related_queryset_type_error(self):
+ self.hyperlinked_related_queryset_error(TypeError)
+
+ def test_hyperlinked_related_queryset_value_error(self):
+ self.hyperlinked_related_queryset_error(ValueError)
+
class TestHyperlinkedIdentityField(APISimpleTestCase):
def setUp(self):
| Try/catch in HyperlinkedRelatedField too broad.
In https://github.com/encode/django-rest-framework/blob/master/rest_framework/relations.py#L347-L350
Catching and silently discarding the `TypeError` and `ValueError` seems overly broad, is it necessary?
I'm asking, after spending time debugging a derived `HyperlinkedRelatedField` where, it turns out, I was using the wrong method signature, which was throwing `TypeError` exceptions that DRF was thing reporting as 'object not found'.
Turns out there was an error in the documentation which I've patched in https://github.com/encode/django-rest-framework/pull/6024
Maybe correcting the docs is enough to prevent similar mistakes in the future, but catching `TypeError` could mask all sorts of errors, is it too broad?
| > catching TypeError could mask all sorts of errors, is it too broad?
I'm not sure it's resolvable. Making a queryset lookup with a string that *doesn't* convert to the expected type will raise one of those two error classes.
This will happen eg. in the case of API input of a hyperlinked URL using "/organizations/abc" for a model that expects "/organizations/123" .
We do need to catch those cases and represent them as "does_not_exist" errors against the user input. | 2018-06-13T16:08:28 |
encode/django-rest-framework | 6,113 | encode__django-rest-framework-6113 | [
"6088"
] | 2fab7838ef79c2b9c6f67d930ab2e28aa392f516 | diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py
--- a/rest_framework/authentication.py
+++ b/rest_framework/authentication.py
@@ -135,7 +135,10 @@ def enforce_csrf(self, request):
"""
Enforce CSRF validation for session based authentication.
"""
- reason = CSRFCheck().process_view(request, None, (), {})
+ check = CSRFCheck()
+ # populates request.META['CSRF_COOKIE'], which is used in process_view()
+ check.process_request(request)
+ reason = check.process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
| diff --git a/tests/test_authentication.py b/tests/test_authentication.py
--- a/tests/test_authentication.py
+++ b/tests/test_authentication.py
@@ -5,6 +5,7 @@
import base64
import pytest
+from django.conf import settings
from django.conf.urls import include, url
from django.contrib.auth.models import User
from django.db import models
@@ -202,6 +203,26 @@ def test_post_form_session_auth_failing_csrf(self):
response = self.csrf_client.post('/session/', {'example': 'example'})
assert response.status_code == status.HTTP_403_FORBIDDEN
+ def test_post_form_session_auth_passing_csrf(self):
+ """
+ Ensure POSTing form over session authentication with CSRF token succeeds.
+ Regression test for #6088
+ """
+ from django.middleware.csrf import _get_new_csrf_token
+
+ self.csrf_client.login(username=self.username, password=self.password)
+
+ # Set the csrf_token cookie so that CsrfViewMiddleware._get_token() works
+ token = _get_new_csrf_token()
+ self.csrf_client.cookies[settings.CSRF_COOKIE_NAME] = token
+
+ # Post the token matching the cookie value
+ response = self.csrf_client.post('/session/', {
+ 'example': 'example',
+ 'csrfmiddlewaretoken': token,
+ })
+ assert response.status_code == status.HTTP_200_OK
+
def test_post_form_session_auth_passing(self):
"""
Ensure POSTing form over session authentication with logged in
| CSRFCheck fails from csrf cookie with django 1.11
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [x] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
* use `Django~=1.11.6` (the issue does not happen with 1.10 or earlier 1.11s. I haven't tested with 2.x)
* use session auth and have a valid `csrf_token` cookie
* do a POST/PUT request using a DRF API
## Expected behavior
Get a successful response.
## Actual behavior
We get this returned:
```
{"detail":"CSRF Failed: CSRF cookie not set."}
```
## What's going on
It looks like `SessionAuthentication.enforce_csrf` uses `CSRFCheck` which is a thin subclass of `CSRFViewMiddleware`.
In django 1.11.6 this change was made in `CSRFViewMiddleware`: https://github.com/django/django/commit/42847327d1277451ee7a61716f7b9f62f50ecbdc
([full code](https://github.com/django/django/blob/stable/1.11.x/django/middleware/csrf.py#L289-L294) for django 1.11.x in that file)
It is clear that the `process_view` method expects `request.META['CSRF_COOKIE']` to be populated. But it is now not done in the body of `process_view` but earlier in the middleware processing, in the `process_request` call.
This works fine when called as a middleware, but when `process_view` is called independently/directly as DRF does, this breaks and rejects the request since it couldn't find the cookie.
This could be considered a Django bug, though in normal django usage it works okay because `process_request` is called before `process_view`. Maybe DRF should call both?
| Any word on this, or pointers to extra information I could supply that would be useful? Thanks | 2018-08-07T01:15:46 |
encode/django-rest-framework | 6,183 | encode__django-rest-framework-6183 | [
"6103"
] | 5f1f2b100353970ac0dec672154fedd3df9d0a9f | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -674,10 +674,7 @@ class BooleanField(Field):
'0', 0, 0.0,
False
}
-
- def __init__(self, **kwargs):
- assert 'allow_null' not in kwargs, '`allow_null` is not a valid option. Use `NullBooleanField` instead.'
- super(BooleanField, self).__init__(**kwargs)
+ NULL_VALUES = {'null', 'Null', 'NULL', '', None}
def to_internal_value(self, data):
try:
@@ -685,6 +682,8 @@ def to_internal_value(self, data):
return True
elif data in self.FALSE_VALUES:
return False
+ elif data in self.NULL_VALUES and self.allow_null:
+ return None
except TypeError: # Input is an unhashable type
pass
self.fail('invalid', input=data)
@@ -694,6 +693,8 @@ def to_representation(self, value):
return True
elif value in self.FALSE_VALUES:
return False
+ if value in self.NULL_VALUES and self.allow_null:
+ return None
return bool(value)
@@ -718,7 +719,7 @@ class NullBooleanField(Field):
'0', 0, 0.0,
False
}
- NULL_VALUES = {'n', 'N', 'null', 'Null', 'NULL', '', None}
+ NULL_VALUES = {'null', 'Null', 'NULL', '', None}
def __init__(self, **kwargs):
assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.'
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -657,7 +657,7 @@ def test_disallow_unhashable_collection_types(self):
class TestNullBooleanField(TestBooleanField):
"""
- Valid and invalid values for `BooleanField`.
+ Valid and invalid values for `NullBooleanField`.
"""
valid_inputs = {
'true': True,
@@ -682,6 +682,16 @@ class TestNullBooleanField(TestBooleanField):
field = serializers.NullBooleanField()
+class TestNullableBooleanField(TestNullBooleanField):
+ """
+ Valid and invalid values for `BooleanField` when `allow_null=True`.
+ """
+
+ @property
+ def field(self):
+ return serializers.BooleanField(allow_null=True)
+
+
# String types...
class TestCharField(FieldValues):
diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py
--- a/tests/test_model_serializer.py
+++ b/tests/test_model_serializer.py
@@ -12,6 +12,7 @@
import sys
from collections import OrderedDict
+import django
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.validators import (
@@ -220,6 +221,25 @@ class Meta:
)
self.assertEqual(unicode_repr(TestSerializer()), expected)
+ # merge this into test_regular_fields / RegularFieldsModel when
+ # Django 2.1 is the minimum supported version
+ @pytest.mark.skipif(django.VERSION < (2, 1), reason='Django version < 2.1')
+ def test_nullable_boolean_field(self):
+ class NullableBooleanModel(models.Model):
+ field = models.BooleanField(null=True, default=False)
+
+ class NullableBooleanSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = NullableBooleanModel
+ fields = ['field']
+
+ expected = dedent("""
+ NullableBooleanSerializer():
+ field = BooleanField(allow_null=True, required=False)
+ """)
+
+ self.assertEqual(unicode_repr(NullableBooleanSerializer()), expected)
+
def test_method_field(self):
"""
Properties and methods on the model should be allowed as `Meta.fields`
| Add support for Django 2.1 BooleanField(null=True)
In Django 2.1 it's possible to add Boolean fields with null=True instead of NullBooleanField
But using such field in ModelSerializer lead to an error `allow_null is not a valid option. Use NullBooleanField instead.`
## Steps to reproduce
create some model with a field defined as `models.BooleanField(null=True, blank=True)`, create model serializer and include model's field in the fields list
## Expected behavior
No exception, serialized could be used as usual
## Actual behavior
Exception is raised
| I worked around this by switching all nullable bools to `models.NullBooleanField()` even though Django's own documentation suggest not doing that since its going to be deprecated.
https://docs.djangoproject.com/en/2.1/ref/models/fields/#booleanfield
We should be able to fix this for the 3.9 release.
Edit:
My previous example wouldn't work - making `BooleanField` compatible requires more than just removing the `allow_null` check. | 2018-09-13T00:42:01 |
encode/django-rest-framework | 6,240 | encode__django-rest-framework-6240 | [
"6094"
] | 2daf6f13414f1a5d363b5bc4a2ce3ba294a7766c | diff --git a/rest_framework/filters.py b/rest_framework/filters.py
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -85,6 +85,9 @@ def must_call_distinct(self, queryset, search_fields):
opts = queryset.model._meta
if search_field[0] in self.lookup_prefixes:
search_field = search_field[1:]
+ # Annotated fields do not need to be distinct
+ if isinstance(queryset, models.QuerySet) and search_field in queryset.query.annotations:
+ return False
parts = search_field.split(LOOKUP_SEP)
for part in parts:
field = opts.get_field(part)
| diff --git a/tests/test_filters.py b/tests/test_filters.py
--- a/tests/test_filters.py
+++ b/tests/test_filters.py
@@ -5,6 +5,7 @@
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.db import models
+from django.db.models.functions import Concat, Upper
from django.test import TestCase
from django.test.utils import override_settings
from django.utils.six.moves import reload_module
@@ -329,6 +330,38 @@ class SearchListView(generics.ListAPIView):
assert len(response.data) == 1
+class SearchFilterAnnotatedSerializer(serializers.ModelSerializer):
+ title_text = serializers.CharField()
+
+ class Meta:
+ model = SearchFilterModel
+ fields = ('title', 'text', 'title_text')
+
+
+class SearchFilterAnnotatedFieldTests(TestCase):
+ @classmethod
+ def setUpTestData(cls):
+ SearchFilterModel.objects.create(title='abc', text='def')
+ SearchFilterModel.objects.create(title='ghi', text='jkl')
+
+ def test_search_in_annotated_field(self):
+ class SearchListView(generics.ListAPIView):
+ queryset = SearchFilterModel.objects.annotate(
+ title_text=Upper(
+ Concat(models.F('title'), models.F('text'))
+ )
+ ).all()
+ serializer_class = SearchFilterAnnotatedSerializer
+ filter_backends = (filters.SearchFilter,)
+ search_fields = ('title_text',)
+
+ view = SearchListView.as_view()
+ request = factory.get('/', {'search': 'ABCDEF'})
+ response = view(request)
+ assert len(response.data) == 1
+ assert response.data[0]['title_text'] == 'ABCDEF'
+
+
class OrderingFilterModel(models.Model):
title = models.CharField(max_length=20, verbose_name='verbose title')
text = models.CharField(max_length=100)
| Annotate model fields don't work as search fields anymore
## Steps to reproduce
In a viewset set queryset to have annotated field:
```
class MyViewSet()
queryset = MyModel.objects.all().annotate(new_field=..)
search_fields = ('new_field',)
```
Perform a search using `new_field`.
## Expected behavior
Return the result filtered by `new_field`.
## Actual behavior
Exception. MyModel doesn't have field new_field.
```
....
File "/usr/local/lib/python3.6/site-packages/rest_framework/filters.py" in must_call_distinct
79. field = opts.get_field(part)
....
```
The reason is SearchFilter.must_call_distinct uses model._meta to look up for the fields.
Worked fine before. The bug was introduced in v3.4.0.
| 2018-10-10T20:37:00 |
|
encode/django-rest-framework | 6,243 | encode__django-rest-framework-6243 | [
"6211"
] | 1c3f796219e7794306bb2db81d4910c0cb7c932a | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1766,6 +1766,9 @@ class JSONField(Field):
'invalid': _('Value must be valid JSON.')
}
+ # Workaround for isinstance calls when importing the field isn't possible
+ _is_jsonfield = True
+
def __init__(self, *args, **kwargs):
self.binary = kwargs.pop('binary', False)
super(JSONField, self).__init__(*args, **kwargs)
diff --git a/rest_framework/utils/serializer_helpers.py b/rest_framework/utils/serializer_helpers.py
--- a/rest_framework/utils/serializer_helpers.py
+++ b/rest_framework/utils/serializer_helpers.py
@@ -90,7 +90,12 @@ def as_form_field(self):
# value will be a JSONString, rather than a JSON primitive.
if not getattr(value, 'is_json_string', False):
try:
- value = json.dumps(self.value, sort_keys=True, indent=4)
+ value = json.dumps(
+ self.value,
+ sort_keys=True,
+ indent=4,
+ separators=(',', ': '),
+ )
except (TypeError, ValueError):
pass
return self.__class__(self._field, value, self.errors, self._prefix)
@@ -118,6 +123,8 @@ def __getitem__(self, key):
error = self.errors.get(key) if isinstance(self.errors, dict) else None
if hasattr(field, 'fields'):
return NestedBoundField(field, value, error, prefix=self.name + '.')
+ elif getattr(field, '_is_jsonfield', False):
+ return JSONBoundField(field, value, error, prefix=self.name + '.')
return BoundField(field, value, error, prefix=self.name + '.')
def as_form_field(self):
| diff --git a/tests/test_bound_fields.py b/tests/test_bound_fields.py
--- a/tests/test_bound_fields.py
+++ b/tests/test_bound_fields.py
@@ -91,6 +91,10 @@ class ExampleSerializer(serializers.Serializer):
assert rendered_packed == expected_packed
+class CustomJSONField(serializers.JSONField):
+ pass
+
+
class TestNestedBoundField:
def test_nested_empty_bound_field(self):
class Nested(serializers.Serializer):
@@ -117,14 +121,31 @@ def test_as_form_fields(self):
class Nested(serializers.Serializer):
bool_field = serializers.BooleanField()
null_field = serializers.IntegerField(allow_null=True)
+ json_field = serializers.JSONField()
+ custom_json_field = CustomJSONField()
class ExampleSerializer(serializers.Serializer):
nested = Nested()
- serializer = ExampleSerializer(data={'nested': {'bool_field': False, 'null_field': None}})
+ serializer = ExampleSerializer(
+ data={'nested': {
+ 'bool_field': False, 'null_field': None,
+ 'json_field': {'bool_item': True, 'number': 1, 'text_item': 'text'},
+ 'custom_json_field': {'bool_item': True, 'number': 1, 'text_item': 'text'},
+ }})
assert serializer.is_valid()
assert serializer['nested']['bool_field'].as_form_field().value == ''
assert serializer['nested']['null_field'].as_form_field().value == ''
+ assert serializer['nested']['json_field'].as_form_field().value == '''{
+ "bool_item": true,
+ "number": 1,
+ "text_item": "text"
+}'''
+ assert serializer['nested']['custom_json_field'].as_form_field().value == '''{
+ "bool_item": true,
+ "number": 1,
+ "text_item": "text"
+}'''
def test_rendering_nested_fields_with_none_value(self):
from rest_framework.renderers import HTMLFormRenderer
| JSONField form data in a related model renders as python dict
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Assuming the following models, serializers and viewsets:
```
# models.py
from django.db import models
from django.contrib.postgres.fields import JSONField
class RelatedModel(models.Model):
json_content = JSONField()
class MainModel(models.Model):
name = models.CharField(max_length=64)
related_object = models.ForeignKey(
to=RelatedModel,
on_delete=models.CASCADE
)
# serializers.py
class RelatedModelSerializer(serializers.ModelSerializer):
class Meta:
model = RelatedModel
fields = '__all__'
class MainModelSerializer(serializers.ModelSerializer):
related_object = RelatedModelSerializer()
class Meta:
model = MainModel
fields = (
'id', 'name', 'related_object'
)
# views.py
class MainModelViewSet(viewsets.ModelViewSet):
serializer_class = MainModelSerializer
queryset = MainModel.objects.all()
class RelatedModelViewSet(viewsets.ModelViewSet):
serializer_class = RelatedModelSerializer
queryset = RelatedModel.objects.all()
# Create models in shell:
rm = RelatedModel.objects.create(json_content={'bool': False, 'text': 'Test text'})
MainModel.objects.create(name='Main', related_object=rm)
```
Then, open the MainModel instance in the Browsable API and look for the content in the form.
## Expected behavior
Form data for the `json_content` field to be in JSON format, that is:
```
{
"bool": false,
"text": "Test text"
}
```
## Actual behavior
Json content rendered as a python dict, that is `{'bool': False, 'text': 'Test text'}`, as shown in:

When viewing the RelatedModel itself (using RelatedModelViewSet) the json content is rendered fine.
| Closing it as duplicate of #4999
I disagree with this being a duplicate of #4999, because that issue was fixed and the JSONField renders correctly when the field is in the serialized model directly. This issue occurs when the JSONField is in the related model.
Is there a workaround for this problem?, I think the same problems occurs with nested serializers in my REST Api output. The JsonField in the related entity is returned as string with a python dict and not is valid JSON.
in [serializers#549](https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L549) when a field is a Serializer, thats the case with related_object, it returns a `NestedBoundField` to parse it.
after that all fields found by `NestedBoundField` will be parsed as a `BoundField`, because `NestedBoundField` can't identify if the field is a json field.
You can see this here in [serializer_helpers#119](https://github.com/encode/django-rest-framework/blob/master/rest_framework/utils/serializer_helpers.py#L119)
as a workaround, i did this inside `BoundField.as_form_field`, put the code from JSONBoundField that parses the json from `value` inside it:
```Python
# serializer_helpers#81
def as_form_field(self):
value = '' if (self.value is None or self.value is False) else self.value
# if value is a valid json then we parse it
if not getattr(value, 'is_json_string', False):
try:
value = json.dumps(self.value, sort_keys=True, indent=4)
except (TypeError, ValueError):
pass
return self.__class__(self._field, value, self.errors, self._prefix)
```
and it rendered as expected:

i think thats not the best solution, but now the problem's found. I woudl like to help with a PR to fix this, if you could give me instructions.
sorry for my bad english, thats all.
Yes, this workaround works for this case but I'm afraid it might break something else. But it gave me the idea that by adapting the `Serializer.__getitem__` logic into `NestedBoundField.__getitem__`, the JSONBoundField would be used properly. | 2018-10-15T05:30:01 |
encode/django-rest-framework | 6,282 | encode__django-rest-framework-6282 | [
"6280"
] | eb3180173ed119192c57a6ab52097025c00148e3 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -350,7 +350,7 @@ def __init__(self, read_only=False, write_only=False,
self.default_empty_html = default
if validators is not None:
- self.validators = validators[:]
+ self.validators = list(validators)
# These are set up by `.bind()` when the field is added to a serializer.
self.field_name = None
@@ -410,7 +410,7 @@ def validators(self, validators):
self._validators = validators
def get_validators(self):
- return self.default_validators[:]
+ return list(self.default_validators)
def get_initial(self):
"""
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -393,7 +393,7 @@ def get_validators(self):
# Used by the lazily-evaluated `validators` property.
meta = getattr(self, 'Meta', None)
validators = getattr(meta, 'validators', None)
- return validators[:] if validators else []
+ return list(validators) if validators else []
def get_initial(self):
if hasattr(self, 'initial_data'):
@@ -1480,7 +1480,7 @@ def get_validators(self):
# If the validators have been declared explicitly then use that.
validators = getattr(getattr(self, 'Meta', None), 'validators', None)
if validators is not None:
- return validators[:]
+ return list(validators)
# Otherwise use the default set of validators.
return (
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -740,6 +740,25 @@ def test_null_bytes(self):
'Null characters are not allowed.'
]
+ def test_iterable_validators(self):
+ """
+ Ensure `validators` parameter is compatible with reasonable iterables.
+ """
+ value = 'example'
+
+ for validators in ([], (), set()):
+ field = serializers.CharField(validators=validators)
+ field.run_validation(value)
+
+ def raise_exception(value):
+ raise exceptions.ValidationError('Raised error')
+
+ for validators in ([raise_exception], (raise_exception,), set([raise_exception])):
+ field = serializers.CharField(validators=validators)
+ with pytest.raises(serializers.ValidationError) as exc_info:
+ field.run_validation(value)
+ assert exc_info.value.detail == ['Raised error']
+
class TestEmailField(FieldValues):
"""
diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -10,7 +10,7 @@
import pytest
from django.db import models
-from rest_framework import fields, relations, serializers
+from rest_framework import exceptions, fields, relations, serializers
from rest_framework.compat import unicode_repr
from rest_framework.fields import Field
@@ -183,6 +183,38 @@ def to_internal_value(self, data):
assert serializer.validated_data.coords[1] == 50.941357
assert serializer.errors == {}
+ def test_iterable_validators(self):
+ """
+ Ensure `validators` parameter is compatible with reasonable iterables.
+ """
+ data = {'char': 'abc', 'integer': 123}
+
+ for validators in ([], (), set()):
+ class ExampleSerializer(serializers.Serializer):
+ char = serializers.CharField(validators=validators)
+ integer = serializers.IntegerField()
+
+ serializer = ExampleSerializer(data=data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == data
+ assert serializer.errors == {}
+
+ def raise_exception(value):
+ raise exceptions.ValidationError('Raised error')
+
+ for validators in ([raise_exception], (raise_exception,), set([raise_exception])):
+ class ExampleSerializer(serializers.Serializer):
+ char = serializers.CharField(validators=validators)
+ integer = serializers.IntegerField()
+
+ serializer = ExampleSerializer(data=data)
+ assert not serializer.is_valid()
+ assert serializer.data == data
+ assert serializer.validated_data == {}
+ assert serializer.errors == {'char': [
+ exceptions.ErrorDetail(string='Raised error', code='invalid')
+ ]}
+
class TestValidateMethod:
def test_non_field_error_validate_method(self):
| `validators` parameter in field cannot deal with `tuple`
## Checklist
- [X] I have verified that that issue exists against the `master` branch of Django REST framework.
- [X] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [X] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [X] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [X] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
If `tuple` validators (e.g., `validators=(1, 2, 3)`) is passed to field rather than `list`, DRF crashed, as it assumes `validators` is `list`.
## Expected behavior
Django actually uses `tuple` as default type for `validators`, and converts it internally to `list`:
https://github.com/django/django/commit/9027e6c8a3711034d345535036d1a276d9a8b829
This approach takes care of both `tuple` and `list` types for `validators`.
## Actual behavior
However, DRF assumes `validators` is `list`. Though it also uses `self.validators = validators[:]` to generate a new object, it failed to deal with `tuple`.
Hence, in recent change of DRF 3.9.0, the new stuff would break any code passing `tuple` to `validators`:
https://github.com/encode/django-rest-framework/commit/0eb2dc1137189027cc8d638630fb1754b02d6cfa#diff-af402f515db75c7c6754453cf15455d9
The `append()` approach was there in the past, but usually not triggered by default. Now due to the new `ProhibitNullCharactersValidator`, such behavior becomes more popular.
I'd suggest a similar approach to that of Django (`tuple` by default, and convert to `list` internally), so both types could be accepted and taken care of.
## PS
Let's discuss if this is the desired approach. If so, and if no one would like to fix it ASAP, I'd be glad to submit a PR, as my code is not working with DRF 3.9.0.
| Being consistent with Django's behavior would be the correct thing to do here. | 2018-10-26T21:45:00 |
encode/django-rest-framework | 6,365 | encode__django-rest-framework-6365 | [
"6053"
] | 963ce306f3226ec64eb8990c4fbc094a77fabcba | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -461,8 +461,11 @@ def run_validators(self, value):
"""
Add read_only fields with defaults to value before running validators.
"""
- to_validate = self._read_only_defaults()
- to_validate.update(value)
+ if isinstance(value, dict):
+ to_validate = self._read_only_defaults()
+ to_validate.update(value)
+ else:
+ to_validate = value
super(Serializer, self).run_validators(to_validate)
def to_internal_value(self, data):
| diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -156,6 +156,33 @@ def __len__(self):
assert serializer.validated_data == {'char': 'abc', 'integer': 123}
assert serializer.errors == {}
+ def test_custom_to_internal_value(self):
+ """
+ to_internal_value() is expected to return a dict, but subclasses may
+ return application specific type.
+ """
+ class Point(object):
+ def __init__(self, srid, x, y):
+ self.srid = srid
+ self.coords = (x, y)
+
+ # Declares a serializer that converts data into an object
+ class NestedPointSerializer(serializers.Serializer):
+ longitude = serializers.FloatField(source='x')
+ latitude = serializers.FloatField(source='y')
+
+ def to_internal_value(self, data):
+ kwargs = super(NestedPointSerializer, self).to_internal_value(data)
+ return Point(srid=4326, **kwargs)
+
+ serializer = NestedPointSerializer(data={'longitude': 6.958307, 'latitude': 50.941357})
+ assert serializer.is_valid()
+ assert isinstance(serializer.validated_data, Point)
+ assert serializer.validated_data.srid == 4326
+ assert serializer.validated_data.coords[0] == 6.958307
+ assert serializer.validated_data.coords[1] == 50.941357
+ assert serializer.errors == {}
+
class TestValidateMethod:
def test_non_field_error_validate_method(self):
| Returning an object in Serializer.to_internal_value is not working any more since 3.8.2
Returning an object in `Serializer.to_internal_value` is not working any more since 3.8.2 (because of #5922). I don't know if it was ever intended to be working (since obviously there are no tests for it) but it did in 3.8.1. Now `Serializer.to_internal_value` always has to return a `dict`. Otherwise a type error is raised.
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
```
class NestedPointSerializer(serializers.Serializer):
"""
Serialize `django.contrib.gis.geos.point.Point` instances
"""
longitude = serializers.FloatField(source='x')
latitude = serializers.FloatField(source='y')
def to_internal_value(self, data):
kwargs = super(NestedPointSerializer, self).to_internal_value(data)
return Point(srid=4326, **kwargs)
NestedPointSerializer(data={'longitude': 6.958307, 'latitude': 50.941357}).is_valid()
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 2910, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-4-fd7c8e4a6eab>", line 1, in <module>
NestedPointSerializer(data={'longitude': 6.958307, 'latitude': 50.941357}).is_valid()
File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 236, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 436, in run_validation
self.run_validators(value)
File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 465, in run_validators
to_validate.update(value)
TypeError: 'float' object is not iterable
```
## Expected behavior
Everything is working like it did in 3.8.1.
## Actual behavior
`TypeError: 'float' object is not iterable` raised in https://github.com/encode/django-rest-framework/blob/d9f541836b243ef94c8df616a0d5b683414547f7/rest_framework/serializers.py#L465
| Bump,
Is the failing test necessary to proceed? Issue seems obvious
Typically, instance creation is handled in the `create` and `update` methods, which are called when `save`ing the serializer. Per the docstring, `to_internal_value` should return a dict, not an instance.
https://github.com/encode/django-rest-framework/blob/90ed2c1ef7c652ce0a98075c422d25a632d62507/rest_framework/serializers.py#L468-L471
Usage would typically look like:
```python
my_serializer.is_valid(raise_exception=True)
instance = my_serializer.save()
```
What are you expecting to do instead?
What if there is no saving and you want to return your own type in validated_data
`validated_data` is still intended to be a dictionary of validated/native values. e.g., the `kwargs` passed to `save()` are used to update the `validated_data` dict. This wouldn't work if your `validated_data` is another type.
If you don't want to use the builtin save() method, you can always write your own instead. e.g.,
```python
class PointSerializer:
def save(self):
self.instance = Point(self.validated_data)
return self.instance
s = PointSerializer(...)
s.is_valid(raise_exception=True)
instance = s.save()
```
To me it seemed like `save` was meant for persistence? And `to_internal_value` mean "normal form", if that is not the case it should be named `to_scalar_dict` or something. Perhaps my confusion is caused by this: http://www.django-rest-framework.org/api-guide/fields/#custom-fields
This ruins composablity since save is just a non-recursive stub.
This used to work prior to 3.8.2 and i have lot of code doing similar things.
```python
class TwoPoints(serializer.Serializer):
a = PointSerializer()
b = PointSerializer()
s = TwoPoints(...)
s.is_valid(True)
assertDictEqual(s.validated_data, {'a': Point(...), 'b': Point(...) })
```
Good point. That is a discrepancy between the `to_internal_value` behavior of serializers and fields.
I've added it to the milestone to help ensure this is addressed in some capacity.
The temporary "fix" here may just be to override `run_validation` instead of `to_internal_value`.
Is there any workaround exists? I really need to update to 3.9 version and can't do it because of the problem. In our product most of serializers and fields return DTO (implemented with dataclasses) from to_internal_value.
@mofr
You can get old behavior back by overloading run_validators so it doesn't mess with default values
```python
def run_validators(self, value):
super(Serializer, self).run_validators(value)
``` | 2018-12-19T15:37:36 |
encode/django-rest-framework | 6,371 | encode__django-rest-framework-6371 | [
"1811"
] | 63e6bbfd367c78a38e77e5ec25081e34389c5bef | diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py
--- a/rest_framework/utils/field_mapping.py
+++ b/rest_framework/utils/field_mapping.py
@@ -249,6 +249,10 @@ def get_relation_kwargs(field_name, relation_info):
if to_field:
kwargs['to_field'] = to_field
+ limit_choices_to = model_field and model_field.get_limit_choices_to()
+ if limit_choices_to:
+ kwargs['queryset'] = kwargs['queryset'].filter(**limit_choices_to)
+
if has_through_model:
kwargs['read_only'] = True
kwargs.pop('queryset', None)
| diff --git a/tests/models.py b/tests/models.py
--- a/tests/models.py
+++ b/tests/models.py
@@ -52,6 +52,13 @@ class ForeignKeySource(RESTFrameworkModel):
on_delete=models.CASCADE)
+class ForeignKeySourceWithLimitedChoices(RESTFrameworkModel):
+ target = models.ForeignKey(ForeignKeyTarget, help_text='Target',
+ verbose_name='Target',
+ limit_choices_to={"name__startswith": "limited-"},
+ on_delete=models.CASCADE)
+
+
# Nullable ForeignKey
class NullableForeignKeySource(RESTFrameworkModel):
name = models.CharField(max_length=100)
diff --git a/tests/test_relations_pk.py b/tests/test_relations_pk.py
--- a/tests/test_relations_pk.py
+++ b/tests/test_relations_pk.py
@@ -5,10 +5,10 @@
from rest_framework import serializers
from tests.models import (
- ForeignKeySource, ForeignKeyTarget, ManyToManySource, ManyToManyTarget,
- NullableForeignKeySource, NullableOneToOneSource,
- NullableUUIDForeignKeySource, OneToOnePKSource, OneToOneTarget,
- UUIDForeignKeyTarget
+ ForeignKeySource, ForeignKeySourceWithLimitedChoices, ForeignKeyTarget,
+ ManyToManySource, ManyToManyTarget, NullableForeignKeySource,
+ NullableOneToOneSource, NullableUUIDForeignKeySource, OneToOnePKSource,
+ OneToOneTarget, UUIDForeignKeyTarget
)
@@ -38,6 +38,12 @@ class Meta:
fields = ('id', 'name', 'target')
+class ForeignKeySourceWithLimitedChoicesSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = ForeignKeySourceWithLimitedChoices
+ fields = ("id", "target")
+
+
# Nullable ForeignKey
class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
class Meta:
@@ -360,6 +366,18 @@ class Meta(ForeignKeySourceSerializer.Meta):
serializer.is_valid(raise_exception=True)
assert 'target' not in serializer.validated_data
+ def test_queryset_size_without_limited_choices(self):
+ limited_target = ForeignKeyTarget(name="limited-target")
+ limited_target.save()
+ queryset = ForeignKeySourceSerializer().fields["target"].get_queryset()
+ assert len(queryset) == 3
+
+ def test_queryset_size_with_limited_choices(self):
+ limited_target = ForeignKeyTarget(name="limited-target")
+ limited_target.save()
+ queryset = ForeignKeySourceWithLimitedChoicesSerializer().fields["target"].get_queryset()
+ assert len(queryset) == 1
+
class PKNullableForeignKeyTests(TestCase):
def setUp(self):
| Make related fields on ModelSerializer respect `limit_choices_to`
The django `ForeignKey` fields support the keyword argument [`limit_choices_to`](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to), which when present, limits the available choices available by default when a `ModelForm` is created.
The serializer fields that represent relationships do not respect this keyword argument. I propose they should.
If accepted, it appears the place to do this would be in `rest_framework.relations.RelatedField` in the `initialize` method. Open to alternative suggestions on where/how to implement this.
| Agreed. We should also obsolete this comment... https://github.com/tomchristie/django-rest-framework/blob/2.4.0/rest_framework/serializers.py#L826
Added the 3.0 milestone given the incoming serializer redesign.
Any suggestions on approach or considerations?
Can we add a kwargs to the queryset creation?
```
def __init__(self, *args, **kwargs):
queryset = kwargs.pop('queryset', None)
self.limit_choices_to = kwargs.pop('limit_choices_to', None)
self.many = kwargs.pop('many', self.many)
if self.many:
self.widget = self.many_widget
self.form_field_class = self.many_form_field_class
kwargs['read_only'] = kwargs.pop('read_only', self.read_only)
super(RelatedField, self).__init__(*args, **kwargs)
if not self.required:
# Accessed in ModelChoiceIterator django/forms/models.py:1034
# If set adds empty choice.
self.empty_label = BLANK_CHOICE_DASH[0][1]
self.queryset = queryset.filter(**self.limit_choices_to)
```
> Can we add a kwargs to the queryset creation?
There's two parts to this issue.
Firstly - supporting the extra keyword argument in relational fields.
Secondly - ensuring the automatically generated fields for `ModelSerializer` have `limit_choices_to` automatically set.
Here are the cases I see. Lemme know if this behavior seems wrong.
1. Fully auto-generated relation field: should limit if model field has `limit_choices_to` set
2. declared relation field with neither `queryset` or `limit_choices_to` field set: should limit if model field has `limit_choices_to` set
3. declared relation field with `queryset` declared and without `limit_choices_to` set where the model field has `limit_choices_to` set: The user has explicitly declared a queryset so I don't think we should modify it.
4. declared relation field with `limit_choices_to` declared and no `queryset` declared: Should limit choices based on the `limit_choices_to` that was declared on the serializer field.
5. declared relation field with both `limit_choices_to` and `queryset` declared: I think that since both were declared, that it makes sense to go ahead and apply the limit choices to filtering to the provided queryset.
Number 3 is the only one that has any ambiguity to me. It seems like it could be undesirable or unexpected behavior for the queryset to be modified in this case.
I think I'd agree with all that, yup.
I'm hoping to take a stab at this sometime this weekend. Tom, those are
the two things I had in mind.
On Sep 6, 2014 12:26 AM, "Tom Christie" [email protected] wrote:
> Can we add a kwargs to the queryset creation?
>
> There's two parts to this issue.
>
> Firstly - supporting the extra keyword argument in relational fields.
> Secondly - ensuring the automatically generated fields for ModelSerializer
> have limit_choices_to automatically set.
>
> —
> Reply to this email directly or view it on GitHub
> https://github.com/tomchristie/django-rest-framework/issues/1811#issuecomment-54704147
> .
I opened up #1843 with my first stab at this. Tests passed locally, though I don't have all of the python versions tox wants to test against. Interested in feedback on my approach.
Specifically:
1. I'm a little unsure about my approach for setting `limit_choices_to` inside of of the `initialize` when it needs to be pulled from the parent model. It feels heavy.
2. I think I've got gaps in my test coverage but I don't know where. I tested with `RelatedField` but I'm not sure whether I need to do any deeper testing using things like `PrimaryKeyRelatedField` or `HyperlinkedRelatedField`
3. It felt weird to copy over the `get_limit_choices_to` method from django, but it seemed like an established way to do that so... Not sure if that's bad form.
4. The additions to the documentation feel thin.
On review it's not clear to me if we need to support `limit_choices_to` as an initializer itself, or if we should just respect it on automatically created fields, but apply it to the initial queryset that's passed. Thoughts?
Actually given that the Django docs state that limit_choices_to may be re-evaluated multiple times...
- When instantiating the form.
- During validation.
I'm not sure if my suggestion is valid or not.
I'm not sure I follow your self-rebuttal about it being re-evaluated and how that applies.
I think it's a convenient way to limit the available choices to a field without having to actually provide a queryset. I'm also not sure that convenience is worth the maintenance cost. In general I'm not married to it and don't have a solid enough picture of the future of serializers to make this decision myself. I think I'm +0.
> I'm also not sure that convenience is worth the maintenance cost.
Yeah :-| whole lot of code there.
What's the best way for us to figure this out. Would you like a second PR that supports `limit_choices_to` only on generated fields, and does not introduce a new kwarg into `RelatedField`?
Honestly, I'd say defer this until after 3.0. That won't be all that far off and we'll be in a better position to assess then.
Works for me. I'll try to keep up with 3.0 development.
On Sep 8, 2014 1:15 PM, "Tom Christie" [email protected] wrote:
> Honestly, I'd say defer this until after 3.0. That won't be all that far
> off and we'll be in a better position to assess then.
>
> —
> Reply to this email directly or view it on GitHub
> https://github.com/tomchristie/django-rest-framework/issues/1811#issuecomment-54872007
> .
Milestoning to 3.0.2 as I don't think it'd be too hard to resolve this.
Happy to do the lifting on this if you give me some direction as to how you would prefer this be implemented.
Unless an option in the `limit_to` dict is a callable it'd make sense to simply apply it as a filter to the initial queryset on the serializer relationship.
Given that, the only case where we'd need to support `filter_to` as an option on serializer relations would be if the options are callables. To enforce consistency in codebases we should make `filter_to` on a serializer relationship actually error out if it's _not_ a callable.
We could also do something nifty, like use the same `set_context` style as we use on default callables. These are class callables that also have a `set_context` method that is initially called by the serailizer field directly before the callable is invoked. This allows us to eg implement a `CurrentUser` callable. See: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py#L119-127
It's a slightly complex bit of API, but it's then pretty nice that we can do stuff like filter related fields to only be the instances that belong to the requesting user.
Also refs: #1985.
Also note that serializer representations ought to include any filtering clauses.
This is open since 2014. I just ran into the same problem. What is a definite answer on how to solve this?
Someone needs to step in and update #1843
IMHO DRF should respect limit_choices_to , is not so uncommon limit a FK to is_active=True the solution provide in #3605 , worked for me i.e. override class PrimaryKeyRelatedField(RelatedField):
with my custom queryset seems that work :
class CustomForeignKey(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
return Table.objects.filter(is_active=True)
class Serializer(serializers.ModelSerializer):
(...)
table= CustomForeignKey()
class Meta:
(...)
even more easy is :
class Serializer(serializers.ModelSerializer):
(...)
table = serializers.PrimaryKeyRelatedField(queryset=Table.objects.filter(is_active=True))
class Meta:
(...) | 2018-12-20T17:05:18 |
encode/django-rest-framework | 6,380 | encode__django-rest-framework-6380 | [
"6379"
] | 7749e4e3bed56e0f3e7775b0b1158d300964f6c0 | diff --git a/rest_framework/versioning.py b/rest_framework/versioning.py
--- a/rest_framework/versioning.py
+++ b/rest_framework/versioning.py
@@ -75,6 +75,9 @@ class URLPathVersioning(BaseVersioning):
def determine_version(self, request, *args, **kwargs):
version = kwargs.get(self.version_param, self.default_version)
+ if version is None:
+ version = self.default_version
+
if not self.is_allowed_version(version):
raise exceptions.NotFound(self.invalid_version_message)
return version
| URLPathVersioning: Use Default Version when It's None (Not Invalid)
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Allowed Versions: v1, v2
Default Version: v2 (It's latest version as often)
My URL Pattern: `api/((?P<version>(\w){2})/)?users/`
## Expected behavior
1- When GET `api/v1/users/`: get users data according to version v1.
2- When GET `api/users/` : get users data according to Default-Version.
## Actual behavior
for Case 1: get users data according to version v1.
for Case 2: get 404 error: "Invalid version in URL path."
I think it makes sense when client didn't specified version in URI, he expects get response from latest version as often (not getting error)!
| 2018-12-24T08:30:42 |
||
encode/django-rest-framework | 6,405 | encode__django-rest-framework-6405 | [
"6368"
] | 4bb9a3c48427867ef1e46f7dee945a4c25a4f9b8 | diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py
--- a/rest_framework/__init__.py
+++ b/rest_framework/__init__.py
@@ -8,10 +8,10 @@
"""
__title__ = 'Django REST framework'
-__version__ = '3.9.0'
+__version__ = '3.9.1'
__author__ = 'Tom Christie'
__license__ = 'BSD 2-Clause'
-__copyright__ = 'Copyright 2011-2018 Tom Christie'
+__copyright__ = 'Copyright 2011-2019 Encode OSS Ltd'
# Version synonym
VERSION = __version__
| Upgrade to bootstrap 3.4.0 to fix XSS vulnerability
## Description
Picking up Bootstrap `3.4.0` to fix an XSS vulnerability found in `3.3.7`
refs #6178
| @carltongibson fyi. Let me know if there are any additional actions.
No diff to the CSS?
@carltongibson Completely forgot about the CSS. They should be added now.
The diff to `bootstrap-theme.min.css` is weird though, it doesn't even match the old 3.3.7 upstream: https://github.com/twbs/bootstrap/blob/v3.3.7/dist/css/bootstrap-theme.min.css
Not entirely sure what's going on there. | 2019-01-16T12:48:05 |
|
encode/django-rest-framework | 6,416 | encode__django-rest-framework-6416 | [
"6366"
] | 271c4c59209258efdc1ce8bfb3f075a452120893 | diff --git a/rest_framework/management/commands/generateschema.py b/rest_framework/management/commands/generateschema.py
--- a/rest_framework/management/commands/generateschema.py
+++ b/rest_framework/management/commands/generateschema.py
@@ -32,8 +32,10 @@ def handle(self, *args, **options):
self.stdout.write(output.decode('utf-8'))
def get_renderer(self, format):
- return {
- 'corejson': CoreJSONRenderer(),
- 'openapi': OpenAPIRenderer(),
- 'openapi-json': JSONOpenAPIRenderer()
+ renderer_cls = {
+ 'corejson': CoreJSONRenderer,
+ 'openapi': OpenAPIRenderer,
+ 'openapi-json': JSONOpenAPIRenderer,
}[format]
+
+ return renderer_cls()
| pyyaml required for openapi-json schemas
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
- (assuming DRF is set up and has API endpoints for which to generate a schema)
- Install coreapi, but not pyyaml
- run `python manage.py generateschema --format=openapi-json
## Expected behavior
- The openapi-json schema is printed to stdout
## Actual behavior
```
Traceback (most recent call last):
File "./manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.7/site-packages/rest_framework/management/commands/generateschema.py", line 30, in handle
renderer = self.get_renderer(options['format'])
File "/usr/local/lib/python3.7/site-packages/rest_framework/management/commands/generateschema.py", line 37, in get_renderer
'openapi': OpenAPIRenderer(),
File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 1033, in __init__
assert yaml, 'Using OpenAPIRenderer, but `pyyaml` is not installed.'
AssertionError: Using OpenAPIRenderer, but `pyyaml` is not installed.
```
Additional Details
------------------
Installing pyyaml fixes the problem, but it shouldn't be required if only json formatted schemas are being generated.
Additionally, I found the way that it failed to be misleading - I logged #6359 because the stack trace and error message really looked like the format parameter was being ignored, since `--format openapi-json` uses `JsonOpenAPIRenderer`, not `OpenAPIRenderer`.
| 2019-01-21T19:59:46 |
||
encode/django-rest-framework | 6,417 | encode__django-rest-framework-6417 | [
"6363"
] | 0ac20a3d8eb565f1845e2c9beeeb02b296526749 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1725,9 +1725,6 @@ def to_internal_value(self, data):
return self.run_child_validation(data)
def to_representation(self, value):
- """
- List of object instances -> List of dicts of primitive datatypes.
- """
return {
six.text_type(key): self.child.to_representation(val) if val is not None else None
for key, val in value.items()
| Incorrect docstring on fields.DictField:to_representation
Remnants of ListField copy-paste confused me when inspecting code.
https://github.com/encode/django-rest-framework/blob/master/rest_framework/fields.py#L1729
| 2019-01-21T20:06:03 |
||
encode/django-rest-framework | 6,429 | encode__django-rest-framework-6429 | [
"6258"
] | f54a220d8f3c8649b84188c7e2a6dc2ef3be6f4c | diff --git a/rest_framework/schemas/views.py b/rest_framework/schemas/views.py
--- a/rest_framework/schemas/views.py
+++ b/rest_framework/schemas/views.py
@@ -31,3 +31,11 @@ def get(self, request, *args, **kwargs):
if schema is None:
raise exceptions.PermissionDenied()
return Response(schema)
+
+ def handle_exception(self, exc):
+ # Schema renderers do not render exceptions, so re-perform content
+ # negotiation with default renderers.
+ self.renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
+ neg = self.perform_content_negotiation(self.request, force=True)
+ self.request.accepted_renderer, self.request.accepted_media_type = neg
+ return super(SchemaView, self).handle_exception(exc)
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -1304,3 +1304,13 @@ def test_foo(self):
def test_FOO(self):
assert not self._test('FOO')
+
+
[email protected](not coreapi, reason='coreapi is not installed')
+def test_schema_handles_exception():
+ schema_view = get_schema_view(permission_classes=[DenyAllUsingPermissionDenied])
+ request = factory.get('/')
+ response = schema_view(request)
+ response.render()
+ assert response.status_code == 403
+ assert "You do not have permission to perform this action." in str(response.content)
| 3.9: AttributeError when Schema Endpoint requires authentication
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
* Update to 3.9
* Implement Schema Endpoint as described in Announcement: https://www.django-rest-framework.org/community/3.9-announcement/
```
from rest_framework.schemas import get_schema_view
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/'
)
urlpatterns = [
url('^schema.json$', schema_view),
]
```
* Set Permission `IsAuthenticated`:
```
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
```
* Open `/schema.json`
## Expected behavior
* Authorization Error
## Actual behavior
```
Internal Server Error: /schema.json
Traceback (most recent call last):
File "./.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "./.venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 158, in _get_response
response = self.process_exception_by_middleware(e, request)
File "./.venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response
response = response.render()
File "./.venv/lib/python3.6/site-packages/django/template/response.py", line 106, in render
self.content = self.rendered_content
File "./.venv/lib/python3.6/site-packages/rest_framework/response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "./.venv/lib/python3.6/site-packages/rest_framework/renderers.py", line 732, in render
context = self.get_context(data, accepted_media_type, renderer_context)
File "./.venv/lib/python3.6/site-packages/rest_framework/renderers.py", line 687, in get_context
'content': self.get_content(renderer, data, accepted_media_type, renderer_context),
File "./.venv/lib/python3.6/site-packages/rest_framework/renderers.py", line 423, in get_content
content = renderer.render(data, accepted_media_type, renderer_context)
File "./.venv/lib/python3.6/site-packages/rest_framework/renderers.py", line 1036, in render
structure = self.get_structure(data)
File "./.venv/lib/python3.6/site-packages/rest_framework/renderers.py", line 1016, in get_structure
'title': data.title,
AttributeError: 'dict' object has no attribute 'title'
```
```
.venv/lib/python3.6/site-packages/rest_framework/renderers.py in get_structure
data = {'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')}
```
| I'm having the same issue after upgrading to 3.9. Am able to work around the issue by logging by other means, but the schema view results in the following error:
```Traceback (most recent call last):
File "/Users/.../anaconda3/envs/datjango/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/.../anaconda3/envs/datjango/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/.../anaconda3/envs/datjango/lib/python3.6/site-packages/django/core/handlers/base.py", line 154, in _get_response
response = response.render()
File "/Users/.../anaconda3/envs/datjango/lib/python3.6/site-packages/django/template/response.py", line 106, in render
self.content = self.rendered_content
File "/Users/.../anaconda3/envs/datjango/lib/python3.6/site-packages/rest_framework/response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/Users/.../anaconda3/envs/datjango/lib/python3.6/site-packages/rest_framework/renderers.py", line 732, in render
context = self.get_context(data, accepted_media_type, renderer_context)
File "/Users/.../anaconda3/envs/datjango/lib/python3.6/site-packages/rest_framework/renderers.py", line 687, in get_context
'content': self.get_content(renderer, data, accepted_media_type, renderer_context),
File "/Users/.../anaconda3/envs/datjango/lib/python3.6/site-packages/rest_framework/renderers.py", line 423, in get_content
content = renderer.render(data, accepted_media_type, renderer_context)
File "/Users/.../anaconda3/envs/datjango/lib/python3.6/site-packages/rest_framework/renderers.py", line 1036, in render
structure = self.get_structure(data)
File "/Users/.../anaconda3/envs/datjango/lib/python3.6/site-packages/rest_framework/renderers.py", line 1016, in get_structure
'title': data.title,
AttributeError: 'dict' object has no attribute 'title'
```
I duplicated the error with a clean install of Django==2.1.2 and djangorestframework==3.9.0 with "urls.py" as:
```
from django.contrib import admin
from django.urls import path, include
from rest_framework.schemas import get_schema_view
from rest_framework.renderers import JSONOpenAPIRenderer
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/',
renderer_classes=[JSONOpenAPIRenderer]
)
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')),
path('api/', get_schema_view()),
]
```
Let me know if there is any info I can provide to help.
Thanks for the minimal reproduction and traceback.
cc @carltongibson?
OK, so yes...
This looks to me like a variant of the same issue that came up with 3.6, when we introduced the interactive docs. Basically (I guess) the schema view is picking up `DEFAULT_AUTHENTICATION_CLASSES`. See e.g. #5399, #5309, #5448...
`get_schema_view()` takes `authentication_classes`. First this would be to try passing an empty list in there...
(Does that help?)
Is this a duplicate of #6258?
@carltongibson this is #6258 😄
Brough you this ☕️
> ... this is #6258 😄
Thought it looked relevant.
> Brough you this ☕️
Thanks!
For those that are stuck here, you can just pass the `AllowAny` permission to the `schema_view` as a workaround.
schema_view = get_schema_view(
title="My API",
permission_classes=[rest_framework.permissions.AllowAny],
)
FYI, I'm still stuck here. I have a custom permission class that doesn't require authentication, so the workaround proposed by @devsnd doesn't work for me. As another alternative fix, I override the default renderer:
```python
from rest_framework import exceptions, renderers
class OpenAPIRendererV2(renderers.OpenAPIRenderer):
# temporary fix for: https://github.com/encode/django-rest-framework/issues/6258
def get_structure(self, data):
if "detail" in data and isinstance(data["detail"], exceptions.ErrorDetail):
return {"errror": str(data["detail"])}
return super().get_structure(data)
``` | 2019-01-31T13:45:14 |
encode/django-rest-framework | 6,472 | encode__django-rest-framework-6472 | [
"6470"
] | 07c5c968ce8b06c7ebbcc91a070aa492510611b2 | diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py
--- a/rest_framework/utils/field_mapping.py
+++ b/rest_framework/utils/field_mapping.py
@@ -251,7 +251,9 @@ def get_relation_kwargs(field_name, relation_info):
limit_choices_to = model_field and model_field.get_limit_choices_to()
if limit_choices_to:
- kwargs['queryset'] = kwargs['queryset'].filter(**limit_choices_to)
+ if not isinstance(limit_choices_to, models.Q):
+ limit_choices_to = models.Q(**limit_choices_to)
+ kwargs['queryset'] = kwargs['queryset'].filter(limit_choices_to)
if has_through_model:
kwargs['read_only'] = True
| diff --git a/tests/models.py b/tests/models.py
--- a/tests/models.py
+++ b/tests/models.py
@@ -59,6 +59,13 @@ class ForeignKeySourceWithLimitedChoices(RESTFrameworkModel):
on_delete=models.CASCADE)
+class ForeignKeySourceWithQLimitedChoices(RESTFrameworkModel):
+ target = models.ForeignKey(ForeignKeyTarget, help_text='Target',
+ verbose_name='Target',
+ limit_choices_to=models.Q(name__startswith="limited-"),
+ on_delete=models.CASCADE)
+
+
# Nullable ForeignKey
class NullableForeignKeySource(RESTFrameworkModel):
name = models.CharField(max_length=100)
diff --git a/tests/test_relations_pk.py b/tests/test_relations_pk.py
--- a/tests/test_relations_pk.py
+++ b/tests/test_relations_pk.py
@@ -5,10 +5,11 @@
from rest_framework import serializers
from tests.models import (
- ForeignKeySource, ForeignKeySourceWithLimitedChoices, ForeignKeyTarget,
- ManyToManySource, ManyToManyTarget, NullableForeignKeySource,
- NullableOneToOneSource, NullableUUIDForeignKeySource, OneToOnePKSource,
- OneToOneTarget, UUIDForeignKeyTarget
+ ForeignKeySource, ForeignKeySourceWithLimitedChoices,
+ ForeignKeySourceWithQLimitedChoices, ForeignKeyTarget, ManyToManySource,
+ ManyToManyTarget, NullableForeignKeySource, NullableOneToOneSource,
+ NullableUUIDForeignKeySource, OneToOnePKSource, OneToOneTarget,
+ UUIDForeignKeyTarget
)
@@ -378,6 +379,18 @@ def test_queryset_size_with_limited_choices(self):
queryset = ForeignKeySourceWithLimitedChoicesSerializer().fields["target"].get_queryset()
assert len(queryset) == 1
+ def test_queryset_size_with_Q_limited_choices(self):
+ limited_target = ForeignKeyTarget(name="limited-target")
+ limited_target.save()
+
+ class QLimitedChoicesSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = ForeignKeySourceWithQLimitedChoices
+ fields = ("id", "target")
+
+ queryset = QLimitedChoicesSerializer().fields["target"].get_queryset()
+ assert len(queryset) == 1
+
class PKNullableForeignKeyTests(TestCase):
def setUp(self):
| limit_choices_to and Q objects
After upgrading from 3.8 -> 3.9 I've encountered an issue with the new limit_choices_to foreign key changes.
```
filter() argument after ** must be a mapping, not Q
```
It seems the issue was documented in the original merge and a fix was proposed but I can't find an existing PR that has addressed it - nor does the proposed fix exist in master
https://github.com/encode/django-rest-framework/pull/6371#issuecomment-455626461
## Checklist
- [ ] I have verified that that issue exists against the `master` branch of Django REST framework.
- [X] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [X] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [X] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [X] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
model with FK that contains a limit_choices_to with Q object reference ( instead of Dictionary)
## Expected behavior
no errors, code works as expected if a dictionary is passed instead
## Actual behavior
error thrown,
```
filter() argument after ** must be a mapping, not Q
```
| Okay - we'd happily consider a pull request based on https://github.com/usetaptap/django-rest-framework/commit/607059def41dcf8563979629514c3b8d31f0f3d2 | 2019-02-25T10:32:55 |
encode/django-rest-framework | 6,514 | encode__django-rest-framework-6514 | [
"6151"
] | 78cdae69997c9fd95211ec15fb4e21f4cd45e30a | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -963,10 +963,11 @@ class DecimalField(Field):
MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None,
- localize=False, rounding=None, **kwargs):
+ localize=False, rounding=None, normalize_output=False, **kwargs):
self.max_digits = max_digits
self.decimal_places = decimal_places
self.localize = localize
+ self.normalize_output = normalize_output
if coerce_to_string is not None:
self.coerce_to_string = coerce_to_string
if self.localize:
@@ -1079,6 +1080,9 @@ def to_representation(self, value):
quantized = self.quantize(value)
+ if self.normalize_output:
+ quantized = quantized.normalize()
+
if not coerce_to_string:
return quantized
if self.localize:
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -1251,6 +1251,27 @@ def test_part_precision_string_quantized_value_for_decimal(self):
assert value == expected_digit_tuple
+class TestNormalizedOutputValueDecimalField(TestCase):
+ """
+ Test that we get the expected behavior of on DecimalField when normalize=True
+ """
+
+ def test_normalize_output(self):
+ field = serializers.DecimalField(max_digits=4, decimal_places=3, normalize_output=True)
+ output = field.to_representation(Decimal('1.000'))
+ assert output == '1'
+
+ def test_non_normalize_output(self):
+ field = serializers.DecimalField(max_digits=4, decimal_places=3, normalize_output=False)
+ output = field.to_representation(Decimal('1.000'))
+ assert output == '1.000'
+
+ def test_normalize_coeherce_to_string(self):
+ field = serializers.DecimalField(max_digits=4, decimal_places=3, normalize_output=True, coerce_to_string=False)
+ output = field.to_representation(Decimal('1.000'))
+ assert output == Decimal('1')
+
+
class TestNoDecimalPlaces(FieldValues):
valid_inputs = {
'0.12345': Decimal('0.12345'),
| DecimalField: str value without trailing zeros
I guess, `coerce_to_string=True` in DecimalField should safely remove trailing zeros and `coerce_to_string=False` should leave value unchanged. If it's true - why my values are with trailing zeros?
In old version of DRF values were without trailing zeros as I remember
```
| vaue | 24.471635150166826 |
value = serializers.DecimalField(decimal_places=30, max_digits=35, default=0, coerce_to_string=True)
>> 24.471635150166826000000000000000
```
| Just ran into this. I am using it to store SI multipliers for values series and having a series in kilo{something} it is not needed to output "1000.000000000000" in my JSON and its annoying to have to remember the amount of decimal places for simple tests.
This on the DecimalField seems to do it:
``` python
def quantize(self, value):
"""
Quantize the decimal value to the configured precision.
"""
if self.decimal_places is None:
return value
context = decimal.getcontext().copy()
if self.max_digits is not None:
context.prec = self.max_digits
return value.quantize(
decimal.Decimal('.1') ** self.decimal_places,
rounding=self.rounding,
context=context
)
```
Maybe another option is to use .normalize() on the value?
``` python
decimal.Decimal('0.001000000).normalize()`
>> decimal.Decimal('0.001')
# but the following might be a problem for serializing but according to json standard for number it should be ok. (https://json.org/)
decimal.Decimal('1000.00000000).normalize()
>> decimal.Decimal('1E+3')
```
``` python
multiplier = fields.DecimalField(max_digits=25, decimal_places=12, normalize=True)
```
Another option could be to create a subclass of the field that makes the quantize function do nothing. but that would get problems if you got a result that has more decimal places than wanted and there would be no rounding.
Not sure what the best way to solve it would be.
@carltongibson added the rounding parameter on DecimalField. Maybe he could give some insight to what could be a good direction to solve the problem.
Seems to me like adding a normalize option would be good.
> Another option could be to create a subclass...
This is always the first option. Capture the exact behaviour you need for your application. Then propose a change if you think it appropriate, with a set of test cases that show exactly the what behaviour is altered.
I suspect all the options here are a matter of choice. If we change the default behaviour someone else will complain. I'm not sure there's much we can do.
I assume this is related to changes in #4075 or #4339. Also, this sounds related to #6311, which has additional, extensive discussion. Not 100% sure, since I don't have the bandwidth to read all of these threads extensively.
in #6311 @tomchristie say that he would accept `strip_trailing_zeros` flag. Would a `normalize` argument achieving pretty much the same thing also be acceptable?
I think the normalize flag could be added without breaking any existing stuff. I'm working on a deadline right now but afterwards I could try and put together a PR for it.
Hey @Krolken. A PR is always worth looking at. 🙂 | 2019-03-19T16:23:41 |
encode/django-rest-framework | 6,593 | encode__django-rest-framework-6593 | [
"6504"
] | db65282163b91688367095459328de7e9dab94d8 | diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py
--- a/rest_framework/pagination.py
+++ b/rest_framework/pagination.py
@@ -589,7 +589,7 @@ def get_next_link(self):
if not self.has_next:
return None
- if self.cursor and self.cursor.reverse and self.cursor.offset != 0:
+ if self.page and self.cursor and self.cursor.reverse and self.cursor.offset != 0:
# If we're reversing direction and we have an offset cursor
# then we cannot use the first position we find as a marker.
compare = self._get_position_from_instance(self.page[-1], self.ordering)
@@ -597,12 +597,14 @@ def get_next_link(self):
compare = self.next_position
offset = 0
+ has_item_with_unique_position = False
for item in reversed(self.page):
position = self._get_position_from_instance(item, self.ordering)
if position != compare:
# The item in this position and the item following it
# have different positions. We can use this position as
# our marker.
+ has_item_with_unique_position = True
break
# The item in this position has the same position as the item
@@ -611,7 +613,7 @@ def get_next_link(self):
compare = position
offset += 1
- else:
+ if self.page and not has_item_with_unique_position:
# There were no unique positions in the page.
if not self.has_previous:
# We are on the first page.
@@ -630,6 +632,9 @@ def get_next_link(self):
offset = self.cursor.offset + self.page_size
position = self.previous_position
+ if not self.page:
+ position = self.next_position
+
cursor = Cursor(offset=offset, reverse=False, position=position)
return self.encode_cursor(cursor)
@@ -637,7 +642,7 @@ def get_previous_link(self):
if not self.has_previous:
return None
- if self.cursor and not self.cursor.reverse and self.cursor.offset != 0:
+ if self.page and self.cursor and not self.cursor.reverse and self.cursor.offset != 0:
# If we're reversing direction and we have an offset cursor
# then we cannot use the first position we find as a marker.
compare = self._get_position_from_instance(self.page[0], self.ordering)
@@ -645,12 +650,14 @@ def get_previous_link(self):
compare = self.previous_position
offset = 0
+ has_item_with_unique_position = False
for item in self.page:
position = self._get_position_from_instance(item, self.ordering)
if position != compare:
# The item in this position and the item following it
# have different positions. We can use this position as
# our marker.
+ has_item_with_unique_position = True
break
# The item in this position has the same position as the item
@@ -659,7 +666,7 @@ def get_previous_link(self):
compare = position
offset += 1
- else:
+ if self.page and not has_item_with_unique_position:
# There were no unique positions in the page.
if not self.has_next:
# We are on the final page.
@@ -678,6 +685,9 @@ def get_previous_link(self):
offset = 0
position = self.next_position
+ if not self.page:
+ position = self.previous_position
+
cursor = Cursor(offset=offset, reverse=True, position=position)
return self.encode_cursor(cursor)
| diff --git a/tests/test_pagination.py b/tests/test_pagination.py
--- a/tests/test_pagination.py
+++ b/tests/test_pagination.py
@@ -634,6 +634,52 @@ def test_cursor_pagination(self):
assert isinstance(self.pagination.to_html(), six.text_type)
+ def test_cursor_pagination_current_page_empty_forward(self):
+ # Regression test for #6504
+ self.pagination.base_url = "/"
+
+ # We have a cursor on the element at position 100, but this element doesn't exist
+ # anymore.
+ cursor = pagination.Cursor(reverse=False, offset=0, position=100)
+ url = self.pagination.encode_cursor(cursor)
+ self.pagination.base_url = "/"
+
+ # Loading the page with this cursor doesn't crash
+ (previous, current, next, previous_url, next_url) = self.get_pages(url)
+
+ # The previous url doesn't crash either
+ (previous, current, next, previous_url, next_url) = self.get_pages(previous_url)
+
+ # And point to things that are not completely off.
+ assert previous == [7, 7, 7, 8, 9]
+ assert current == [9, 9, 9, 9, 9]
+ assert next == []
+ assert previous_url is not None
+ assert next_url is not None
+
+ def test_cursor_pagination_current_page_empty_reverse(self):
+ # Regression test for #6504
+ self.pagination.base_url = "/"
+
+ # We have a cursor on the element at position 100, but this element doesn't exist
+ # anymore.
+ cursor = pagination.Cursor(reverse=True, offset=0, position=100)
+ url = self.pagination.encode_cursor(cursor)
+ self.pagination.base_url = "/"
+
+ # Loading the page with this cursor doesn't crash
+ (previous, current, next, previous_url, next_url) = self.get_pages(url)
+
+ # The previous url doesn't crash either
+ (previous, current, next, previous_url, next_url) = self.get_pages(next_url)
+
+ # And point to things that are not completely off.
+ assert previous == [7, 7, 7, 7, 8]
+ assert current == []
+ assert next is None
+ assert previous_url is not None
+ assert next_url is None
+
def test_cursor_pagination_with_page_size(self):
(previous, current, next, previous_url, next_url) = self.get_pages('/?page_size=20')
| IndexError for CursorPagination when queryset changes
## Checklist
- [X] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [x] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
1. Enable CursorPagination
2. Make enough items that there is pagination
3. Go to page 2
4. Delete all items within the shell
5. Refresh the page
6. See error
## Expected behavior
To be honest I'm not sure, maybe an empty page.
## Actual behavior
```
Traceback (most recent call last):
File "/var/env/lib/python3.6/site-packages/django/contrib/staticfiles/handlers.py", line 65, in __call__
return self.application(environ, start_response)
File "/var/env/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 142, in __call__
response = self.get_response(request)
File "/var/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 78, in get_response
response = self._middleware_chain(request)
File "/var/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner
response = response_for_exception(request, exc)
File "/var/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/var/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/var/env/lib/python3.6/site-packages/django_extensions/management/technical_response.py", line 37, in null_technical_500_response
six.reraise(exc_type, exc_value, tb)
File "/var/env/lib/python3.6/site-packages/six.py", line 692, in reraise
raise value.with_traceback(tb)
File "/var/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/var/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/var/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/env/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/var/env/lib/python3.6/site-packages/rest_framework/viewsets.py", line 116, in view
return self.dispatch(request, *args, **kwargs)
File "/var/env/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/var/env/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/var/env/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/var/env/lib/python3.6/site-packages/rest_framework/mixins.py", line 45, in list
return self.get_paginated_response(serializer.data)
File "/var/env/lib/python3.6/site-packages/rest_framework/generics.py", line 180, in get_paginated_response
return self.paginator.get_paginated_response(data)
File "/var/env/lib/python3.6/site-packages/rest_framework/pagination.py", line 781, in get_paginated_response
('previous', self.get_previous_link()),
File "/var/env/lib/python3.6/site-packages/rest_framework/pagination.py", line 643, in get_previous_link
compare = self._get_position_from_instance(self.page[0], self.ordering)
IndexError: list index out of range
```
| I'm going to try and have a go at it. If there's no news from me by April 15, consider I'm not on it anymore.
For the record I can't repoduce when following the exact steps of the ticket, but if I try to go back to page 1 then I have the same traceback. | 2019-04-14T12:53:26 |
encode/django-rest-framework | 6,613 | encode__django-rest-framework-6613 | [
"6577"
] | 59a5a5a868dd1fed12df12f536804338b6d5e233 | diff --git a/rest_framework/compat.py b/rest_framework/compat.py
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -168,7 +168,12 @@ def is_guardian_installed():
"""
django-guardian is optional and only imported if in INSTALLED_APPS.
"""
- if six.PY2:
+ try:
+ import guardian
+ except ImportError:
+ guardian = None
+
+ if six.PY2 and (not guardian or guardian.VERSION >= (1, 5)):
# Guardian 1.5.0, for Django 2.2 is NOT compatible with Python 2.7.
# Remove when dropping PY2.
return False
| DjangoGuardianObjectPermissionsFilter Broken on django 1.11 with python 2.7
This line unconditionally disables django-guardian from being detected with python 2.7 but it should still work with older releases that don't meet the conditions in the comments:
https://github.com/encode/django-rest-framework/blob/29cbe574a384c3bcc09434a3a9c5ff0cb7576b99/rest_framework/compat.py#L172
| We don't test against older Django-guardian versions so there might be other incompatibilities.
If you are confident enough, I'd suggest you override `DjangoObjectPermissionsFilter.__init__()` to skip the installation check (or perform your own).
Can I suggest that you add a warning into the code in the python2 path as currently the code returns a rather confusing error message that guardian is not installed. You have to dig into the code to find out the information about the incompatibility
@carltongibson do you think we'll have releases before merging Python 2.7 removal PR ?
Yeah. good. I had basically thought no. But it might be worth throwing this in quick... Thoughts?
Almost everything merged since 3.9.2 has either been a docs fix or a minor code cleanup. We could release 3.9.3 if it's not too much trouble.
Maybe change the check to:
```python
if six.PY2 and guardian.VERSION >= (1, 5):
return False
```
From #6054, there were issues importing `guardian`, but since this is a runtime check, it might be fine?
OK. Let’s reopen to assess. I’ve been putting off dropping Python 2, so we may as well look at taking advantage of that.
Happy to look at a PR adjusting the compat code here. I don’t mind doing the release.
It might be more like:
```python
if six.PY2 and django.version >= (2, 2) and guardian.VERSION >= (1, 5):
return False
``` | 2019-04-29T13:25:16 |
|
encode/django-rest-framework | 6,659 | encode__django-rest-framework-6659 | [
"3451"
] | 2e7ab9d6c638f6eae9fed95548065693b8d59c3d | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -493,6 +493,11 @@ def validate_empty_values(self, data):
if data is None:
if not self.allow_null:
self.fail('null')
+ # Nullable `source='*'` fields should not be skipped when its named
+ # field is given a null value. This is because `source='*'` means
+ # the field is passed the entire object, which is not null.
+ elif self.source == '*':
+ return (False, None)
return (True, None)
return (False, data)
| diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -317,7 +317,8 @@ def test_validate_list(self):
class TestStarredSource:
"""
- Tests for `source='*'` argument, which is used for nested representations.
+ Tests for `source='*'` argument, which is often used for complex field or
+ nested representations.
For example:
@@ -337,11 +338,28 @@ class NestedSerializer2(serializers.Serializer):
c = serializers.IntegerField()
d = serializers.IntegerField()
- class TestSerializer(serializers.Serializer):
+ class NestedBaseSerializer(serializers.Serializer):
nested1 = NestedSerializer1(source='*')
nested2 = NestedSerializer2(source='*')
- self.Serializer = TestSerializer
+ # nullable nested serializer testing
+ class NullableNestedSerializer(serializers.Serializer):
+ nested = NestedSerializer1(source='*', allow_null=True)
+
+ # nullable custom field testing
+ class CustomField(serializers.Field):
+ def to_representation(self, instance):
+ return getattr(instance, 'foo', None)
+
+ def to_internal_value(self, data):
+ return {'foo': data}
+
+ class NullableFieldSerializer(serializers.Serializer):
+ field = CustomField(source='*', allow_null=True)
+
+ self.Serializer = NestedBaseSerializer
+ self.NullableNestedSerializer = NullableNestedSerializer
+ self.NullableFieldSerializer = NullableFieldSerializer
def test_nested_validate(self):
"""
@@ -356,6 +374,12 @@ def test_nested_validate(self):
'd': 4
}
+ def test_nested_null_validate(self):
+ serializer = self.NullableNestedSerializer(data={'nested': None})
+
+ # validation should fail (but not error) since nested fields are required
+ assert not serializer.is_valid()
+
def test_nested_serialize(self):
"""
An object can be serialized into a nested representation.
@@ -364,6 +388,20 @@ def test_nested_serialize(self):
serializer = self.Serializer(instance)
assert serializer.data == self.data
+ def test_field_validate(self):
+ serializer = self.NullableFieldSerializer(data={'field': 'bar'})
+
+ # validation should pass since no internal validation
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'foo': 'bar'}
+
+ def test_field_null_validate(self):
+ serializer = self.NullableFieldSerializer(data={'field': None})
+
+ # validation should pass since no internal validation
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'foo': None}
+
class TestIncorrectlyConfigured:
def test_incorrect_field_name(self):
| None and source="*" compatibility
This:
``` python
class TestField(serializers.Field):
def __init__(self, *args, **kwargs):
kwargs['source'] = '*'
super(TestField, self).__init__(*args, **kwargs)
def to_representation(self, value):
return value
def to_internal_value(self, data):
return data
class TestSerializer(serializers.Serializer):
f = TestField(allow_null=True)
s = TestSerializer(data={"f": None})
s.is_valid(raise_exception=True)
```
Results in :
```
131. s.is_valid(raise_exception=True)
File "/projects/test/env/local/lib/python2.7/site-packages/rest_framework/serializers.py" in is_valid
202. self._validated_data = self.run_validation(self.initial_data)
File "/projects/test/env/local/lib/python2.7/site-packages/rest_framework/serializers.py" in run_validation
396. value = self.to_internal_value(data)
File "projects/test/env/local/lib/python2.7/site-packages/rest_framework/serializers.py" in to_internal_value
436. set_value(ret, field.source_attrs, validated_value)
File "projects/test/env/local/lib/python2.7/site-packages/rest_framework/fields.py" in set_value
101. dictionary.update(value)
File "/projects/test/env/lib/python2.7/_abcoll.py" in update
547. for key, value in other:
```
Tested: 3.1.1, 3.2.4
What's expected behavior here?
| Probably worth expanding on this with what you're expecting to see here?
Unless i'm missing something, None in data. Non null values work just fine.
I'm having problems when I change the field of ModelSerializer to relate a serializer field name to a model field name using source argument.
``` python
class ArticleSerializer(serializer.ModelSerializer):
user_id = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), source='user',
required=False, allow_null=True)
```
I solved overwriting the `to_internal_value` and `to_representation` method of PrimaryKeryRelatedField. But I don't think this is the best solution:
``` python
class AllowNullPKField(serializers.PrimaryKeyRelatedField):
def to_internal_value(self, data):
if data == 'None':
return None
return super(AllowNullPKField, self).to_internal_value(data)
def to_representation(self, value):
if value is None:
return None
return super(AllowNullPKField, self).to_representation(value)
class ArticleSerializer(serializer.ModelSerializer):
user_id = AllowNullPKField(
queryset=User.objects.all(), source='user',
required=False, allow_null=True)
```
| 2019-05-09T02:12:50 |
encode/django-rest-framework | 6,711 | encode__django-rest-framework-6711 | [
"6667"
] | 19ca86d8d69d37d0e953837fbba1c1934d31dc75 | diff --git a/rest_framework/views.py b/rest_framework/views.py
--- a/rest_framework/views.py
+++ b/rest_framework/views.py
@@ -350,9 +350,13 @@ def check_throttles(self, request):
Check if request should be throttled.
Raises an appropriate exception if the request is throttled.
"""
+ throttle_durations = []
for throttle in self.get_throttles():
if not throttle.allow_request(request, self):
- self.throttled(request, throttle.wait())
+ throttle_durations.append(throttle.wait())
+
+ if throttle_durations:
+ self.throttled(request, max(throttle_durations))
def determine_version(self, request, *args, **kwargs):
"""
| diff --git a/tests/test_throttling.py b/tests/test_throttling.py
--- a/tests/test_throttling.py
+++ b/tests/test_throttling.py
@@ -30,6 +30,11 @@ class User3MinRateThrottle(UserRateThrottle):
scope = 'minutes'
+class User6MinRateThrottle(UserRateThrottle):
+ rate = '6/min'
+ scope = 'minutes'
+
+
class NonTimeThrottle(BaseThrottle):
def allow_request(self, request, view):
if not hasattr(self.__class__, 'called'):
@@ -38,6 +43,13 @@ def allow_request(self, request, view):
return False
+class MockView_DoubleThrottling(APIView):
+ throttle_classes = (User3SecRateThrottle, User6MinRateThrottle,)
+
+ def get(self, request):
+ return Response('foo')
+
+
class MockView(APIView):
throttle_classes = (User3SecRateThrottle,)
@@ -80,7 +92,8 @@ def set_throttle_timer(self, view, value):
"""
Explicitly set the timer, overriding time.time()
"""
- view.throttle_classes[0].timer = lambda self: value
+ for cls in view.throttle_classes:
+ cls.timer = lambda self: value
def test_request_throttling_expires(self):
"""
@@ -115,6 +128,37 @@ def test_request_throttling_is_per_user(self):
"""
self.ensure_is_throttled(MockView, 200)
+ def test_request_throttling_multiple_throttles(self):
+ """
+ Ensure all throttle classes see each request even when the request is
+ already being throttled
+ """
+ self.set_throttle_timer(MockView_DoubleThrottling, 0)
+ request = self.factory.get('/')
+ for dummy in range(4):
+ response = MockView_DoubleThrottling.as_view()(request)
+ assert response.status_code == 429
+ assert int(response['retry-after']) == 1
+
+ # At this point our client made 4 requests (one was throttled) in a
+ # second. If we advance the timer by one additional second, the client
+ # should be allowed to make 2 more before being throttled by the 2nd
+ # throttle class, which has a limit of 6 per minute.
+ self.set_throttle_timer(MockView_DoubleThrottling, 1)
+ for dummy in range(2):
+ response = MockView_DoubleThrottling.as_view()(request)
+ assert response.status_code == 200
+
+ response = MockView_DoubleThrottling.as_view()(request)
+ assert response.status_code == 429
+ assert int(response['retry-after']) == 59
+
+ # Just to make sure check again after two more seconds.
+ self.set_throttle_timer(MockView_DoubleThrottling, 2)
+ response = MockView_DoubleThrottling.as_view()(request)
+ assert response.status_code == 429
+ assert int(response['retry-after']) == 58
+
def ensure_response_header_contains_proper_throttle_field(self, view, expected_headers):
"""
Ensure the response returns an Retry-After field with status and next attributes
| Check each throttle class before returning a 429 response
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [ ] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
- Add several throttling classes to a view
## Expected behavior
- Each request is added to the history of all throttling classes, even when one of them disallows the request
## Actual behavior
- If a single throttling class disallows the request, the other throttling classes never see the request and it never gets added to their history
This is because [DRF checks throttling classes in a loop and raises as soon as it finds one failing](https://github.com/encode/django-rest-framework/blob/9811a29a5a1348f1a5de30a9a7a5d0f8d2fd4843/rest_framework/views.py#L353-L355):
```python
for throttle in self.get_throttles():
if not throttle.allow_request(request, self):
self.throttled(request, throttle.wait())
```
It's faster, but this makes throttling with multiple classes less efficient as some throttling classes never see some of the requests.
See also https://github.com/encode/django-rest-framework/issues/6666
It could be done as a third-party library, but I believe it's better to have this change in DRF itself to make throttling more efficient against brute-force attacks. I haven't written the pull request yet, but it's relatively trivial and I'd be willing to do it, I just want to validate the idea first.
| Example of where it can matter:
Consider a view protected with the following classes, using `throttling_classes = (TestBurstThrottle, Test SustainedThrottle)`:
```python
class TestBurstThrottle(AnonRateThrottle):
rate = '3/min'
class TestSustainedThrottle(AnonRateThrottle):
rate = '10/hour'
```
If someone makes 4 requests in quick succession, the 4th one is blocked and they need to wait one minute to continue. But once that minute is up, instead of being allowed 6 more requests for the hour, they're allowed 7, because the 4th request was never sent to the `TestSustainedThrottle` class.
Is this different to #6666?
In any case - yes sounds like it'd be a valid change. Happy to consider pull requests towards it.
It's different, yes: #6666 would make throttle failures count towards history, but when there are multiple throttling classes set, that still wouldn't be enough, the `check_throttles()` code in the views would bail before even sending the request to the other throttling classes. Both fixes are nice to have but work independently.
| 2019-05-23T11:44:58 |
encode/django-rest-framework | 6,722 | encode__django-rest-framework-6722 | [
"6317"
] | 6aac9d2be1f3a40a85ca8068ceabf5d4507994e4 | diff --git a/rest_framework/compat.py b/rest_framework/compat.py
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -128,7 +128,7 @@ def distinct(queryset, base):
View.http_method_names = View.http_method_names + ['patch']
-# Markdown is optional (version 2.6+ required)
+# Markdown is optional (version 3.0+ required)
try:
import markdown
@@ -206,7 +206,7 @@ def repl(m):
return ret.split("\n")
def md_filter_add_syntax_highlight(md):
- md.preprocessors.add('highlight', CodeBlockPreprocessor(), "_begin")
+ md.preprocessors.register(CodeBlockPreprocessor(), 'highlight', 40)
return True
else:
def md_filter_add_syntax_highlight(md):
| DeprecationWarning with markdown
Code: https://github.com/encode/django-rest-framework/blob/bf9533ae37affc64638c21f551250914dd5f80be/rest_framework/compat.py#L263-L265
Warning:
> DeprecationWarning: Using the add method to register a processor or pattern is deprecated. Use the `register` method instead.
Relevant commit in markdown: https://github.com/Python-Markdown/markdown/commit/6ee07d2735d86d7a3d0b31c3409d42d31997a96c
| This'd probably be a good one for a contributor to jump onto, right?
*waves to the world*
Note - we added the "good first issue" label a while back, which theoretically helps new users find issues like these? | 2019-05-31T20:45:35 |
|
encode/django-rest-framework | 6,752 | encode__django-rest-framework-6752 | [
"6751",
"6751"
] | 72de94a05d2038f2557d4c7a3b16cf20416fb123 | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -973,14 +973,22 @@ def update(self, instance, validated_data):
# Note that unlike `.create()` we don't need to treat many-to-many
# relationships as being a special case. During updates we already
# have an instance pk for the relationships to be associated with.
+ m2m_fields = []
for attr, value in validated_data.items():
if attr in info.relations and info.relations[attr].to_many:
- field = getattr(instance, attr)
- field.set(value)
+ m2m_fields.append((attr, value))
else:
setattr(instance, attr, value)
+
instance.save()
+ # Note that many-to-many fields are set after updating instance.
+ # Setting m2m fields triggers signals which could potentialy change
+ # updated instance and we do not want it to collide with .update()
+ for attr, value in m2m_fields:
+ field = getattr(instance, attr)
+ field.set(value)
+
return instance
# Determine the fields to apply...
| diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py
--- a/tests/test_model_serializer.py
+++ b/tests/test_model_serializer.py
@@ -18,6 +18,8 @@
MaxValueValidator, MinLengthValidator, MinValueValidator
)
from django.db import models
+from django.db.models.signals import m2m_changed
+from django.dispatch import receiver
from django.test import TestCase
from rest_framework import serializers
@@ -1251,7 +1253,6 @@ class Meta:
class Issue6110Test(TestCase):
-
def test_model_serializer_custom_manager(self):
instance = Issue6110ModelSerializer().create({'name': 'test_name'})
self.assertEqual(instance.name, 'test_name')
@@ -1260,3 +1261,43 @@ def test_model_serializer_custom_manager_error_message(self):
msginitial = ('Got a `TypeError` when calling `Issue6110TestModel.all_objects.create()`.')
with self.assertRaisesMessage(TypeError, msginitial):
Issue6110ModelSerializer().create({'wrong_param': 'wrong_param'})
+
+
+class Issue6751Model(models.Model):
+ many_to_many = models.ManyToManyField(ManyToManyTargetModel, related_name='+')
+ char_field = models.CharField(max_length=100)
+ char_field2 = models.CharField(max_length=100)
+
+
+@receiver(m2m_changed, sender=Issue6751Model.many_to_many.through)
+def process_issue6751model_m2m_changed(action, instance, **_):
+ if action == 'post_add':
+ instance.char_field = 'value changed by signal'
+ instance.save()
+
+
+class Issue6751Test(TestCase):
+ def test_model_serializer_save_m2m_after_instance(self):
+ class TestSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Issue6751Model
+ fields = (
+ 'many_to_many',
+ 'char_field',
+ )
+
+ instance = Issue6751Model.objects.create(char_field='initial value')
+ m2m_target = ManyToManyTargetModel.objects.create(name='target')
+
+ serializer = TestSerializer(
+ instance=instance,
+ data={
+ 'many_to_many': (m2m_target.id,),
+ 'char_field': 'will be changed by signal',
+ }
+ )
+
+ serializer.is_valid()
+ serializer.save()
+
+ self.assertEqual(instance.char_field, 'value changed by signal')
| ModelSerializer fields does not get updated correctly when signals are connected to some fields
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Having model Ticket
``` Python
class Ticket(models.Model):
tags = models.ManyToManyField(to='Tag', ...)
changed_by_signal = models.CharField(...)
# ... other fields ...
```
then some custom signal which is listening to Ticket.tags changes
``` Python
@receiver(m2m_changed, sender=Ticket.tags.through)
def process_tags_changed(sender, ticket, tag_set, **kwargs):
ticket.changed_by_signal = 'Some value'
ticket.save()
```
and TicketModelSerializer
``` Python
class TicketModelSerializer(serializers.ModelSerializer):
class Meta:
model = Ticket
fields = ('tags', 'changed_by_signal')
```
then when you save serializer with new `tags` and `changed_by_signal` **left unchanged** (e. g. `None`), you would expect the value of `changed_by_signal` to be 'Some value' as the signal sets, but the value is `None`. Why? Because `ModelSerializer.update` method does not update fields in correct way.
``` Python
class ModelSerializer(Serializer):
...
def update(self, instance, validated_data):
raise_errors_on_nested_writes('update', self, validated_data)
info = model_meta.get_field_info(instance)
# Simply set each attribute on the instance, and then save it.
# Note that unlike `.create()` we don't need to treat many-to-many
# relationships as being a special case. During updates we already
# have an instance pk for the relationships to be associated with.
for attr, value in validated_data.items(): # <- 1.
if attr in info.relations and info.relations[attr].to_many:
field = getattr(instance, attr)
field.set(value)
else:
setattr(instance, attr, value)
instance.save()
return instance
```
1. ModelSerializer updates the data from validated_data dict which is not sorted in any way. So when `tags` gets updated before `changed_by_signal`, then the value which is set by signal gets overriden.
## Proposed solution
I suppose changing the ModelSerializer method to
1. save non m2m fields (does not trigger any signals and does not change the instance as a side effect)
2. save m2m fields (can trigger side signals and change instance by side effects)
``` Python
class ModelSerializer(Serializer):
...
def update(self, instance, validated_data):
raise_errors_on_nested_writes('update', self, validated_data)
info = model_meta.get_field_info(instance)
# Simply set each attribute on the instance, and then save it.
# Note that unlike `.create()` we don't need to treat many-to-many
# relationships as being a special case. During updates we already
# have an instance pk for the relationships to be associated with.
m2m_fields = []
for attr, value in validated_data.items():
if attr not in info.relations or not info.relations[attr].to_many:
setattr(instance, attr, value)
else:
m2m_fields.append((attr, value))
for attr, value in m2m_fields:
field = getattr(instance, attr)
field.set(value)
instance.save()
return instance
```
Which stores m2m fields in a list that is processed after every other field has been changed. This is my temporary override for the TicketModelSerializer. I would consider making a pull request with changes that fix this issue.
ModelSerializer fields does not get updated correctly when signals are connected to some fields
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Having model Ticket
``` Python
class Ticket(models.Model):
tags = models.ManyToManyField(to='Tag', ...)
changed_by_signal = models.CharField(...)
# ... other fields ...
```
then some custom signal which is listening to Ticket.tags changes
``` Python
@receiver(m2m_changed, sender=Ticket.tags.through)
def process_tags_changed(sender, ticket, tag_set, **kwargs):
ticket.changed_by_signal = 'Some value'
ticket.save()
```
and TicketModelSerializer
``` Python
class TicketModelSerializer(serializers.ModelSerializer):
class Meta:
model = Ticket
fields = ('tags', 'changed_by_signal')
```
then when you save serializer with new `tags` and `changed_by_signal` **left unchanged** (e. g. `None`), you would expect the value of `changed_by_signal` to be 'Some value' as the signal sets, but the value is `None`. Why? Because `ModelSerializer.update` method does not update fields in correct way.
``` Python
class ModelSerializer(Serializer):
...
def update(self, instance, validated_data):
raise_errors_on_nested_writes('update', self, validated_data)
info = model_meta.get_field_info(instance)
# Simply set each attribute on the instance, and then save it.
# Note that unlike `.create()` we don't need to treat many-to-many
# relationships as being a special case. During updates we already
# have an instance pk for the relationships to be associated with.
for attr, value in validated_data.items(): # <- 1.
if attr in info.relations and info.relations[attr].to_many:
field = getattr(instance, attr)
field.set(value)
else:
setattr(instance, attr, value)
instance.save()
return instance
```
1. ModelSerializer updates the data from validated_data dict which is not sorted in any way. So when `tags` gets updated before `changed_by_signal`, then the value which is set by signal gets overriden.
## Proposed solution
I suppose changing the ModelSerializer method to
1. save non m2m fields (does not trigger any signals and does not change the instance as a side effect)
2. save m2m fields (can trigger side signals and change instance by side effects)
``` Python
class ModelSerializer(Serializer):
...
def update(self, instance, validated_data):
raise_errors_on_nested_writes('update', self, validated_data)
info = model_meta.get_field_info(instance)
# Simply set each attribute on the instance, and then save it.
# Note that unlike `.create()` we don't need to treat many-to-many
# relationships as being a special case. During updates we already
# have an instance pk for the relationships to be associated with.
m2m_fields = []
for attr, value in validated_data.items():
if attr not in info.relations or not info.relations[attr].to_many:
setattr(instance, attr, value)
else:
m2m_fields.append((attr, value))
for attr, value in m2m_fields:
field = getattr(instance, attr)
field.set(value)
instance.save()
return instance
```
Which stores m2m fields in a list that is processed after every other field has been changed. This is my temporary override for the TicketModelSerializer. I would consider making a pull request with changes that fix this issue.
| I think we're likely going to pass on this, as an out-of-scope usage.
We could *consider* a pull request that addressed it, but it seems like a pretty fundamental change, and it's not obvious that it wouldn't have side effects.
If you're really invested in seeing it happen you're welcome to attempt a pull request for it, to see if you're able to make the proposed change without affecting anything already existing in the test suite.
I think we're likely going to pass on this, as an out-of-scope usage.
We could *consider* a pull request that addressed it, but it seems like a pretty fundamental change, and it's not obvious that it wouldn't have side effects.
If you're really invested in seeing it happen you're welcome to attempt a pull request for it, to see if you're able to make the proposed change without affecting anything already existing in the test suite. | 2019-06-19T12:40:47 |
encode/django-rest-framework | 6,758 | encode__django-rest-framework-6758 | [
"6597"
] | f76480a127cd653d981e1463fa6bafdcea0021c6 | diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py
--- a/rest_framework/utils/field_mapping.py
+++ b/rest_framework/utils/field_mapping.py
@@ -109,6 +109,9 @@ def get_field_kwargs(field_name, model_field):
if model_field.blank and (isinstance(model_field, (models.CharField, models.TextField))):
kwargs['allow_blank'] = True
+ if not model_field.blank and (postgres_fields and isinstance(model_field, postgres_fields.ArrayField)):
+ kwargs['allow_empty'] = False
+
if isinstance(model_field, models.FilePathField):
kwargs['path'] = model_field.path
| diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py
--- a/tests/test_model_serializer.py
+++ b/tests/test_model_serializer.py
@@ -440,15 +440,17 @@ class Meta:
def test_array_field(self):
class ArrayFieldModel(models.Model):
array_field = postgres_fields.ArrayField(base_field=models.CharField())
+ array_field_with_blank = postgres_fields.ArrayField(blank=True, base_field=models.CharField())
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = ArrayFieldModel
- fields = ['array_field']
+ fields = ['array_field', 'array_field_with_blank']
expected = dedent("""
TestSerializer():
- array_field = ListField(child=CharField(label='Array field', validators=[<django.core.validators.MaxLengthValidator object>]))
+ array_field = ListField(allow_empty=False, child=CharField(label='Array field', validators=[<django.core.validators.MaxLengthValidator object>]))
+ array_field_with_blank = ListField(child=CharField(label='Array field with blank', validators=[<django.core.validators.MaxLengthValidator object>]), required=False)
""")
self.assertEqual(repr(TestSerializer()), expected)
| DRF doesn't set allow_empty=False for ArrayField with blank=False
Recently I came across an issue where invalid data was being created through our API, it turns out there's a subtle difference between the validation on an `ArrayField` and the resulting `ListField` in a `ModelSerializer`.
Given the following `models.py`:
```python
from django.db import models
from django.contrib.postgres.fields import ArrayField
class Example(models.Model):
data = ArrayField(models.IntegerField()) # blank=False by default
```
and this `serializers.py`
```python
from rest_framework import serializers
from .models import Example
class ExampleSerializer(serializers.ModelSerializer):
class Meta:
model = Example
fields = ['data']
class ExampleSerializer2(serializers.ModelSerializer):
data = serializers.ListField(child=serializers.IntegerField(), allow_empty=False)
class Meta:
model = Example
fields = ['data']
```
The `TestExampleSerializer.test_empty_list` test fails:
```python
from unittest import TestCase
from django.core.exceptions import ValidationError
from .models import Example
from .serializers import ExampleSerializer, ExampleSerializer2
class TestExampleModel(TestCase):
def test_empty_list(self):
# This works, Django doesn't allow an empty list if blank=False
obj = Example(data=[])
with self.assertRaises(ValidationError) as cm:
obj.full_clean()
error_dict = cm.exception.error_dict
self.assertIn('data', error_dict)
self.assertEqual('blank', error_dict['data'][0].code)
class TestExampleSerializer(TestCase):
def test_empty_list(self):
# This fails, DRF allows empty lists
serializer = ExampleSerializer(data={'data': []})
self.assertFalse(serializer.is_valid(), 'Expected validation error for empty list')
class TestExampleSerializer2(TestCase):
def test_empty_list(self):
# Setting allow_empty=False manually works
serializer = ExampleSerializer2(data={'data': []})
self.assertFalse(serializer.is_valid(), 'Expected validation error for empty list')
self.assertIn('data', serializer.errors)
self.assertEqual('empty', serializer.errors['data'][0].code)
```
I expected `ExampleSerializer` and `ExampleSerializer2` to behave the same.
When creating the `ListField` from the `ArrayField` DRF should set `allow_empty` on the `ListField` to the same value as `blank` on the `ArrayField`.
| 2019-06-25T13:25:59 |
|
encode/django-rest-framework | 6,766 | encode__django-rest-framework-6766 | [
"6351"
] | df1d146ee784868b44ddba802edfcc30c6ad9795 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -47,10 +47,24 @@ class empty:
pass
+class BuiltinSignatureError(Exception):
+ """
+ Built-in function signatures are not inspectable. This exception is raised
+ so the serializer can raise a helpful error message.
+ """
+ pass
+
+
def is_simple_callable(obj):
"""
True if the object is a callable that takes no arguments.
"""
+ # Bail early since we cannot inspect built-in function signatures.
+ if inspect.isbuiltin(obj):
+ raise BuiltinSignatureError(
+ 'Built-in function signatures are not inspectable. '
+ 'Wrap the function call in a simple, pure Python function.')
+
if not (inspect.isfunction(obj) or inspect.ismethod(obj) or isinstance(obj, functools.partial)):
return False
@@ -427,6 +441,18 @@ def get_attribute(self, instance):
"""
try:
return get_attribute(instance, self.source_attrs)
+ except BuiltinSignatureError as exc:
+ msg = (
+ 'Field source for `{serializer}.{field}` maps to a built-in '
+ 'function type and is invalid. Define a property or method on '
+ 'the `{instance}` instance that wraps the call to the built-in '
+ 'function.'.format(
+ serializer=self.parent.__class__.__name__,
+ field=self.field_name,
+ instance=instance.__class__.__name__,
+ )
+ )
+ raise type(exc)(msg)
except (KeyError, AttributeError) as exc:
if self.default is not empty:
return self.get_default()
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -14,7 +14,9 @@
import rest_framework
from rest_framework import exceptions, serializers
from rest_framework.compat import ProhibitNullCharactersValidator
-from rest_framework.fields import DjangoImageField, is_simple_callable
+from rest_framework.fields import (
+ BuiltinSignatureError, DjangoImageField, is_simple_callable
+)
# Tests for helper functions.
# ---------------------------
@@ -86,6 +88,18 @@ class Meta:
assert is_simple_callable(ChoiceModel().get_choice_field_display)
+ def test_builtin_function(self):
+ # Built-in function signatures are not easily inspectable, so the
+ # current expectation is to just raise a helpful error message.
+ timestamp = datetime.datetime.now()
+
+ with pytest.raises(BuiltinSignatureError) as exc_info:
+ is_simple_callable(timestamp.date)
+
+ assert str(exc_info.value) == (
+ 'Built-in function signatures are not inspectable. Wrap the '
+ 'function call in a simple, pure Python function.')
+
def test_type_annotation(self):
# The annotation will otherwise raise a syntax error in python < 3.5
locals = {}
@@ -206,6 +220,18 @@ def example_callable(self):
assert 'method call failed' in str(exc_info.value)
+ def test_builtin_callable_source_raises(self):
+ class BuiltinSerializer(serializers.Serializer):
+ date = serializers.ReadOnlyField(source='timestamp.date')
+
+ with pytest.raises(BuiltinSignatureError) as exc_info:
+ BuiltinSerializer({'timestamp': datetime.datetime.now()}).data
+
+ assert str(exc_info.value) == (
+ 'Field source for `BuiltinSerializer.date` maps to a built-in '
+ 'function type and is invalid. Define a property or method on '
+ 'the `dict` instance that wraps the call to the built-in function.')
+
class TestReadOnly:
def setup(self):
| Objects builtin methods are not called when passed in fields source
I open this ticket to check whether it's worth working on a specific case I spotted recently.
It is not possible to use built-in methods (or functions) in fields "source" argument, as they are not treated as `simple_callable`.
## Steps to reproduce
Example with Django User's date joined:
# serializers.py
day_joined = serializer.ReadOnlyField(source=`date_joined.date`)
#### Result
{
"day_joined": "<built-in method date of datetime.datetime object at 0x109400000>"
}
#### Expected result
{
"day_joined": "2008-09-03"
}
## Suggestion
There are [ways](https://stackoverflow.com/questions/48567935/get-parameterarg-count-of-builtin-functions-in-python) to ensure a built-in method/callable is a simple callable (ie can be called without arguments as per [`rest_framework.fields.is_simple_callable`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/fields.py#L56)).
I'm happy to create the PR for this, but need to know if it's worth it beforehand.
Related: see #5114
| aha, a bit frustrating to write SerializerMethodField.... instead
I stumbled upon same named method in IPython:
```python
# @ta_env/lib/python3.5/site-packages/IPython/core/oinspect.py:197
def is_simple_callable(obj):
"""True if obj is a function ()"""
return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
# @ta_env/lib/python3.5/site-packages/IPython/core/oinspect.py:58
_builtin_func_type = type(all)
_builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
```
Hi @antwan. I'm going to echo Tom's response in https://github.com/encode/django-rest-framework/issues/5114#issuecomment-298956002. If you can submit a minimal, low-friction pull request, then that would be worth including. However, the solution in the SO answer is too complex/brittle for the value that it provides.
That said, if a simple solution can't be found, it would be worth raising a helpful error message. e.g.,
> Python's built-in functions are not supported. Wrap the call in a function, method, or property. | 2019-06-29T01:27:56 |
encode/django-rest-framework | 6,767 | encode__django-rest-framework-6767 | [
"2420"
] | df1d146ee784868b44ddba802edfcc30c6ad9795 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1835,12 +1835,6 @@ def bind(self, field_name, parent):
# 'method_name' argument has been used. For example:
# my_field = serializer.SerializerMethodField(method_name='get_my_field')
default_method_name = 'get_{field_name}'.format(field_name=field_name)
- assert self.method_name != default_method_name, (
- "It is redundant to specify `%s` on SerializerMethodField '%s' in "
- "serializer '%s', because it is the same as the default method name. "
- "Remove the `method_name` argument." %
- (self.method_name, field_name, parent.__class__.__name__)
- )
# The method name should default to `get_{field_name}`.
if self.method_name is None:
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -2212,17 +2212,13 @@ def get_example_field(self, obj):
}
def test_redundant_method_name(self):
+ # Prior to v3.10, redundant method names were not allowed.
+ # This restriction has since been removed.
class ExampleSerializer(serializers.Serializer):
example_field = serializers.SerializerMethodField('get_example_field')
- with pytest.raises(AssertionError) as exc_info:
- ExampleSerializer().fields
- assert str(exc_info.value) == (
- "It is redundant to specify `get_example_field` on "
- "SerializerMethodField 'example_field' in serializer "
- "'ExampleSerializer', because it is the same as the default "
- "method name. Remove the `method_name` argument."
- )
+ field = ExampleSerializer().fields['example_field']
+ assert field.method_name == 'get_example_field'
class TestValidationErrorCode:
| Relax redundant method name restriction for SerializerMethodField
As per the 3.0 release, we now get AssertionErrors if we pass in a method name that matches the default:
``` python
AssertionError: It is redundant to specify `get_id_salted` on SerializerMethodField 'id_salted' in serializer 'UserSerializer', because it is the same as the default method name. Remove the `method_name` argument.
```
I can certainly see an argument for this sort of thing, but I subjectively prefer to be as explicit as possible, even if it comes at the cost of a few extra keystrokes. At any time, our team has external contractors (who may or may not have worked with DRF before) coming in and out, so this is one of those little easy hints we can give them. That arg (even if it's not needed anymore) provides some additional context for someone who is getting their bearings.
Would you accept a PR with a setting to disable this assertion? It'd help with those of us who prefer to be very explicit, and would also improve the migration path for those who don't care to make this change for many hundreds of serializer fields in larger codebases.
| > Would you accept a PR with a setting to disable this assertion?
No I don't think we should have it as a setting. We could reconsider the check tho.
Is there anything I can do to help with that?
I'm sure there are others that enshrine "Explicit is better than implicit" as much as I do. I feel like Django is heading in the direction of being more explicit over time, too (starting with the days of magic-removal).
> Is there anything I can do to help with that?
You may as well issue the PR removing it, check if there's any tests expecting the assertion error that now fail, and also in the same PR update/remove any bits of docs that mention it, eg the 3.0 announcement.
Done! See the PR and make sure you are OK with this assert being removed from the Field parent class. I don't think there's a great reason to pass a redundant source param to something like a CharField, but I'm not sure we'd want to police that and not SMField. Seems like that could be handled by the users of DRF during their code reviews. I suppose there's still a case like this where it could be funky looking:
``` python
some_field = CharField(source='doesnt_match')
# Looks kind of out of place?
matching_field = CharField()
another_field = CharField(source='doesnt_match_either')
```
> Seems like that could be handled by the users of DRF during their code reviews.
No - I've seen it plenty of times in 2.x codebases, and it's harmful to the ecosystem as it spreads uncertainty about if it's required or not. We can consider `SerializerMethodField`, but I'd def be against this change for `source`.
How would you like to handle the exemption for SMField but not Field? We'd need to disable the check, and I imagine we'd want to avoid messing with the signature of bind(). Would a (private?) class variable be OK? Could override in sub-classes to give people easy control over this behavior in custom fields.
They're different checks. Don't affect each other. I'm still not totally convinced this change is something we want tho, enforced consistency is def a good thing.
Maybe I'm reading this wrong, but I think the assertion check would come up from the parent class (Field) here: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py#L1237
Wouldn't we need to suppress that?
On reflection I'm going to close this off. The behaviour as it currently stands is deliberate design and I'm happy with the benefit of enforcing a single consistent style.
I just ran into this on a case you're probably not considering: the source argument is coming from a lookup in a global dictionary that is used in other places. The dictionary currently contains mostly identity mappings, but my serializer should respect that dictionary should it ever change. I can't do that right now without jumping through major hoops because of this assertion, which is totally unnecessary to the functioning of this class. I don't honestly care if you remove it or not because I won't be able to use the new version before it matters, but IMO this is an ill-considered design decision.
Hi @masterpi314. It's difficult to appreciate your use case without seeing a more complete example. e.g., it's not clear if there's another way to workaround your issue. Regardless, it shouldn't be too difficult to override the `bind` method to exhibit the desired behavior.
Just make sure that you call `super(SerializerMethodField, self).bind(field_name, parent)`, to *skip* `SerializerMethodField`'s `bind` implementation.
The implicit relationship between a `SerializerMethodField` and a method means that the code is harder to read than specifying `method_name=get_whatever.__name__`. Specifying the method name like this also means refactoring tools can rename the method. My team is literally working around this by renaming getter methods.
Please reconsider disabling this assertion. Would you be willing to accept a similar PR for only this change?
Apropos: Have you considered just having a `method` argument rather than `method_name`?
I am +0 on relaxing this restriction. On the one hand, I understand that consistency is valuable - it would be undesirable if redundant method names are provided inconsistently. On the other hand, I also prefer explicitly providing the method name, even if it does happen to be redundant.
I'll leave this to Tom, but if this isn't accepted, a minimal implementation to require a `method` is:
```python
class SerializerMethodField(serializers.Field):
def __init__(self, method, **kwargs):
self.method = method
kwargs['source'] = '*'
kwargs['read_only'] = True
super().__init__(**kwargs)
def to_representation(self, value):
method = getattr(self.parent, self.method)
return method(value)
```
Ran into this working with a client. Probably would be okay with us relaxing the `source` assertion. | 2019-06-29T01:41:59 |
encode/django-rest-framework | 6,770 | encode__django-rest-framework-6770 | [
"4012"
] | c04d6eac43c53b49c78120efcd7d950fd70541a7 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -56,6 +56,10 @@ def get_version(package):
print("twine not installed.\nUse `pip install twine`.\nExiting.")
sys.exit()
os.system("python setup.py sdist bdist_wheel")
+ if os.system("twine check dist/*"):
+ print("twine check failed. Packages might be outdated.")
+ print("Try using `pip install -U twine wheel`.\nExiting.")
+ sys.exit()
os.system("twine upload dist/*")
print("You probably want to also tag the version now:")
print(" git tag -a %s -m 'version %s'" % (version, version))
| long_description renders improperly on PyPI
## Steps to reproduce
View https://pypi.python.org/pypi/djangorestframework/3.3.3 on PyPI.
## Expected behavior
Rendered HTML that includes links, headings, and the like.
## Actual behavior
Raw reST markup appears in a non-monospace font.
I looked at the `setup.py` and observed that the project does not actually use the `long_description` field. I think PyPI is trying to convert the `README.md` to reST and failing. Since PyPI does not support Markdown (see https://bitbucket.org/pypa/pypi/issues/148/support-markdown-for-readmes), maybe an explicit `long_description` directing users to the proper documentation would be appropriate.
| pandoc has been configured to provide a long desc which should override the README.md.
We need to investigate why this didn't work for 3.3.3.
I'll add that this is not unique for 3.3.3. The issue goes back to 3.1.2. Prior to that, it appears that the README content was not included in the `long_description`. Unless something has changed about PyPI rendering of the `long_description`, maybe this never worked properly. _shrug_
Should I be reporting this somewhere else? I'm new to reporting issues for this project. It seems like this is a valid issue so I'm unclear on why it is closed. Is there some further action I can take to help this get fixed?
This issue is already reported as #3817
Cool, thanks for clarifying!
Sorry to dig this up but it seems that the Readme is - again - not rendered properly: https://pypi.org/project/djangorestframework/
`setup.py` looks good though... Really odd.
@xordoquy
Hmm. OK. Something has gone wrong there. Thanks for the report. I’ll look into it next week.
Also, `twine check dist/*` passes on master and the 3.9.3 tag. Note that the last working readme render was 3.9.0
The diff between https://github.com/encode/django-rest-framework/compare/3.9.0...3.9.1 doesn't point out anything obvious as to why this would fail. I've also successfully rendered the readme locally (using the snippet from https://github.com/pypa/readme_renderer/issues/117), so it's not clear to me why this is failing on PyPI.
Ah, finally figured it out. A lot of additional info in https://github.com/pypa/twine/issues/425, but the short version is that we were using an outdated `wheel` v0.30.0 to create the distributions, which doesn't support metadata 2.1 and the `long_description_content_type` option.
The fix is to ensure we run `twine check dist/*` to the publish command, which will complain when the readme is malformed. e.g., here's the output when wheel v0.30.0 is used:
```
Checking distribution dist/djangorestframework-3.9.3-py3-none-any.whl: warning: `long_description_content_type` missing. defaulting to `text/x-rst`.
Failed
The project's long_description has invalid markup which will not be rendered on PyPI. The following syntax errors were detected:
line 73: Warning: Definition list ends without a blank line; unexpected unindent.
Checking distribution dist/djangorestframework-3.9.3.tar.gz: Passed
``` | 2019-07-01T07:12:23 |
|
encode/django-rest-framework | 6,771 | encode__django-rest-framework-6771 | [
"6177"
] | 3242adf0589b00e2098fa5b0a08652548b3cd42c | diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py
--- a/rest_framework/exceptions.py
+++ b/rest_framework/exceptions.py
@@ -219,8 +219,8 @@ def __init__(self, media_type, detail=None, code=None):
class Throttled(APIException):
status_code = status.HTTP_429_TOO_MANY_REQUESTS
default_detail = _('Request was throttled.')
- extra_detail_singular = 'Expected available in {wait} second.'
- extra_detail_plural = 'Expected available in {wait} seconds.'
+ extra_detail_singular = _('Expected available in {wait} second.')
+ extra_detail_plural = _('Expected available in {wait} seconds.')
default_code = 'throttled'
def __init__(self, wait=None, detail=None, code=None):
| Translation missing for part of throttle warning
I'm using the throttling mechanism of DRF. When the exception is shown that actually the request was throttled, one part of the message is translated, the other part is not:

I couldn't find the part "expected available in X seconds" in the translation file so I guess it is just missing?
I'm using `djangorestframework==3.8.2`.
Best regards
Ron
| It looks like the `Throttled` exception doesn't have translations for the extra detail.
https://github.com/encode/django-rest-framework/blob/5f1f2b100353970ac0dec672154fedd3df9d0a9f/rest_framework/exceptions.py#L223-L228
Any quick workaround possible?
Re-raise as a custom Exception class that has translations?
Bump. Just faced this, is it possible to get this fixed in the next minor release?
Rather than a missing translation, this is also looks like a misuse of the translation framework.
Monkey patch the exception in the meantime.
```
# Adding this here so we force the translation to happen
# because DRF is bugged, monkey patch it.
# Remove once https://github.com/encode/django-rest-framework/issues/6177 is fixed
from django.utils.translation import gettext_lazy as _
from rest_framework.exceptions import Throttled
Throttled.extra_detail_singular = _("Expected available in {wait} second.")
Throttled.extra_detail_plural = _("Expected available in {wait} seconds.")
```
Adding this to the milestone, as I don't think there is any significant complexity in fixing this.
> Rather than a missing translation, this is also looks like a misuse of the translation framework.
Can you clarify? `ngettext` is still used to switch between the two messages.
>
>
> Adding this to the milestone, as I don't think there is any significant complexity in fixing this.
>
> > Rather than a missing translation, this is also looks like a misuse of the translation framework.
>
> Can you clarify? `ngettext` is still used to switch between the two messages.
I'm not 100% sure about what's the issue, but ngettext doesn't seem to be working unless the text itself is also a translated string. Please see my monkey patch above.
Looks like this line:
```
force_text(ungettext(self.extra_detail_singular.format(wait=wait),
self.extra_detail_plural.format(wait=wait),
wait))))
```
Will only work if extra_detail_singular and extra_detail_plural are lazy translation strings (or translated in place).
Perhaps it is my Windows environment and gettext, but ungettext wasn't giving me translated text even if I added the translation string by hand.
Edit: Probably related to the fact that a variable is used there, and that .format is also used. Please read the django docs for a good example about how to use ungettext: https://docs.djangoproject.com/en/2.2/topics/i18n/translation/#pluralization
> Probably related to the fact that a variable is used there, and that .format is also used.
This would make sense.
> Please read the django docs for a good example about how to use ungettext
DRF uses `.format` instead of `%`-based formatting, so we can't just pass the strings directly to the various gettext functions. That said, wrapping the format strings in `gettext_lazy` should fix the issue. | 2019-07-02T00:05:26 |
|
encode/django-rest-framework | 6,773 | encode__django-rest-framework-6773 | [
"6171"
] | a7778897adbc7184f1b500bf221c29b2d7201bbd | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1888,9 +1888,9 @@ def __init__(self, model_field, **kwargs):
self.model_field = model_field
# The `max_length` option is supported by Django's base `Field` class,
# so we'd better support it here.
- max_length = kwargs.pop('max_length', None)
+ self.max_length = kwargs.pop('max_length', None)
super().__init__(**kwargs)
- if max_length is not None:
+ if self.max_length is not None:
message = lazy_format(self.error_messages['max_length'], max_length=self.max_length)
self.validators.append(
MaxLengthValidator(self.max_length, message=message))
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -2204,8 +2204,8 @@ class TestBinaryJSONField(FieldValues):
field = serializers.JSONField(binary=True)
-# Tests for FieldField.
-# ---------------------
+# Tests for FileField.
+# --------------------
class MockRequest:
def build_absolute_uri(self, value):
@@ -2247,6 +2247,21 @@ class ExampleSerializer(serializers.Serializer):
assert field.method_name == 'get_example_field'
+# Tests for ModelField.
+# ---------------------
+
+class TestModelField:
+ def test_max_length_init(self):
+ field = serializers.ModelField(None)
+ assert len(field.validators) == 0
+
+ field = serializers.ModelField(None, max_length=10)
+ assert len(field.validators) == 1
+
+
+# Tests for validation errors
+# ---------------------------
+
class TestValidationErrorCode:
@pytest.mark.parametrize('use_list', (False, True))
def test_validationerror_code_with_msg(self, use_list):
| 'ModelField' object has no attribute 'max_length'

**I have add max_length,but got a traceback**
```
Traceback:
.....
File "/webapps/fi-licaishi/env35/lib/python3.5/site-packages/rest_framework/serializers.py" in get_fields
1054. fields[field_name] = field_class(**field_kwargs)
File "/webapps/fi-licaishi/env35/lib/python3.5/site-packages/rest_framework/fields.py" in __init__
1878. six.text_type)(max_length=self.max_length)
Exception Type: AttributeError at /api/products/short_products/
Exception Value: 'ModelField' object has no attribute 'max_length'
```

**I try change `max_length=self.max_length` to `max_length=max_length`, it will be work.**
**Is there any other solution?**
| 2019-07-02T02:07:06 |
|
encode/django-rest-framework | 6,774 | encode__django-rest-framework-6774 | [
"6453"
] | 280014fe37c57f7068c42e9c2f644c685c48b909 | diff --git a/rest_framework/filters.py b/rest_framework/filters.py
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -64,7 +64,9 @@ def get_search_terms(self, request):
and may be comma and/or whitespace delimited.
"""
params = request.query_params.get(self.search_param, '')
- return params.replace(',', ' ').split()
+ params = params.replace('\x00', '') # strip null characters
+ params = params.replace(',', ' ')
+ return params.split()
def construct_search(self, field_name):
lookup = self.lookup_prefixes.get(field_name[0])
| diff --git a/tests/test_filters.py b/tests/test_filters.py
--- a/tests/test_filters.py
+++ b/tests/test_filters.py
@@ -180,6 +180,15 @@ class SearchListView(generics.ListAPIView):
{'id': 3, 'title': 'zzz', 'text': 'cde'}
]
+ def test_search_field_with_null_characters(self):
+ view = generics.GenericAPIView()
+ request = factory.get('/?search=\0as%00d\x00f')
+ request = view.initialize_request(request)
+
+ terms = filters.SearchFilter().get_search_terms(request)
+
+ assert terms == ['asdf']
+
class AttributeModel(models.Model):
label = models.CharField(max_length=32)
| ValueError on incorrect user input, should we sanitize user input by default?
## Checklist
- [X] I have verified that that issue exists against the `master` branch of Django REST framework.
- [X] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [X] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [X] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [X] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Any `viewsets.ReadOnlyModelViewSet` with `search_fields` attribute.
Request the API endpoint with the following `search` query param:
`api-url?search=Exploit%20String:%200%0d%0a%00%3Cscript%20src=//example.com%3E`
## Expected behavior
No match found, no exception raised.
Expecting to see something like `{"count": 0, next: None, previous: None, results: []}` in the output.
## Actual behavior
Got HTTP 500 error with the following exception:
`ValueError: A string literal cannot contain NUL (0x00) characters.`
| Do you have the full traceback ?
Sure. In my current case this is the following (not sure how to make it more 'full'):
```
Traceback:
File "/app/env/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/app/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/app/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/app/env/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/app/env/lib/python2.7/site-packages/rest_framework/viewsets.py" in view
116. return self.dispatch(request, *args, **kwargs)
File "/app/env/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/app/env/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/app/env/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/app/env/lib/python2.7/site-packages/rest_framework/mixins.py" in list
42. page = self.paginate_queryset(queryset)
File "/app/env/lib/python2.7/site-packages/rest_framework/generics.py" in paginate_queryset
173. return self.paginator.paginate_queryset(queryset, self.request, view=self)
File "/app/env/lib/python2.7/site-packages/rest_framework/pagination.py" in paginate_queryset
325. self.count = self.get_count(queryset)
File "/app/env/lib/python2.7/site-packages/rest_framework/pagination.py" in get_count
466. return queryset.count()
File "/app/env/lib/python2.7/site-packages/cacheops/query.py" in count
307. return self._no_monkey.count(self)
File "/app/env/lib/python2.7/site-packages/django/db/models/query.py" in count
364. return self.query.get_count(using=self.db)
File "/app/env/lib/python2.7/site-packages/django/db/models/sql/query.py" in get_count
499. number = obj.get_aggregation(using, ['__count'])['__count']
File "/app/env/lib/python2.7/site-packages/django/db/models/sql/query.py" in get_aggregation
480. result = compiler.execute_sql(SINGLE)
File "/app/env/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
899. raise original_exception
Exception Type: ValueError at /api/apps/
Exception Value: A string literal cannot contain NUL (0x00) characters.
```
There's a related bug on Django about this. https://code.djangoproject.com/ticket/30064.
The summary there is that this should be handled by a form (etc) sanitising the user input before passing it to the ORM. (That seems reasonable to me.)
Would be totally reasonable for our string fields to strip null characters, yup.
Is this not fixed by #6073?
Looks like it, yes.
@niksite - Could you verify which version of REST framework you were running here?
Can we verify this against master now or not?
1. I am using 3.9.1 version of DRF.
2. This ticket is about '?search=' parameter to the query. Is it working via regular CharField too?
#6073 just added the validator to serializer fields. But `SearchFilter` doesn't use a serializer or form to sanitize the query parameter, so bad values can leak in.
https://github.com/encode/django-rest-framework/blob/d110454d4c15fe6617a112e846b89e09ed6c95b2/rest_framework/filters.py#L64-L70
This is the same thing that happens in the Django admin in the linked ticket.
We basically should be using a form on the parameters before using then. ("Sanitize input...")
Here is a quick draft of how this could be done by using form sanitation. Please be kind :smile: I might be totally out of order here.
https://github.com/encode/django-rest-framework/compare/master...busla:sanitize-searchfield-input?expand=1
~~Wondering if I should raise a custom exception when is_valid is False or try to propogate the Validation error?~~
After looking through the code flow of `filters.py`, it might be acceptable to ignore `form.errors` and not raise a ValidationError, instead just return an empty list as before. | 2019-07-02T16:52:37 |
encode/django-rest-framework | 6,775 | encode__django-rest-framework-6775 | [
"6761"
] | 43d4736802792a370c59db76545697866048c209 | diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py
--- a/rest_framework/renderers.py
+++ b/rest_framework/renderers.py
@@ -604,10 +604,13 @@ def get_description(self, view, status_code):
def get_breadcrumbs(self, request):
return get_breadcrumbs(request.path, request)
- def get_extra_actions(self, view):
- if hasattr(view, 'get_extra_action_url_map'):
- return view.get_extra_action_url_map()
- return None
+ def get_extra_actions(self, view, status_code):
+ if (status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)):
+ return None
+ elif not hasattr(view, 'get_extra_action_url_map'):
+ return None
+
+ return view.get_extra_action_url_map()
def get_filter_form(self, data, view, request):
if not hasattr(view, 'get_queryset') or not hasattr(view, 'filter_backends'):
@@ -695,7 +698,7 @@ def get_context(self, data, accepted_media_type, renderer_context):
'delete_form': self.get_rendered_html_form(data, view, 'DELETE', request),
'options_form': self.get_rendered_html_form(data, view, 'OPTIONS', request),
- 'extra_actions': self.get_extra_actions(view),
+ 'extra_actions': self.get_extra_actions(view, response.status_code),
'filter_form': self.get_filter_form(data, view, request),
| diff --git a/tests/test_renderers.py b/tests/test_renderers.py
--- a/tests/test_renderers.py
+++ b/tests/test_renderers.py
@@ -631,8 +631,12 @@ def list(self, request):
def list_action(self, request):
raise NotImplementedError
+ class AuthExampleViewSet(ExampleViewSet):
+ permission_classes = [permissions.IsAuthenticated]
+
router = SimpleRouter()
router.register('examples', ExampleViewSet, basename='example')
+ router.register('auth-examples', AuthExampleViewSet, basename='auth-example')
urlpatterns = [url(r'^api/', include(router.urls))]
def setUp(self):
@@ -657,6 +661,12 @@ def test_extra_actions_dropdown(self):
assert '/api/examples/list_action/' in resp.content.decode()
assert '>Extra list action<' in resp.content.decode()
+ def test_extra_actions_dropdown_not_authed(self):
+ resp = self.client.get('/api/unauth-examples/', HTTP_ACCEPT='text/html')
+ assert 'id="extra-actions-menu"' not in resp.content.decode()
+ assert '/api/examples/list_action/' not in resp.content.decode()
+ assert '>Extra list action<' not in resp.content.decode()
+
class AdminRendererTests(TestCase):
| List of actions of a viewset are visible from unauthenticated users in browsable api (latest 3.9.4)
## Checklist
- [ ] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Create a model viewset with different actions (detail=True or False), make sure the viewset and actions require users to be authenticated, and get the following response on list and retrieve views and actions: HTTP 401 Unauthorized "detail": "Authentication credentials were not provided."
## Expected behavior
Unauthenticated users should not have access to the list of actions (on list view and on retrieve view) in the "Extra actions" dropdown if they don't have access to the views and actions.
## Actual behavior
In browsable api of latest DRF (3.9.4) unauthenticated users can see the list of detail=False actions on the list view and the list of detail=True actions on the retrieve view, even though they don't have access to retrieve/list/actions views (401 unauthorized)
| 2019-07-03T02:34:57 |
|
encode/django-rest-framework | 6,786 | encode__django-rest-framework-6786 | [
"5212"
] | eebc579e9b96fca4c8fcc4d4a8365d915d676caa | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -819,10 +819,10 @@ def raise_errors_on_nested_writes(method_name, serializer, validated_data):
# ...
# address = serializer.CharField('profile.address')
assert not any(
- '.' in field.source and
- (key in validated_data) and
- isinstance(validated_data[key], (list, dict))
- for key, field in serializer.fields.items()
+ len(field.source_attrs) > 1 and
+ (field.source_attrs[0] in validated_data) and
+ isinstance(validated_data[field.source_attrs[0]], (list, dict))
+ for field in serializer._writable_fields
), (
'The `.{method_name}()` method does not support writable dotted-source '
'fields by default.\nWrite an explicit `.{method_name}()` method for '
| diff --git a/tests/test_serializer_nested.py b/tests/test_serializer_nested.py
--- a/tests/test_serializer_nested.py
+++ b/tests/test_serializer_nested.py
@@ -1,4 +1,7 @@
+import pytest
+from django.db import models
from django.http import QueryDict
+from django.test import TestCase
from rest_framework import serializers
@@ -241,3 +244,61 @@ def test_multipart_validate(self):
serializer = self.Serializer(data=input_data)
assert serializer.is_valid()
assert 'nested' in serializer.validated_data
+
+
+class NestedWriteProfile(models.Model):
+ address = models.CharField(max_length=100)
+
+
+class NestedWritePerson(models.Model):
+ profile = models.ForeignKey(NestedWriteProfile, on_delete=models.CASCADE)
+
+
+class TestNestedWriteErrors(TestCase):
+ # tests for rests_framework.serializers.raise_errors_on_nested_writes
+ def test_nested_serializer_error(self):
+ class ProfileSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = NestedWriteProfile
+ fields = ['address']
+
+ class NestedProfileSerializer(serializers.ModelSerializer):
+ profile = ProfileSerializer()
+
+ class Meta:
+ model = NestedWritePerson
+ fields = ['profile']
+
+ serializer = NestedProfileSerializer(data={'profile': {'address': '52 festive road'}})
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'profile': {'address': '52 festive road'}}
+ with pytest.raises(AssertionError) as exc_info:
+ serializer.save()
+
+ assert str(exc_info.value) == (
+ 'The `.create()` method does not support writable nested fields by '
+ 'default.\nWrite an explicit `.create()` method for serializer '
+ '`tests.test_serializer_nested.NestedProfileSerializer`, or set '
+ '`read_only=True` on nested serializer fields.'
+ )
+
+ def test_dotted_source_field_error(self):
+ class DottedAddressSerializer(serializers.ModelSerializer):
+ address = serializers.CharField(source='profile.address')
+
+ class Meta:
+ model = NestedWritePerson
+ fields = ['address']
+
+ serializer = DottedAddressSerializer(data={'address': '52 festive road'})
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'profile': {'address': '52 festive road'}}
+ with pytest.raises(AssertionError) as exc_info:
+ serializer.save()
+
+ assert str(exc_info.value) == (
+ 'The `.create()` method does not support writable dotted-source '
+ 'fields by default.\nWrite an explicit `.create()` method for '
+ 'serializer `tests.test_serializer_nested.DottedAddressSerializer`, '
+ 'or set `read_only=True` on dotted-source serializer fields.'
+ )
| Check source attrs when checking for nested writes
## Description
When checking for 'dotted' source nested values prior to serializer create or update, the problematic fields are not being identified correctly.
In the example given in the code comment, the validated data would look like `{'profile': {'address': '10 downing street'}}` but the code is currently checking for key 'address' in the dict.
## Test case
The issue can be seen currently with the following test (which will fail):
```
import pytest
from django.contrib.postgres.fields import JSONField
from django.db import models
from rest_framework import serializers
class NestedSourceModel(models.Model):
profile = JSONField()
class NestedSourceSerializer(serializers.ModelSerializer):
address = serializers.CharField(source='profile.address')
class Meta:
model = NestedSourceModel
fields = ('address',)
data = QueryDict('address=10 downing street')
serializer = NestedSourceSerializer(data=data)
serializer.is_valid()
assert serializer.validated_data == {'profile': {'address': '10 downing street'}}
with pytest.raises(AssertionError):
serializer.save()
```
| Thanks for the PR.
Test added.
I'm a bit annoyed as I can't run the tests without the other part of the PR on my box.
@xordoquy What do you mean by 'other part of the PR'?
sorry, I meant the test alone with the current code base.
Copy and paste? :P
How do you normally show issues like this and provide a resolution? I can't introduce the test before the fix....
I usually try to make sure new test cases are failing without code addition so I'm confident the code fixes something ;)
How do you do that? Make a temporary PR that is just the test so you can see the failure?
Looks good. Little bit cautious about pulling into a minor release - we *could* choose to defer to the next major release. | 2019-07-06T01:11:17 |
encode/django-rest-framework | 6,817 | encode__django-rest-framework-6817 | [
"6808",
"6811"
] | 91140348561165c18674b4ba81e6a57fab878d31 | diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py
--- a/rest_framework/__init__.py
+++ b/rest_framework/__init__.py
@@ -8,7 +8,7 @@
"""
__title__ = 'Django REST framework'
-__version__ = '3.10.0'
+__version__ = '3.10.1'
__author__ = 'Tom Christie'
__license__ = 'BSD 2-Clause'
__copyright__ = 'Copyright 2011-2019 Encode OSS Ltd'
diff --git a/rest_framework/authtoken/admin.py b/rest_framework/authtoken/admin.py
--- a/rest_framework/authtoken/admin.py
+++ b/rest_framework/authtoken/admin.py
@@ -7,7 +7,6 @@ class TokenAdmin(admin.ModelAdmin):
list_display = ('key', 'user', 'created')
fields = ('user',)
ordering = ('-created',)
- autocomplete_fields = ('user',)
admin.site.register(Token, TokenAdmin)
diff --git a/rest_framework/compat.py b/rest_framework/compat.py
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -93,12 +93,16 @@ def distinct(queryset, base):
postgres_fields = None
-# coreapi is optional (Note that uritemplate is a dependency of coreapi)
+# coreapi is required for CoreAPI schema generation
try:
import coreapi
- import uritemplate
except ImportError:
coreapi = None
+
+# uritemplate is required for OpenAPI and CoreAPI schema generation
+try:
+ import uritemplate
+except ImportError:
uritemplate = None
| rest_framework 3.10.0 - crash with runserver
## Checklist
- [X] I have verified that that issue exists against the `master` branch of Django REST framework.
- [X] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [X] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [X] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [X] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
- django 2.2
- update rest_framework to v3.10.0 with pip (last version in my computer: 3.9.4)
- settings.py
```python
INSTALLED_APPS = [
....
'rest_framework',
'rest_framework.authtoken',
...
]
```
- ``python manage.py runserver 0.0.0.0:8080``
## Expected behavior
Not crash
## Actual behavior
```
user@pc:~/path/to/project/$ python manage.py runserver 0.0.0.0:8080
Watching for file changes with StatReloader
Performing system checks...
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/home/user/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/home/user/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/home/user/.local/lib/python3.6/site-packages/django/core/management/base.py", line 436, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'rest_framework.authtoken.admin.TokenAdmin'>: (admin.E040) UserAdmin must define "search_fields", because it's referenced by TokenAdmin.autocomplete_fields.
System check identified 1 issue (0 silenced).
```
Added requirement for UserAdmin.search_fields to 3.10 release notes.
Closes #6808.
| Due to this pull request #6762 ...
UserAdmin is Django’s right? In which case we may need to revert...
Looks like it does define search_fields.
https://github.com/django/django/blob/cf79f92abee2ff5fd4fdcc1a124129a9773805b8/django/contrib/auth/admin.py#L63
So are you using a custom user model and admin? If so, does adding search_fields like the error says fix it?
Yes I use custom user model and custom admin model.
If I add ``search_fields = ("email",)``, it works.
But if I have to do it, it means that it's not backward compatible ...
I don’t know if there’s any great options here. I guess we could do a runtime check for if search_fields is set on the user model, and only include it in the autocomplete list if it is?
A small break, with an easy fix, between a minor version, especially that is caught by a system check is OK.
The SemVer purists will scream but that's how we've always done it on DRF.
BUT we should add a small clarification to the release notes. (If there's not one already.)
Just to provide further information. If a custom admin site is used and the User model is not registered, the following error will occur:
```
ERRORS:
<class 'rest_framework.authtoken.admin.TokenAdmin'>: (admin.E039) An admin for model "User" has to be registered to be referenced by TokenAdmin.autocomplete_fields.
```
I fixed it by registering my User model.
Yes, that would be expected. TBH I think the system check does the best job here of explaining what’s needed. (We’d just he repeating the Django docs to try to cover it.)
Just chiming in on this. It's breaking my stuff as well.
Except, I'm not even doing `runserver` I'm just doing migrations.
The issue appears to resolve itself if I comment out a line from this file:
`venv/lib/python3.7/site-packages/rest_framework/authtoken/admin.py`
```
from django.contrib import admin
from rest_framework.authtoken.models import Token
class TokenAdmin(admin.ModelAdmin):
list_display = ('key', 'user', 'created')
fields = ('user',)
ordering = ('-created',)
autocomplete_fields = ('user',)
# Commenting this out makes it work
# admin.site.register(Token, TokenAdmin)
```
Kind of a bummer this happened. I do not understand what this is at all and why it's failing.
Hi @loganknecht - any management command (runserver, migrate, etc..) should fail since this is causing a system check failure. You need to do either one of two things:
- Unregister the Token model `admin.site.unregister(Token)`
- Add `search_fields` to your customer user admin
@rpkilby Thank you for taking the time to respond.
I think my point of confusion for this is why does version `3.9.4` work completely fine, but version `3.10.0` break everything entirely?
In addition to that, why do I now have to do either one of those two things? That doesn't make sense why I have to unregister something I never registered before, or add a field I never used before?
> I think my point of confusion for this is why does version 3.9.4 work completely fine, but version 3.10.0 break everything entirely?
DRF doesn't use strict semantic versioning. The [versioning scheme](https://www.django-rest-framework.org/community/release-notes/#versioning) is slightly different, and the jump from 3.9.4 to 3.10 is considered a "medium" version release, which may contain breaking API changes. You can think of 3.9 and 3.10 as analogous to Django's ["feature"](https://docs.djangoproject.com/en/dev/internals/release-process/#official-releases) releases.
> In addition to that, why do I now have to do either one of those two things? That doesn't make sense why I have to unregister something I never registered before, or add a field I never used before?
You've likely enabled it unknowingly. If you're getting this error, then `rest_framework.authtoken` should be in your `INSTALLED_APPS`, and the Django admin's autodiscovery should have picked it up. If that's the case, and you don't need the token admin, one option would be to unregister it. This is effectively what you did above by commenting out the register call. If you do want to keep the token admin, then you need to add `search_fields` to your custom user model's admin.
@rpkilby Again, Thank you for taking the time to respond.
Is there somewhere I can read about `search_fields` configuration and why it needs to be added/what it does?
> Again, Thank you for taking the time to respond.
No problem - this is useful feedback, as other users are likely to run into the same issue.
> Is there somewhere I can read about `search_fields` configuration
The django admin [docs](https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields) explain `autocomplete_fields`, and why the related model's admin needs to have `search_fields` set. In this case, the `TokenAdmin` added `autocomplete_fields = ['user']`, and your custom user admin does not have `search_fields`, which this feature depends on.
@rpkilby I think I it's really hard for me to understand what you've explained. I've read the documentation and I kind of understand what `autocomplete_fields` are used for, and that it is helped by using the `search_fields`
Does Django Rest Framework have to add the `user` to its `autocomplete_fields`? Was that one of that changes from `3.9.4` to `3.10`? Is that required?
I think I understand the problem, but I don't have an admin configuration for my django project. What should I do to fix this? Does this mean I simply add:
```
class User(AbstractBaseUser, PermissionsMixin):
...
search_fields = []
...
```
I would like to politely express some frustration regarding this because it seems like I have to go back and account for changes because of DRF after the fact. And it would be nice to have a clear explanation in the form of documentation from DRF to understand why this information is needed for the DRF admin configurations, and why I have to change my user model to match that.
Is there no way to opt-in to this? I do need to use the `rest_framework.authtoken` app to support my token authorization, but it just seems weird to have to do this now, because I'm not even making use of the django admin functionality. It also seems weird to have to unregister something. If that's the case, wouldn't it make more sense for me to register the DRF token admin configuration myself as a form of opt-in?
Additionally, for me this isn't a huge deal because my user model hasn't been formalized yet, but I imagine this is going to affect a lot of people who don't have the luxury of easily modifying their custom user model? Is this going to affect them as well? I have been under the impression that having to make changes to the user model after the fact is a hard thing to do.
Thank you for all the work, and the responses. I really appreciate everything.
I think this little change is doing more harm than good. Maybe it's better to revert it ... or to change something to do not force users to do something weird. Updating the doc is the simplest solution but the problem is still here.
And please be careful before merging pull request, a lot of people use this awesome package and their works can be broken with thing like this.
Thanks for all.
> I'm not even making use of the django admin functionality
But the system check shouldn't fire is django.contrib.admin is not in `INSTALLED_APPS`.
The usability benefits of autocomplete fields are worth the costs here. Anyone using the admin with a decent number of user records will benefit.
The system check error messages are pretty clear. #6811 adds an extra explanatory note but the admin docs are the canonical source. This isn't a big enough issue to revert over.
> Does Django Rest Framework have to add the user to its `autocomplete_fields`?
No, but it is beneficial when there are a large number of users in your database. Otherwise the token admin becomes unusable (rendering a select dropdown for 150k users is slow).
> I think I understand the problem, but I don't have an admin configuration for my django project.
If you're not using the Django admin, you could also fix this by just removing `django.contrib.admin` from the `INSTALLED_APPS` setting.
> I would like to politely express some frustration regarding this because it seems like I have to go back and account for changes because of DRF after the fact.
Of course. There are a few issues that intersect, and the result in this case is surprising/confusing.
> Is there no way to opt-in to this? ... It also seems weird to have to unregister something. If that's the case, wouldn't it make more sense for me to register it myself as a form of opt-in?
The admin works via autodiscovery, and 3rd party apps generally self-register on discovery. It would be atypical for an app to provide admin classes and require projects to register them separately. Note that you're effectively opting in by having the `'django.contrib.auth'` in your `INSTALLED_APPS`. If you're not using the admin, then it should be removed from the apps list.
> I imagine this is going to affect a lot of people who don't have the luxury of easily modifying their custom user model?
This doesn't require changing the user model - just the admin for the custom user model.
I think the documentation approach makes sense, as this should only affect projects that define a custom user model/admin that doesn't set `search_fields`. If a project uses the builtin user model/admin or inherits those, they should be fine.
Of course, the other option is to just revert #6762 and let users modify the admin when there is a sufficiently large number of users in their database. | 2019-07-17T12:28:28 |
|
encode/django-rest-framework | 6,819 | encode__django-rest-framework-6819 | [
"6815"
] | da1c6d4129261fdc7f20afb674da7e553d4e3006 | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -9,7 +9,7 @@
from rest_framework import exceptions, serializers
from rest_framework.compat import uritemplate
-from rest_framework.fields import empty
+from rest_framework.fields import _UnvalidatedField, empty
from .generators import BaseSchemaGenerator
from .inspectors import ViewInspector
@@ -256,9 +256,15 @@ def _map_field(self, field):
# ListField.
if isinstance(field, serializers.ListField):
- return {
+ mapping = {
'type': 'array',
+ 'items': {},
}
+ if not isinstance(field.child, _UnvalidatedField):
+ mapping['items'] = {
+ "type": self._map_field(field.child).get('type')
+ }
+ return mapping
# DateField and DateTimeField type is string
if isinstance(field, serializers.DateField):
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -39,6 +39,20 @@ def test_pagination(self):
assert f.get_schema_operation_parameters(self.dummy_view)
+class TestFieldMapping(TestCase):
+ def test_list_field_mapping(self):
+ inspector = AutoSchema()
+ cases = [
+ (serializers.ListField(), {'items': {}, 'type': 'array'}),
+ (serializers.ListField(child=serializers.BooleanField()), {'items': {'type': 'boolean'}, 'type': 'array'}),
+ (serializers.ListField(child=serializers.FloatField()), {'items': {'type': 'number'}, 'type': 'array'}),
+ (serializers.ListField(child=serializers.CharField()), {'items': {'type': 'string'}, 'type': 'array'}),
+ ]
+ for field, mapping in cases:
+ with self.subTest(field=field):
+ assert inspector._map_field(field) == mapping
+
+
@pytest.mark.skipif(uritemplate is None, reason='uritemplate not installed.')
class TestOperationIntrospection(TestCase):
| OpenAPI AutoSchema does not handle ListField correctly
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
djangorestframework==3.10.0
```python
# serializers.py
class MySerializer(serializers.Serializer):
my_values = serializers.ListField(child=serializers.FloatField())
# views.py
class MyAPIView(GenericAPIView):
serializer_class = MySerializer
```
`urls.py` and `templates/swagger-ui.html` are same as described in [documentation](https://www.django-rest-framework.org/topics/documenting-your-api/).
## Expected behavior
Swagger should render schema without any problems.
## Actual behavior
swagger

console

I think the latest version of drf does not handle `ListField` correctly. The `array` type in OpenAPI should come with corresponding `items`, but `AutoSchema` in `rest_framework.schemas.openapi` does not provide `items` for `ListField` in `_map_field` method.
https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas/openapi.py#L257-L261
| OK, looks like a good addition. Do you think you could make a PR adding the correct mapping for ListField? | 2019-07-17T18:51:42 |
encode/django-rest-framework | 6,827 | encode__django-rest-framework-6827 | [
"6823"
] | da1c6d4129261fdc7f20afb674da7e553d4e3006 | diff --git a/rest_framework/schemas/coreapi.py b/rest_framework/schemas/coreapi.py
--- a/rest_framework/schemas/coreapi.py
+++ b/rest_framework/schemas/coreapi.py
@@ -20,7 +20,18 @@
header_regex = re.compile('^[a-zA-Z][0-9A-Za-z_]*:')
# Generator #
-# TODO: Pull some of this into base.
+
+
+def common_path(paths):
+ split_paths = [path.strip('/').split('/') for path in paths]
+ s1 = min(split_paths)
+ s2 = max(split_paths)
+ common = s1
+ for i, c in enumerate(s1):
+ if c != s2[i]:
+ common = s1[:i]
+ break
+ return '/' + '/'.join(common)
def is_custom_action(action):
@@ -209,6 +220,37 @@ def get_keys(self, subpath, method, view):
# Default action, eg "/users/", "/users/{pk}/"
return named_path_components + [action]
+ def determine_path_prefix(self, paths):
+ """
+ Given a list of all paths, return the common prefix which should be
+ discounted when generating a schema structure.
+
+ This will be the longest common string that does not include that last
+ component of the URL, or the last component before a path parameter.
+
+ For example:
+
+ /api/v1/users/
+ /api/v1/users/{pk}/
+
+ The path prefix is '/api/v1'
+ """
+ prefixes = []
+ for path in paths:
+ components = path.strip('/').split('/')
+ initial_components = []
+ for component in components:
+ if '{' in component:
+ break
+ initial_components.append(component)
+ prefix = '/'.join(initial_components[:-1])
+ if not prefix:
+ # We can just break early in the case that there's at least
+ # one URL that doesn't have a path prefix.
+ return '/'
+ prefixes.append('/' + prefix + '/')
+ return common_path(prefixes)
+
# View Inspectors #
diff --git a/rest_framework/schemas/generators.py b/rest_framework/schemas/generators.py
--- a/rest_framework/schemas/generators.py
+++ b/rest_framework/schemas/generators.py
@@ -18,18 +18,6 @@
from rest_framework.utils.model_meta import _get_pk
-def common_path(paths):
- split_paths = [path.strip('/').split('/') for path in paths]
- s1 = min(split_paths)
- s2 = max(split_paths)
- common = s1
- for i, c in enumerate(s1):
- if c != s2[i]:
- common = s1[:i]
- break
- return '/' + '/'.join(common)
-
-
def get_pk_name(model):
meta = model._meta.concrete_model._meta
return _get_pk(meta).name
@@ -236,37 +224,6 @@ def coerce_path(self, path, method, view):
def get_schema(self, request=None, public=False):
raise NotImplementedError(".get_schema() must be implemented in subclasses.")
- def determine_path_prefix(self, paths):
- """
- Given a list of all paths, return the common prefix which should be
- discounted when generating a schema structure.
-
- This will be the longest common string that does not include that last
- component of the URL, or the last component before a path parameter.
-
- For example:
-
- /api/v1/users/
- /api/v1/users/{pk}/
-
- The path prefix is '/api/v1'
- """
- prefixes = []
- for path in paths:
- components = path.strip('/').split('/')
- initial_components = []
- for component in components:
- if '{' in component:
- break
- initial_components.append(component)
- prefix = '/'.join(initial_components[:-1])
- if not prefix:
- # We can just break early in the case that there's at least
- # one URL that doesn't have a path prefix.
- return '/'
- prefixes.append('/' + prefix + '/')
- return common_path(prefixes)
-
def has_view_permissions(self, path, method, view):
"""
Return `True` if the incoming request has the correct view permissions.
diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -1,4 +1,5 @@
import warnings
+from urllib.parse import urljoin
from django.core.validators import (
DecimalValidator, EmailValidator, MaxLengthValidator, MaxValueValidator,
@@ -39,17 +40,18 @@ def get_paths(self, request=None):
# Only generate the path prefix for paths that will be included
if not paths:
return None
- prefix = self.determine_path_prefix(paths)
- if prefix == '/': # no prefix
- prefix = ''
for path, method, view in view_endpoints:
if not self.has_view_permissions(path, method, view):
continue
operation = view.schema.get_operation(path, method)
- subpath = path[len(prefix):]
- result.setdefault(subpath, {})
- result[subpath][method.lower()] = operation
+ # Normalise path for any provided mount url.
+ if path.startswith('/'):
+ path = path[1:]
+ path = urljoin(self.url or '/', path)
+
+ result.setdefault(path, {})
+ result[path][method.lower()] = operation
return result
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -190,85 +190,36 @@ def test_repeat_operation_ids(self):
assert schema_str.count("newExample") == 1
assert schema_str.count("oldExample") == 1
-
[email protected](uritemplate is None, reason='uritemplate not installed.')
-@override_settings(REST_FRAMEWORK={'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.openapi.AutoSchema'})
-class TestGenerator(TestCase):
-
- def test_override_settings(self):
- assert isinstance(views.ExampleListView.schema, AutoSchema)
-
- def test_paths_construction(self):
- """Construction of the `paths` key."""
- patterns = [
- url(r'^example/?$', views.ExampleListView.as_view()),
- ]
- generator = SchemaGenerator(patterns=patterns)
- generator._initialise_endpoints()
-
- paths = generator.get_paths()
-
- assert '/example/' in paths
- example_operations = paths['/example/']
- assert len(example_operations) == 2
- assert 'get' in example_operations
- assert 'post' in example_operations
-
- def test_prefixed_paths_construction(self):
- """Construction of the `paths` key with a common prefix."""
- patterns = [
- url(r'^api/v1/example/?$', views.ExampleListView.as_view()),
- url(r'^api/v1/example/{pk}/?$', views.ExampleDetailView.as_view()),
- ]
- generator = SchemaGenerator(patterns=patterns)
- generator._initialise_endpoints()
-
- paths = generator.get_paths()
-
- assert '/example/' in paths
- assert '/example/{id}/' in paths
-
- def test_schema_construction(self):
- """Construction of the top level dictionary."""
- patterns = [
- url(r'^example/?$', views.ExampleListView.as_view()),
- ]
- generator = SchemaGenerator(patterns=patterns)
-
- request = create_request('/')
- schema = generator.get_schema(request=request)
-
- assert 'openapi' in schema
- assert 'paths' in schema
-
def test_serializer_datefield(self):
- patterns = [
- url(r'^example/?$', views.ExampleGenericViewSet.as_view({"get": "get"})),
- ]
- generator = SchemaGenerator(patterns=patterns)
-
- request = create_request('/')
- schema = generator.get_schema(request=request)
-
- response = schema['paths']['/example/']['get']['responses']
- response_schema = response['200']['content']['application/json']['schema']['properties']
+ path = '/'
+ method = 'GET'
+ view = create_view(
+ views.ExampleGenericAPIView,
+ method,
+ create_request(path),
+ )
+ inspector = AutoSchema()
+ inspector.view = view
+ responses = inspector._get_responses(path, method)
+ response_schema = responses['200']['content']['application/json']['schema']['properties']
assert response_schema['date']['type'] == response_schema['datetime']['type'] == 'string'
-
assert response_schema['date']['format'] == 'date'
assert response_schema['datetime']['format'] == 'date-time'
def test_serializer_validators(self):
- patterns = [
- url(r'^example/?$', views.ExampleValdidatedAPIView.as_view()),
- ]
- generator = SchemaGenerator(patterns=patterns)
-
- request = create_request('/')
- schema = generator.get_schema(request=request)
+ path = '/'
+ method = 'GET'
+ view = create_view(
+ views.ExampleValidatedAPIView,
+ method,
+ create_request(path),
+ )
+ inspector = AutoSchema()
+ inspector.view = view
- response = schema['paths']['/example/']['get']['responses']
- response_schema = response['200']['content']['application/json']['schema']['properties']
+ responses = inspector._get_responses(path, method)
+ response_schema = responses['200']['content']['application/json']['schema']['properties']
assert response_schema['integer']['type'] == 'integer'
assert response_schema['integer']['maximum'] == 99
@@ -307,3 +258,67 @@ def test_serializer_validators(self):
assert response_schema['ip']['type'] == 'string'
assert 'format' not in response_schema['ip']
+
+
[email protected](uritemplate is None, reason='uritemplate not installed.')
+@override_settings(REST_FRAMEWORK={'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.openapi.AutoSchema'})
+class TestGenerator(TestCase):
+
+ def test_override_settings(self):
+ assert isinstance(views.ExampleListView.schema, AutoSchema)
+
+ def test_paths_construction(self):
+ """Construction of the `paths` key."""
+ patterns = [
+ url(r'^example/?$', views.ExampleListView.as_view()),
+ ]
+ generator = SchemaGenerator(patterns=patterns)
+ generator._initialise_endpoints()
+
+ paths = generator.get_paths()
+
+ assert '/example/' in paths
+ example_operations = paths['/example/']
+ assert len(example_operations) == 2
+ assert 'get' in example_operations
+ assert 'post' in example_operations
+
+ def test_prefixed_paths_construction(self):
+ """Construction of the `paths` key maintains a common prefix."""
+ patterns = [
+ url(r'^v1/example/?$', views.ExampleListView.as_view()),
+ url(r'^v1/example/{pk}/?$', views.ExampleDetailView.as_view()),
+ ]
+ generator = SchemaGenerator(patterns=patterns)
+ generator._initialise_endpoints()
+
+ paths = generator.get_paths()
+
+ assert '/v1/example/' in paths
+ assert '/v1/example/{id}/' in paths
+
+ def test_mount_url_prefixed_to_paths(self):
+ patterns = [
+ url(r'^example/?$', views.ExampleListView.as_view()),
+ url(r'^example/{pk}/?$', views.ExampleDetailView.as_view()),
+ ]
+ generator = SchemaGenerator(patterns=patterns, url='/api')
+ generator._initialise_endpoints()
+
+ paths = generator.get_paths()
+
+ assert '/api/example/' in paths
+ assert '/api/example/{id}/' in paths
+
+ def test_schema_construction(self):
+ """Construction of the top level dictionary."""
+ patterns = [
+ url(r'^example/?$', views.ExampleListView.as_view()),
+ ]
+ generator = SchemaGenerator(patterns=patterns)
+
+ request = create_request('/')
+ schema = generator.get_schema(request=request)
+
+ assert 'openapi' in schema
+ assert 'paths' in schema
diff --git a/tests/schemas/views.py b/tests/schemas/views.py
--- a/tests/schemas/views.py
+++ b/tests/schemas/views.py
@@ -96,7 +96,7 @@ class ExampleValidatedSerializer(serializers.Serializer):
ip = serializers.IPAddressField()
-class ExampleValdidatedAPIView(generics.GenericAPIView):
+class ExampleValidatedAPIView(generics.GenericAPIView):
serializer_class = ExampleValidatedSerializer
def get(self, *args, **kwargs):
| get_schema_view() does not respect url= keyword argument
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
1. create an app with the following content
test_app/urls.py
```python
from django.urls import path
from rest_framework.schemas import get_schema_view
from rest_framework import views, response
class ExampleModelView(views.APIView):
def get(self, request, fmt=None):
return response.Response(status=200, data={'test_endpoint': 'success'})
schema_view = get_schema_view(
title='Example Schema',
url='api/' # note that url= is being specified here
)
urlpatterns = [
path('api/test', ExampleModelView.as_view()),
path('schema/', schema_view, name='schema-endpoint')
]
```
prefix_test/urls.py (root urls module)
```python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('test_app.urls'))
]
```
2. run the django testserver and navigate to localhost:8000/schema
## Expected behavior
A yml schema spec with the content:
```yml
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/vnd.oai.openapi
Vary: Accept
openapi: 3.0.2
info:
title: Example Schema
version: TODO
paths:
/api/test:
get:
operationId: ListExampleModels
parameters: []
responses:
'200':
content:
application/json:
schema: {}
```
## Actual behavior
```yml
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/vnd.oai.openapi
Vary: Accept
openapi: 3.0.2
info:
title: Example Schema
version: TODO
paths:
/test:
get:
operationId: ListExampleModels
parameters: []
responses:
'200':
content:
application/json:
schema: {}
```
note the difference between the given paths. Issue #6675 appears similar but not identical. If one examines the openapi.py [`get_paths()`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas/openapi.py#L34) method, it's clear that a url prefix is being determined, removed from url endpoint paths and discarded.
| 2019-07-20T19:40:14 |
|
encode/django-rest-framework | 6,832 | encode__django-rest-framework-6832 | [
"6831"
] | 659375ffe6dedca02694dbd94ffddb8be907b7bb | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -377,7 +377,7 @@ def _map_serializer(self, serializer):
if field.default and field.default != empty: # why don't they use None?!
schema['default'] = field.default
if field.help_text:
- schema['description'] = field.help_text
+ schema['description'] = str(field.help_text)
self._map_field_validators(field.validators, schema)
properties[field.field_name] = schema
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -1,6 +1,7 @@
import pytest
from django.conf.urls import url
from django.test import RequestFactory, TestCase, override_settings
+from django.utils.translation import gettext_lazy as _
from rest_framework import filters, generics, pagination, routers, serializers
from rest_framework.compat import uritemplate
@@ -52,6 +53,15 @@ def test_list_field_mapping(self):
with self.subTest(field=field):
assert inspector._map_field(field) == mapping
+ def test_lazy_string_field(self):
+ class Serializer(serializers.Serializer):
+ text = serializers.CharField(help_text=_('lazy string'))
+
+ inspector = AutoSchema()
+
+ data = inspector._map_serializer(Serializer())
+ assert isinstance(data['properties']['text']['description'], str), "description must be str"
+
@pytest.mark.skipif(uritemplate is None, reason='uritemplate not installed.')
class TestOperationIntrospection(TestCase):
| OpenAPI AutoSchema does not handle lazy strings / ugettext properly
## Steps to reproduce
1. create a `UserSerializer` as instance of `ModelSerializer` and use it in a viewset (just like in quickstart tutorial)
2. run `manage.py generateschema`
## Expected behavior
`generateschema` returns a valid OpenAPI schema
## Actual behavior
The generated schema's description fields contains unserialized lazy strings
```yaml
openapi: 3.0.2
info:
title: ''
version: TODO
paths:
/users/:
get:
operationId: ListUsers
parameters: []
responses:
'200':
content:
application/json:
schema:
required:
- username
properties:
url:
type: string
readOnly: true
username:
type: string
description: &id003 !!python/object/apply:django.utils.functional._lazy_proxy_unpickle
- &id001 !!python/name:django.utils.translation.ugettext ''
- !!python/tuple
- Required. 150 characters or fewer. Letters, digits and @/./+/-/_
only.
- {}
- &id002 !!python/name:builtins.str ''
```
# Suggested solution
Force description to text in [`schemas.openapi.AutoSchema._map_serializer()`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas/openapi.py#L372)
# Workaround
This problem can be worked around with a custom schema generator:
```python
from django.utils.encoding import force_text
from rest_framework.schemas.openapi import AutoSchema
class FixedAutoSchema(AutoSchema):
def _map_serializer(self, serializer):
result = super()._map_serializer(serializer)
for prop, value in result['properties'].items():
if 'description' in value:
value['description'] = force_text(value['description'])
return result
# in settings.py
DEFAULT_SCHEMA_CLASS = 'myapp.FixedAutoSchema'
```
| Hi @chrisv2. Thanks. (The `force_text()` does the business yes?)
`django.utils.encoding.force_text` solves this, yes. That's what I use as workaround.
I'd do a PR but I'm not really familiar with DRFs unittests so that may take a while.
Hey @chrisv2.
Look at https://github.com/encode/django-rest-framework/commit/2138f558cee33db9dbcff393517173a42a363421
If you added a case in `TestFieldMapping` which passed _map_field a `CharField` instance with a lazy `help_text` that asserted that we got a `str` there back, I think it would be enough.
If you'd like to have a go at that it would be super to have you onboard! 🙂
Thank's, I'll try.
Awesome. If you open a PR early, I'm happy to assist if you get stuck somewhere. | 2019-07-24T10:11:45 |
encode/django-rest-framework | 6,837 | encode__django-rest-framework-6837 | [
"6836"
] | 7e1c4be7ced1fe242540c796d046d665f2a40350 | diff --git a/rest_framework/views.py b/rest_framework/views.py
--- a/rest_framework/views.py
+++ b/rest_framework/views.py
@@ -356,7 +356,15 @@ def check_throttles(self, request):
throttle_durations.append(throttle.wait())
if throttle_durations:
- self.throttled(request, max(throttle_durations))
+ # Filter out `None` values which may happen in case of config / rate
+ # changes, see #1438
+ durations = [
+ duration for duration in throttle_durations
+ if duration is not None
+ ]
+
+ duration = max(durations, default=None)
+ self.throttled(request, duration)
def determine_version(self, request, *args, **kwargs):
"""
| diff --git a/tests/test_throttling.py b/tests/test_throttling.py
--- a/tests/test_throttling.py
+++ b/tests/test_throttling.py
@@ -159,6 +159,27 @@ def test_request_throttling_multiple_throttles(self):
assert response.status_code == 429
assert int(response['retry-after']) == 58
+ def test_throttle_rate_change_negative(self):
+ self.set_throttle_timer(MockView_DoubleThrottling, 0)
+ request = self.factory.get('/')
+ for dummy in range(24):
+ response = MockView_DoubleThrottling.as_view()(request)
+ assert response.status_code == 429
+ assert int(response['retry-after']) == 60
+
+ previous_rate = User3SecRateThrottle.rate
+ try:
+ User3SecRateThrottle.rate = '1/sec'
+
+ for dummy in range(24):
+ response = MockView_DoubleThrottling.as_view()(request)
+
+ assert response.status_code == 429
+ assert int(response['retry-after']) == 60
+ finally:
+ # reset
+ User3SecRateThrottle.rate = previous_rate
+
def ensure_response_header_contains_proper_throttle_field(self, view, expected_headers):
"""
Ensure the response returns an Retry-After field with status and next attributes
| TypeError: '>' not supported between instances of 'float' and 'NoneType'
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [x] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
On Python 3.
This is a regression from https://github.com/encode/django-rest-framework/commit/afb678433b7dc068213e6e8a359ad1f6fff05b0d, when running a config-change scenario as described in https://github.com/encode/django-rest-framework/issues/1438
## Expected behavior
Not raise an exception
## Actual behavior
Raising `TypeError: '>' not supported between instances of 'float' and 'NoneType'`
| 2019-07-26T14:30:14 |
|
encode/django-rest-framework | 6,850 | encode__django-rest-framework-6850 | [
"6833"
] | 0ebfbfdf81b71a5ba3600e6edbd666c5b732fb23 | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -490,6 +490,10 @@ def _get_responses(self, path, method):
'content': {
ct: {'schema': response_schema}
for ct in self.content_types
- }
+ },
+ # description is a mandatory property,
+ # https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#responseObject
+ # TODO: put something meaningful into it
+ 'description': ""
}
}
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -84,6 +84,7 @@ def test_path_without_parameters(self):
'parameters': [],
'responses': {
'200': {
+ 'description': '',
'content': {
'application/json': {
'schema': {
@@ -190,6 +191,7 @@ class View(generics.GenericAPIView):
responses = inspector._get_responses(path, method)
assert responses['200']['content']['application/json']['schema']['required'] == ['text']
assert list(responses['200']['content']['application/json']['schema']['properties'].keys()) == ['text']
+ assert 'description' in responses['200']
def test_response_body_nested_serializer(self):
path = '/'
@@ -243,6 +245,7 @@ class View(generics.GenericAPIView):
responses = inspector._get_responses(path, method)
assert responses == {
'200': {
+ 'description': '',
'content': {
'application/json': {
'schema': {
@@ -283,6 +286,7 @@ class View(generics.GenericAPIView):
responses = inspector._get_responses(path, method)
assert responses == {
'200': {
+ 'description': '',
'content': {
'application/json': {
'schema': {
| OpenAPI: 'description' is a mandatory field on Response.StatusCode
As per [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#responseObject), the `response` object must have a `description` property.
## Steps to reproduce
Generate a schema with `manage.py generateschema` and paste it into https://editor.swagger.org/
## Expected behavior
There should be no error message
## Actual behavior
We get an error message
```
Structural error at paths.[path].get.responses.200
should have required property 'description'
missingProperty: description'
```
Note: The description should be added in `schemas.openapi.AutoSchema._get_responses()`, however I'm not sure what to put in there. An empty string does satisfy editor.swagger.io, but of course doesn't help much.
Should we put the serializer's docstring into the description? Would that make sense?
| Let's start by including it but leaving it as an empty string.
Putting something meaningful in there could then be left as a follow up.
Pull requests resolving this would be most welcome.
Thanks! 😃 | 2019-07-31T06:46:18 |
encode/django-rest-framework | 6,851 | encode__django-rest-framework-6851 | [
"6834"
] | 335054a5d36b352a58286b303b608b6bf48152f8 | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -381,10 +381,14 @@ def _map_serializer(self, serializer):
self._map_field_validators(field.validators, schema)
properties[field.field_name] = schema
- return {
- 'required': required,
- 'properties': properties,
+
+ result = {
+ 'properties': properties
}
+ if len(required) > 0:
+ result['required'] = required
+
+ return result
def _map_field_validators(self, validators, schema):
"""
@@ -470,7 +474,8 @@ def _get_responses(self, path, method):
for name, schema in item_schema['properties'].copy().items():
if 'writeOnly' in schema:
del item_schema['properties'][name]
- item_schema['required'] = [f for f in item_schema['required'] if f != name]
+ if 'required' in item_schema:
+ item_schema['required'] = [f for f in item_schema['required'] if f != name]
if is_list_view(path, method, self.view):
response_schema = {
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -142,6 +142,32 @@ class View(generics.GenericAPIView):
assert request_body['content']['application/json']['schema']['required'] == ['text']
assert list(request_body['content']['application/json']['schema']['properties'].keys()) == ['text']
+ def test_empty_required(self):
+ path = '/'
+ method = 'POST'
+
+ class Serializer(serializers.Serializer):
+ read_only = serializers.CharField(read_only=True)
+ write_only = serializers.CharField(write_only=True, required=False)
+
+ class View(generics.GenericAPIView):
+ serializer_class = Serializer
+
+ view = create_view(
+ View,
+ method,
+ create_request(path)
+ )
+ inspector = AutoSchema()
+ inspector.view = view
+
+ request_body = inspector._get_request_body(path, method)
+ # there should be no empty 'required' property, see #6834
+ assert 'required' not in request_body['content']['application/json']['schema']
+
+ for response in inspector._get_responses(path, method).values():
+ assert 'required' not in response['content']['application/json']['schema']
+
def test_response_body_generation(self):
path = '/'
method = 'POST'
| OpenAPI: Schema.required must not be an empty list
Note: I don't know where (or whether) the [spec](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schema-object) actually says so, but editor.swagger.io complains about empty `Schema.required` properties.
`AutoSchema._get_responses` and `AutoSchema._get_request_body` happily create such empty lists and therefore it should be fixed there.
| I assume it's just following the spec badly there, but we should resolve it anyways.
Presumably we should just pop `required` out if it's an empty list?
Want to take a crack at a pull request for this?
Assign both tickets to me, I'll have a go at this tomorrow, today it's just too hot for work ;)
Hey @chrisv2. Super thanks. (Again if you want/need input open the PR early and I'm happy to comment.) Champion.
I'll roll another minor release once this one is in.
(Worth ironing out the various niggles here quickly.) | 2019-07-31T07:43:39 |
encode/django-rest-framework | 6,860 | encode__django-rest-framework-6860 | [
"6856",
"6856"
] | f7dc6b56569790d6cea0ab19485832064f1c8069 | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -465,6 +465,13 @@ def _get_request_body(self, path, method):
def _get_responses(self, path, method):
# TODO: Handle multiple codes and pagination classes.
+ if method == 'DELETE':
+ return {
+ '204': {
+ 'description': ''
+ }
+ }
+
item_schema = {}
serializer = self._get_serializer(path, method)
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -264,6 +264,29 @@ class View(generics.GenericAPIView):
},
}
+ def test_delete_response_body_generation(self):
+ """Test that a view's delete method generates a proper response body schema."""
+ path = '/{id}/'
+ method = 'DELETE'
+
+ class View(generics.DestroyAPIView):
+ serializer_class = views.ExampleSerializer
+
+ view = create_view(
+ View,
+ method,
+ create_request(path),
+ )
+ inspector = AutoSchema()
+ inspector.view = view
+
+ responses = inspector._get_responses(path, method)
+ assert responses == {
+ '204': {
+ 'description': '',
+ },
+ }
+
def test_retrieve_response_body_generation(self):
"""Test that a list of properties is returned for retrieve item views."""
path = '/{id}/'
| DRF generates incorrect OpenAPI schema for generic views' delete method
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
```
# view.py
from rest_framework import generics
from rest_framework import serializers
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
# urls.py
urlpatterns = [
...
path('api/books/<int:pk>/', views.BookDetail.as_view()),
...
]
```
## Expected behavior
```
$ ./manage.py generateschema
openapi: 3.0.2
info:
title: ''
version: TODO
paths:
/api/books/{id}/:
delete:
operationId: DestroyBook
parameters:
- name: id
in: path
required: true
description: A unique integer value identifying this book.
schema:
type: string
responses:
'204':
description: ''
```
## Actual behavior
```
$ ./manage.py generateschema
openapi: 3.0.2
info:
title: ''
version: TODO
paths:
/api/books/{id}/:
delete:
operationId: DestroyBook
parameters:
- name: id
in: path
required: true
description: A unique integer value identifying this book.
schema:
type: string
responses:
'200':
content:
application/json:
schema:
required:
- title
properties:
id:
type: integer
readOnly: true
title:
type: string
maxLength: 200
```
DRF generates incorrect OpenAPI schema for generic views' delete method
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
```
# view.py
from rest_framework import generics
from rest_framework import serializers
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
# urls.py
urlpatterns = [
...
path('api/books/<int:pk>/', views.BookDetail.as_view()),
...
]
```
## Expected behavior
```
$ ./manage.py generateschema
openapi: 3.0.2
info:
title: ''
version: TODO
paths:
/api/books/{id}/:
delete:
operationId: DestroyBook
parameters:
- name: id
in: path
required: true
description: A unique integer value identifying this book.
schema:
type: string
responses:
'204':
description: ''
```
## Actual behavior
```
$ ./manage.py generateschema
openapi: 3.0.2
info:
title: ''
version: TODO
paths:
/api/books/{id}/:
delete:
operationId: DestroyBook
parameters:
- name: id
in: path
required: true
description: A unique integer value identifying this book.
schema:
type: string
responses:
'200':
content:
application/json:
schema:
required:
- title
properties:
id:
type: integer
readOnly: true
title:
type: string
maxLength: 200
```
| Yes, this is valid. `DestroyModelMixin` returns `Response(status=status.HTTP_204_NO_CONTENT)`.
Fix here should be a test case plus an adjustment to _get_responses to sensibly handle the `DELETE` method case.
https://github.com/encode/django-rest-framework/blob/b45ff072947d01917132ef6993bf1b7f46d9f2c8/rest_framework/schemas/openapi.py#L462
Maybe could be as simple as
```
# as a guard at the beginning...
if method == 'DELETE':
return {'204': {description: ''}}
```
Thanks for the report @knivets. Fancy working on a PR for this?
Sure I can work on this. Will submit a PR this week.
Awesome. Welcome aboard! 🎉
If you need any assistance open a PR early and @carltongibson me, so I'll get a message.
Thanks Carlton! :)
Yes, this is valid. `DestroyModelMixin` returns `Response(status=status.HTTP_204_NO_CONTENT)`.
Fix here should be a test case plus an adjustment to _get_responses to sensibly handle the `DELETE` method case.
https://github.com/encode/django-rest-framework/blob/b45ff072947d01917132ef6993bf1b7f46d9f2c8/rest_framework/schemas/openapi.py#L462
Maybe could be as simple as
```
# as a guard at the beginning...
if method == 'DELETE':
return {'204': {description: ''}}
```
Thanks for the report @knivets. Fancy working on a PR for this?
Sure I can work on this. Will submit a PR this week.
Awesome. Welcome aboard! 🎉
If you need any assistance open a PR early and @carltongibson me, so I'll get a message.
Thanks Carlton! :) | 2019-08-09T12:32:42 |
encode/django-rest-framework | 6,866 | encode__django-rest-framework-6866 | [
"6862"
] | a1424675861e6add5a05710fc3a88922e529c340 | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -378,7 +378,7 @@ def _map_serializer(self, serializer):
schema['default'] = field.default
if field.help_text:
schema['description'] = str(field.help_text)
- self._map_field_validators(field.validators, schema)
+ self._map_field_validators(field, schema)
properties[field.field_name] = schema
@@ -390,13 +390,11 @@ def _map_serializer(self, serializer):
return result
- def _map_field_validators(self, validators, schema):
+ def _map_field_validators(self, field, schema):
"""
map field validators
- :param list:validators: list of field validators
- :param dict:schema: schema that the validators get added to
"""
- for v in validators:
+ for v in field.validators:
# "Formats such as "email", "uuid", and so on, MAY be used even though undefined by this specification."
# https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#data-types
if isinstance(v, EmailValidator):
@@ -406,9 +404,15 @@ def _map_field_validators(self, validators, schema):
if isinstance(v, RegexValidator):
schema['pattern'] = v.regex.pattern
elif isinstance(v, MaxLengthValidator):
- schema['maxLength'] = v.limit_value
+ attr_name = 'maxLength'
+ if isinstance(field, serializers.ListField):
+ attr_name = 'maxItems'
+ schema[attr_name] = v.limit_value
elif isinstance(v, MinLengthValidator):
- schema['minLength'] = v.limit_value
+ attr_name = 'minLength'
+ if isinstance(field, serializers.ListField):
+ attr_name = 'minItems'
+ schema[attr_name] = v.limit_value
elif isinstance(v, MaxValueValidator):
schema['maximum'] = v.limit_value
elif isinstance(v, MinValueValidator):
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -395,6 +395,9 @@ def test_serializer_validators(self):
assert properties['string']['minLength'] == 2
assert properties['string']['maxLength'] == 10
+ assert properties['lst']['minItems'] == 2
+ assert properties['lst']['maxItems'] == 10
+
assert properties['regex']['pattern'] == r'[ABC]12{3}'
assert properties['regex']['description'] == 'must have an A, B, or C followed by 1222'
diff --git a/tests/schemas/views.py b/tests/schemas/views.py
--- a/tests/schemas/views.py
+++ b/tests/schemas/views.py
@@ -85,6 +85,12 @@ class ExampleValidatedSerializer(serializers.Serializer):
),
help_text='must have an A, B, or C followed by 1222'
)
+ lst = serializers.ListField(
+ validators=(
+ MaxLengthValidator(limit_value=10),
+ MinLengthValidator(limit_value=2),
+ )
+ )
decimal1 = serializers.DecimalField(max_digits=6, decimal_places=2)
decimal2 = serializers.DecimalField(max_digits=5, decimal_places=0,
validators=(DecimalValidator(max_digits=17, decimal_places=4),))
| DRF generates incorrect attributes for serializers.ListField
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
```
# view.py
from rest_framework import generics
from rest_framework import serializers
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
class BookSerializer(serializers.ModelSerializer):
tags = serializers.ListField(min_length=2, max_length=5)
class Meta:
model = Book
fields = ('tags',)
class BooksView(generics.ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
# urls.py
urlpatterns = [
...
path('api/books/', views.BooksView.as_view()),
...
]
```
## Expected behavior
```
$ ./manage.py generateschema
openapi: 3.0.2
info:
title: ''
version: TODO
paths:
/api/books/:
get:
operationId: ListBooks
parameters: []
responses:
'200':
content:
application/json:
schema:
required:
- tags
properties:
tags:
type: array
items: {}
maxItems: 5
minItems: 2
```
## Actual behavior
```
$ ./manage.py generateschema
openapi: 3.0.2
info:
title: ''
version: TODO
paths:
/api/books/:
get:
operationId: ListBooks
parameters: []
responses:
'200':
content:
application/json:
schema:
required:
- tags
properties:
tags:
type: array
items: {}
maxLength: 5
minLength: 2
```
https://swagger.io/docs/specification/data-models/data-types/#array-length
| @carltongibson please confirm whether this is something you'd like me to work on 🙂
There's one more https://github.com/encode/django-rest-framework/issues/6863
Hi @knivets I’m struggling to spot the difference between the actual and expected here. Could you ping it out for me please? (Sorry)
Oh, items vs length. Right.
Yes, I guess we need an adjustment here, after mapping validators. (Grrrr. Messy spec. Grrrr. 🙂) | 2019-08-11T13:06:27 |
encode/django-rest-framework | 6,876 | encode__django-rest-framework-6876 | [
"6875",
"6875"
] | f8c16441fa69850fd581c23807a8a0e38f3239d4 | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -111,7 +111,7 @@ def _get_operation_id(self, path, method):
"""
method_name = getattr(self.view, 'action', method.lower())
if is_list_view(path, method, self.view):
- action = 'List'
+ action = 'list'
elif method_name not in self.method_mapping:
action = method_name
else:
@@ -135,10 +135,13 @@ def _get_operation_id(self, path, method):
name = name[:-7]
elif name.endswith('View'):
name = name[:-4]
- if name.endswith(action): # ListView, UpdateAPIView, ThingDelete ...
+
+ # Due to camel-casing of classes and `action` being lowercase, apply title in order to find if action truly
+ # comes at the end of the name
+ if name.endswith(action.title()): # ListView, UpdateAPIView, ThingDelete ...
name = name[:-len(action)]
- if action == 'List' and not name.endswith('s'): # ListThings instead of ListThing
+ if action == 'list' and not name.endswith('s'): # listThings instead of listThing
name += 's'
return action + name
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -80,7 +80,7 @@ def test_path_without_parameters(self):
operation = inspector.get_operation(path, method)
assert operation == {
- 'operationId': 'ListExamples',
+ 'operationId': 'listExamples',
'parameters': [],
'responses': {
'200': {
@@ -402,7 +402,7 @@ def test_operation_id_generation(self):
inspector.view = view
operationId = inspector._get_operation_id(path, method)
- assert operationId == 'ListExamples'
+ assert operationId == 'listExamples'
def test_repeat_operation_ids(self):
router = routers.SimpleRouter()
| OpenAPI Schema inconsistent operationId casing
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [x] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
There is inconsistent casing of titles in the the OpenAPI `operationId` naming.
## Expected behavior
Expected behavior is that the method names are consistent in case between them. I.e.
```
RetrieveRegistrant
ListRegistrant
```
or
```
retrieveRegistrant
listRegistrant
```
Given that the rest of the method names are lowercase, I would opt for `listRegistrant` (initial lower camel case) over CamelCase.
## Actual behavior
It lowercases all methods names accept for List which is hardcoded.
```
retrieveRegistrant
ListRegistrants
```
Problem area:
[https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas/openapi.py#L112](https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas/openapi.py#L112
OpenAPI Schema inconsistent operationId casing
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [x] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
There is inconsistent casing of titles in the the OpenAPI `operationId` naming.
## Expected behavior
Expected behavior is that the method names are consistent in case between them. I.e.
```
RetrieveRegistrant
ListRegistrant
```
or
```
retrieveRegistrant
listRegistrant
```
Given that the rest of the method names are lowercase, I would opt for `listRegistrant` (initial lower camel case) over CamelCase.
## Actual behavior
It lowercases all methods names accept for List which is hardcoded.
```
retrieveRegistrant
ListRegistrants
```
Problem area:
[https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas/openapi.py#L112](https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas/openapi.py#L112
| Hi @peterfarrell. Want to make a PR correcting that `L`?
Hi @peterfarrell. Want to make a PR correcting that `L`? | 2019-08-19T20:09:18 |
encode/django-rest-framework | 6,892 | encode__django-rest-framework-6892 | [
"6181"
] | ec1b14174f8717337fc4402c7cea43f647e2586e | diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py
--- a/rest_framework/utils/field_mapping.py
+++ b/rest_framework/utils/field_mapping.py
@@ -91,7 +91,8 @@ def get_field_kwargs(field_name, model_field):
if isinstance(model_field, models.SlugField):
kwargs['allow_unicode'] = model_field.allow_unicode
- if isinstance(model_field, models.TextField) or (postgres_fields and isinstance(model_field, postgres_fields.JSONField)):
+ if isinstance(model_field, models.TextField) and not model_field.choices or \
+ (postgres_fields and isinstance(model_field, postgres_fields.JSONField)):
kwargs['style'] = {'base_template': 'textarea.html'}
if isinstance(model_field, models.AutoField) or not model_field.editable:
| diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py
--- a/tests/test_model_serializer.py
+++ b/tests/test_model_serializer.py
@@ -89,6 +89,7 @@ class FieldOptionsModel(models.Model):
default_field = models.IntegerField(default=0)
descriptive_field = models.IntegerField(help_text='Some help text', verbose_name='A label')
choices_field = models.CharField(max_length=100, choices=COLOR_CHOICES)
+ text_choices_field = models.TextField(choices=COLOR_CHOICES)
class ChoicesModel(models.Model):
@@ -211,6 +212,7 @@ class Meta:
default_field = IntegerField(required=False)
descriptive_field = IntegerField(help_text='Some help text', label='A label')
choices_field = ChoiceField(choices=(('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')))
+ text_choices_field = ChoiceField(choices=(('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')))
""")
self.assertEqual(repr(TestSerializer()), expected)
| TextField model with choices set should default to a select box
## Steps to reproduce
Create a models.TextField with a choices parameter and visit its representation through the browsable API
## Expected behavior
Show a select box
## Actual behavior
Shows a text area
| 2019-08-25T13:55:45 |
|
encode/django-rest-framework | 6,914 | encode__django-rest-framework-6914 | [
"6913"
] | 89ac0a1c7ef6153312890376ac142674b28b04f1 | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -344,6 +344,7 @@ def _map_field(self, field):
serializers.BooleanField: 'boolean',
serializers.JSONField: 'object',
serializers.DictField: 'object',
+ serializers.HStoreField: 'object',
}
return {'type': FIELD_CLASS_SCHEMA_TYPE.get(field.__class__, 'string')}
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -437,6 +437,22 @@ def test_serializer_datefield(self):
assert properties['date']['format'] == 'date'
assert properties['datetime']['format'] == 'date-time'
+ def test_serializer_hstorefield(self):
+ path = '/'
+ method = 'GET'
+ view = create_view(
+ views.ExampleGenericAPIView,
+ method,
+ create_request(path),
+ )
+ inspector = AutoSchema()
+ inspector.view = view
+
+ responses = inspector._get_responses(path, method)
+ response_schema = responses['200']['content']['application/json']['schema']
+ properties = response_schema['items']['properties']
+ assert properties['hstore']['type'] == 'object'
+
def test_serializer_validators(self):
path = '/'
method = 'GET'
diff --git a/tests/schemas/views.py b/tests/schemas/views.py
--- a/tests/schemas/views.py
+++ b/tests/schemas/views.py
@@ -33,6 +33,7 @@ def get(self, *args, **kwargs):
class ExampleSerializer(serializers.Serializer):
date = serializers.DateField()
datetime = serializers.DateTimeField()
+ hstore = serializers.HStoreField()
class ExampleGenericAPIView(generics.GenericAPIView):
| Schema generation with an HStoreField gives an incorrect type
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
On any serializer, add an HStoreField.
``` python
class HStoredSerializer(serializers.Serializer):
myfield = serializers.HStoreField()
class HStoredAPIView(CreateAPIView):
serializer_class = HStoredSerializer
...
```
## Expected behavior
Output of `./manage.py generateschema`:
``` yaml
paths:
/api/hstored:
post:
operationId: CreateHStored
parameters: []
requestBody:
content:
application/json:
schema:
required:
- myfield
properties:
myfield:
type: object
```
## Actual behavior
Output of `./manage.py generateschema`:
``` yaml
paths:
/api/hstored:
post:
operationId: CreateHStored
parameters: []
requestBody:
content:
application/json:
schema:
required:
- myfield
properties:
myfield:
type: string
```
It seems that we should only need to add a line to the `FIELD_CLASS_SCHEMA_TYPE` dict [found here](https://github.com/encode/django-rest-framework/blob/89ac0a1c7ef6153312890376ac142674b28b04f1/rest_framework/schemas/openapi.py#L343); if that's all we need, I can easily open a PR myself.
| Hi @Lucidiot. Yep, that plus a test case should do it.
Thanks for the report! | 2019-09-05T16:18:03 |
encode/django-rest-framework | 6,980 | encode__django-rest-framework-6980 | [
"5798"
] | 0fd72f17ee18506c02b4c0f0e4af368e3bedac3e | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -299,18 +299,22 @@ def _get_declared_fields(cls, bases, attrs):
if isinstance(obj, Field)]
fields.sort(key=lambda x: x[1]._creation_counter)
- # If this class is subclassing another Serializer, add that Serializer's
- # fields. Note that we loop over the bases in *reverse*. This is necessary
- # in order to maintain the correct order of fields.
- for base in reversed(bases):
- if hasattr(base, '_declared_fields'):
- fields = [
- (field_name, obj) for field_name, obj
- in base._declared_fields.items()
- if field_name not in attrs
- ] + fields
-
- return OrderedDict(fields)
+ # Ensures a base class field doesn't override cls attrs, and maintains
+ # field precedence when inheriting multiple parents. e.g. if there is a
+ # class C(A, B), and A and B both define 'field', use 'field' from A.
+ known = set(attrs)
+
+ def visit(name):
+ known.add(name)
+ return name
+
+ base_fields = [
+ (visit(name), f)
+ for base in bases if hasattr(base, '_declared_fields')
+ for name, f in base._declared_fields.items() if name not in known
+ ]
+
+ return OrderedDict(base_fields + fields)
def __new__(cls, name, bases, attrs):
attrs['_declared_fields'] = cls._get_declared_fields(bases, attrs)
| diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -682,3 +682,53 @@ class Grandchild(Child):
assert len(Parent().get_fields()) == 2
assert len(Child().get_fields()) == 2
assert len(Grandchild().get_fields()) == 2
+
+ def test_multiple_inheritance(self):
+ class A(serializers.Serializer):
+ field = serializers.CharField()
+
+ class B(serializers.Serializer):
+ field = serializers.IntegerField()
+
+ class TestSerializer(A, B):
+ pass
+
+ fields = {
+ name: type(f) for name, f
+ in TestSerializer()._declared_fields.items()
+ }
+ assert fields == {
+ 'field': serializers.CharField,
+ }
+
+ def test_field_ordering(self):
+ class Base(serializers.Serializer):
+ f1 = serializers.CharField()
+ f2 = serializers.CharField()
+
+ class A(Base):
+ f3 = serializers.IntegerField()
+
+ class B(serializers.Serializer):
+ f3 = serializers.CharField()
+ f4 = serializers.CharField()
+
+ class TestSerializer(A, B):
+ f2 = serializers.IntegerField()
+ f5 = serializers.CharField()
+
+ fields = {
+ name: type(f) for name, f
+ in TestSerializer()._declared_fields.items()
+ }
+
+ # `IntegerField`s should be the 'winners' in field name conflicts
+ # - `TestSerializer.f2` should override `Base.F2`
+ # - `A.f3` should override `B.f3`
+ assert fields == {
+ 'f1': serializers.CharField,
+ 'f2': serializers.IntegerField,
+ 'f3': serializers.IntegerField,
+ 'f4': serializers.CharField,
+ 'f5': serializers.CharField,
+ }
| Inheriting multiple Serializers gives unexpected order of overloading of fields
## Checklist
- [ x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [ x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [ x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [ x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [ x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
inheriting a serializer from several other serializers. Some of them have fields with same name, and that name is not present localy in inheriting one
## Expected behavior
from those same-name fields, the first as in the order of inheritance should win
## Actual behavior
last one wins.
This is because in SerializerMetaclass._get_declared_fields():
a) bases is walked in reverse
b) fields are prepended (i.e. reversing order once more)
c) repeating field-names are added just as any other; check is only against local-attrs
d) result list goes into ordereddict... hence last wins.
Easiest remedy is to reverse bases once more on entrance to this func...
or to avoid breaking unknown amounts of code that *relies* on current behavior, keep it as is, and put big warning somewhere as documentation.
have fun
| Hi.
From the description, and from experience of working with inheritance and serialisers, the behaviour you describe sounds expected.
I'm going to close this as such. If you can expand your "Steps to Reproduce" to include an actual (and minimal) code reproduce then I'm happy to re-open. (As it stands the issue is not actionable.)
Thanks.
Hi @carltongibson,
I've run into this before. Here's a minimal example:
```
>>> from rest_framework import serializers
>>> class First(serializers.Serializer):
... a = serializers.CharField()
>>> class Second(serializers.Serializer):
... a = serializers.IntegerField()
>>> class MySerializer(First, Second):
... pass
>>> MySerializer()
MySerializer():
a = IntegerField()
```
Under normal Python MRO, you'd expect the `a` field on `MySerializer` to be a `CharField()` since that's what's on `First`. However, we get an `IntegerField` due to the combination of reversing the bases and prepending the fields as described above.
It would have the intuitive behavior if https://github.com/encode/django-rest-framework/blob/0e4811e9ce30904bbd4f3aef6446d68be6c3a658/rest_framework/serializers.py#L304 iterated over the bases in the normal, rather than reverse, order.
Processing the mro in reverse is correct, since we want classes higher up in the mro to be overridden by those lower in the mro. The issue is the subsequent line, that prepends fields, effectively reversing order again (as pointed out by @svilendobrev).
Reopening as this looks valid, and the above is enough of a test case to work with. | 2019-10-09T05:12:25 |
encode/django-rest-framework | 7,018 | encode__django-rest-framework-7018 | [
"7017"
] | 5e8fe6edf0b25506c5bc3ce749c5b9d5cb9e7e7e | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -265,9 +265,13 @@ def _map_field(self, field):
'items': {},
}
if not isinstance(field.child, _UnvalidatedField):
- mapping['items'] = {
- "type": self._map_field(field.child).get('type')
+ map_field = self._map_field(field.child)
+ items = {
+ "type": map_field.get('type')
}
+ if 'format' in map_field:
+ items['format'] = map_field.get('format')
+ mapping['items'] = items
return mapping
# DateField and DateTimeField type is string
@@ -337,6 +341,9 @@ def _map_field(self, field):
'type': 'integer'
}
self._map_min_max(field, content)
+ # 2147483647 is max for int32_size, so we use int64 for format
+ if int(content.get('maximum', 0)) > 2147483647 or int(content.get('minimum', 0)) > 2147483647:
+ content['format'] = 'int64'
return content
# Simplest cases, default to 'string' type:
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -48,6 +48,10 @@ def test_list_field_mapping(self):
(serializers.ListField(child=serializers.BooleanField()), {'items': {'type': 'boolean'}, 'type': 'array'}),
(serializers.ListField(child=serializers.FloatField()), {'items': {'type': 'number'}, 'type': 'array'}),
(serializers.ListField(child=serializers.CharField()), {'items': {'type': 'string'}, 'type': 'array'}),
+ (serializers.ListField(child=serializers.IntegerField(max_value=4294967295)),
+ {'items': {'type': 'integer', 'format': 'int64'}, 'type': 'array'}),
+ (serializers.IntegerField(min_value=2147483648),
+ {'type': 'integer', 'minimum': 2147483648, 'format': 'int64'}),
]
for field, mapping in cases:
with self.subTest(field=field):
| integer types that are greater than 32bit should use format int64
## Checklist
- [X] I have verified that that issue exists against the `master` branch of Django REST framework.
- [X] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [X] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [X] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [X] I have reduced the issue to the simplest possible case.
- [X] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Create a project that uses a django 2.1.x PositiveIntegerField in the api. Use drf to generate an openapi spec
## Expected behavior
the field should be represented as a `type` field of `integer` and there should be a `format` field of `int64`
## Actual behavior
the field has `type` field of `integer`, but there is no `format` field of `int64`
| 2019-10-24T19:05:04 |
|
encode/django-rest-framework | 7,059 | encode__django-rest-framework-7059 | [
"4748"
] | a73d3c309f0736f46dd46c99e15e1102af26dacb | diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -344,7 +344,7 @@ def to_internal_value(self, data):
if data.startswith(prefix):
data = '/' + data[len(prefix):]
- data = uri_to_iri(data)
+ data = uri_to_iri(parse.unquote(data))
try:
match = resolve(data)
| diff --git a/tests/test_relations.py b/tests/test_relations.py
--- a/tests/test_relations.py
+++ b/tests/test_relations.py
@@ -153,6 +153,7 @@ def setUp(self):
self.queryset = MockQueryset([
MockObject(pk=1, name='foobar'),
MockObject(pk=2, name='bazABCqux'),
+ MockObject(pk=2, name='bazABC qux'),
])
self.field = serializers.HyperlinkedRelatedField(
view_name='example',
@@ -191,6 +192,10 @@ def test_hyperlinked_related_lookup_url_encoded_exists(self):
instance = self.field.to_internal_value('http://example.org/example/baz%41%42%43qux/')
assert instance is self.queryset.items[1]
+ def test_hyperlinked_related_lookup_url_space_encoded_exists(self):
+ instance = self.field.to_internal_value('http://example.org/example/bazABC%20qux/')
+ assert instance is self.queryset.items[2]
+
def test_hyperlinked_related_lookup_does_not_exist(self):
with pytest.raises(serializers.ValidationError) as excinfo:
self.field.to_internal_value('http://example.org/example/doesnotexist/')
| HyperlinkedRelatedField exception on string with %20 instead of space
Use serializers.HyperlinkedRelatedField where defined lookup_field link to the field string causes an exception 'Invalid hyperlink - Object does not exist.' when the value of that field contains characters that are encoded in the url. eg space -> %20
Missing unquote when try get the value from the url
| Looks legit as https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/generics.py#L96 doesn't unquote the data from url.
I'm rather surprised - I'd have fully expected that percent encoding is handled for you by Django's URL routing. A failing test case here might be a good first pass.
@xordoquy what you linked seems unrelated, as the error mentioned here is most likely raised from:
https://github.com/encode/django-rest-framework/blob/4dd71d68d2227cced7f1215a664343b20da8c804/rest_framework/relations.py#L345
The `view` with custom lookup field doesn't seem to cause any trouble by itself.
So why does `resolve` it work in view, but not in related field?
`'%20'` in `path` gets unquoted quite early on, already in WSGI server (or django test client). This is seems not exactly well defined part of WSGI, so some servers may not unquote this, but django builtin server does, and so is `uwsgi` and few others. Anyway, this is just explanation why it does seem to work when working with `path` from taken `request` object.
In related field we deal with user provided `data`, which is not parsed by any magical WSGI implementation. So I think we should call `uri_to_iri` (just like django test server) on `urlparse.urlparse(data).path`.
@tomchristie @rooterkyberian @xordoquy it seems to be broken again since the Django's `uri_to_iri()` function has changed in Django2.0+
See what they've changed: https://github.com/django/django/commit/03281d8fe7a32f580a85235659d4fbb143eeb867#diff-d3fe562051dcbab80f60f067fa6a5838R180
I.e. now, `%20` stays in the URL as opposed to how it worked before. Therefore, HyperlinkedRelatedField doesn't work with hyperlinks containing spaces`%20` and returns "Object does not exist".
And the unit test in DRF passes because here https://github.com/encode/django-rest-framework/pull/5179 it doesn't cover the %20 case. Thus, HyperlinkedRelatedField appear to be not fully compatible with Django 2.0+
Thanks @hexvolt.
@rpkilby if you don't mind, can you include this on 3.11.x milestone? the milestone tag seems wrong | 2019-11-18T15:00:25 |
encode/django-rest-framework | 7,083 | encode__django-rest-framework-7083 | [
"7078"
] | ebcd93163a5d0663d16a16d4691df1bbe965d42f | diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py
--- a/rest_framework/__init__.py
+++ b/rest_framework/__init__.py
@@ -8,7 +8,7 @@
"""
__title__ = 'Django REST framework'
-__version__ = '3.10.3'
+__version__ = '3.11.0'
__author__ = 'Tom Christie'
__license__ = 'BSD 3-Clause'
__copyright__ = 'Copyright 2011-2019 Encode OSS Ltd'
diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py
--- a/rest_framework/renderers.py
+++ b/rest_framework/renderers.py
@@ -16,7 +16,6 @@
from django.core.paginator import Page
from django.http.multipartparser import parse_header
from django.template import engines, loader
-from django.test.client import encode_multipart
from django.urls import NoReverseMatch
from django.utils.html import mark_safe
@@ -902,6 +901,8 @@ class MultiPartRenderer(BaseRenderer):
BOUNDARY = 'BoUnDaRyStRiNg'
def render(self, data, accepted_media_type=None, renderer_context=None):
+ from django.test.client import encode_multipart
+
if hasattr(data, 'items'):
for key, value in data.items():
assert not isinstance(value, dict), (
| _DeadlockError on import of django.test.signals
Hey y'all, I've been intermittently receiving an error that looks like this:
``` File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File ".../venv/lib/python3.7/site-packages/rest_framework/templatetags/rest_framework.py", line 12, in <module>
from rest_framework.renderers import HTMLFormRenderer
File ".../venv/lib/python3.7/site-packages/rest_framework/renderers.py", line 19, in <module>
from django.test.client import encode_multipart
File ".../venv/lib/python3.7/site-packages/django/test/client.py", line 23, in <module>
from django.test import signals
File "<frozen importlib._bootstrap>", line 980, in _find_and_load
File "<frozen importlib._bootstrap>", line 149, in __enter__
File "<frozen importlib._bootstrap>", line 94, in acquire
_frozen_importlib._DeadlockError: deadlock detected by _ModuleLock('django.test.signals') at 4512885264
```
(Ignore the `...` just removing user paths for privacy)
I've tried for awhile to build a test case to make this easier to track down but was unsuccessful. I was able though to successfully make this go away. [Here](https://github.com/encode/django-rest-framework/blob/90eaf51839e2bfc3ca897d1f87028ca3303aa097/rest_framework/renderers.py#L913) it seems that the `django.test.client.encode_multipart` function is being used within `renderers.MultiPartRenderer`.
Now re-using code seems fine to me, but I'm a bit hesitant to say that using code designed purely for testing purposes is something that should be done within production code. I've confirmed that copying that function and moving it elsewhere fixes this issue for me (and I've found that I'm not necessarily the only one suffering from this issue as seen [here](https://stackoverflow.com/questions/56372727/deadlockerror-in-django-while-starting-server).
Looking at your contribution guide I know it says to talk about the expected behavior rather than code, but it seemed unavoidable to me to make this about the code causing the problem. Would anyone have any suggestions for getting this fixed seeing as it seems kind of tough to reproduce? As an outsider of this project I'd say though that not relying on a function designed for use in testing would be optimal.
I am running django-channels 2.2.0 with Django 2.2.5 at the moment if that helps narrow it down. I mention this because django-channels does replace the default runserver command with its own.
| Hi,
Thanks for your detailed report.
It looks a lot like https://code.djangoproject.com/ticket/30921 or https://code.djangoproject.com/ticket/30352 which seem to be an issue Django related.
Hi, I know I didn't follow the contribution guide to a T, but would it be possible to have more of a discussion around this? Even if it is an issue with Django, wouldn't mitigating the problem for users of DRF be worth looking into? If this simply isn't possible I'll drop the issue. I'm only concerned for the experience of users of DRF as the error this problem induces is kind of hard to track down and can be frustrating when debugging as you have to keep restarting the debug server.
The recommended fix I saw in those threads of removing .pyc files doesn't even work for me. The only fix that works (at least for me through empirical testing) is removing the dependency on `django.test.client.encode_multipart` from the renderers.py file and importing the function from somewhere else (in my testing I simply in-lined the function inside the renderers.py file).
What if [that import](https://github.com/encode/django-rest-framework/blob/master/rest_framework/renderers.py#L19) was moved inside [this function](https://github.com/encode/django-rest-framework/blob/master/rest_framework/renderers.py#L904) ?
Does the issue still happen after that ?
Moving the import inside the function that it's used in does seem to fix the issue as well.
> Hi, I know I didn't follow the contribution guide to a T
Just a note - I assume Tom closed the issue assuming it's an upstream Django bug. Bug reports aren't closed just because they don't precisely follow the contribution guide.
If you can't provide a test case, can you provide an example failing project? | 2019-12-10T11:16:15 |
|
encode/django-rest-framework | 7,086 | encode__django-rest-framework-7086 | [
"7003"
] | de9f1d56c45557638725bc18733387beac27ad1e | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -448,7 +448,7 @@ def _read_only_defaults(self):
default = field.get_default()
except SkipField:
continue
- defaults[field.field_name] = default
+ defaults[field.source] = default
return defaults
diff --git a/rest_framework/validators.py b/rest_framework/validators.py
--- a/rest_framework/validators.py
+++ b/rest_framework/validators.py
@@ -106,7 +106,7 @@ def enforce_required_fields(self, attrs, serializer):
missing_items = {
field_name: self.missing_message
for field_name in self.fields
- if field_name not in attrs
+ if serializer.fields[field_name].source not in attrs
}
if missing_items:
raise ValidationError(missing_items, code='required')
@@ -115,17 +115,23 @@ def filter_queryset(self, attrs, queryset, serializer):
"""
Filter the queryset to all instances matching the given attributes.
"""
+ # field names => field sources
+ sources = [
+ serializer.fields[field_name].source
+ for field_name in self.fields
+ ]
+
# If this is an update, then any unprovided field should
# have it's value set based on the existing instance attribute.
if serializer.instance is not None:
- for field_name in self.fields:
- if field_name not in attrs:
- attrs[field_name] = getattr(serializer.instance, field_name)
+ for source in sources:
+ if source not in attrs:
+ attrs[source] = getattr(serializer.instance, source)
# Determine the filter keyword arguments and filter the queryset.
filter_kwargs = {
- field_name: attrs[field_name]
- for field_name in self.fields
+ source: attrs[source]
+ for source in sources
}
return qs_filter(queryset, **filter_kwargs)
| diff --git a/tests/test_validators.py b/tests/test_validators.py
--- a/tests/test_validators.py
+++ b/tests/test_validators.py
@@ -301,6 +301,49 @@ class Meta:
]
}
+ def test_read_only_fields_with_default_and_source(self):
+ class ReadOnlySerializer(serializers.ModelSerializer):
+ name = serializers.CharField(source='race_name', default='test', read_only=True)
+
+ class Meta:
+ model = UniquenessTogetherModel
+ fields = ['name', 'position']
+ validators = [
+ UniqueTogetherValidator(
+ queryset=UniquenessTogetherModel.objects.all(),
+ fields=['name', 'position']
+ )
+ ]
+
+ serializer = ReadOnlySerializer(data={'position': 1})
+ assert serializer.is_valid(raise_exception=True)
+
+ def test_writeable_fields_with_source(self):
+ class WriteableSerializer(serializers.ModelSerializer):
+ name = serializers.CharField(source='race_name')
+
+ class Meta:
+ model = UniquenessTogetherModel
+ fields = ['name', 'position']
+ validators = [
+ UniqueTogetherValidator(
+ queryset=UniquenessTogetherModel.objects.all(),
+ fields=['name', 'position']
+ )
+ ]
+
+ serializer = WriteableSerializer(data={'name': 'test', 'position': 1})
+ assert serializer.is_valid(raise_exception=True)
+
+ # Validation error should use seriazlier field name, not source
+ serializer = WriteableSerializer(data={'position': 1})
+ assert not serializer.is_valid()
+ assert serializer.errors == {
+ 'name': [
+ 'This field is required.'
+ ]
+ }
+
def test_allow_explict_override(self):
"""
Ensure validators can be explicitly removed..
@@ -357,13 +400,9 @@ class MockQueryset:
def filter(self, **kwargs):
self.called_with = kwargs
- class MockSerializer:
- def __init__(self, instance):
- self.instance = instance
-
data = {'race_name': 'bar'}
queryset = MockQueryset()
- serializer = MockSerializer(instance=self.instance)
+ serializer = UniquenessTogetherSerializer(instance=self.instance)
validator = UniqueTogetherValidator(queryset, fields=('race_name',
'position'))
validator.filter_queryset(attrs=data, queryset=queryset, serializer=serializer)
| UniqueTogetherValidator is incompatible with field source
The `UniqueTogetherValidator` is incompatible with serializer fields where the serializer field name is different than the underlying model field name. i.e., fields that have a `source` specified.
This manifests itself in two ways:
- For writeable fields, the validator raises a `required` validation error.
- For read-only fields that have a default value, this passes through to the ORM and ultimately raises a `django.core.exceptions.FieldError`.
<details>
<summary><b>Example setup</b></summary>
```python
from django.db import models
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from django.test import TestCase
class ExampleModel(models.Model):
field1 = models.CharField(max_length=60)
field2 = models.CharField(max_length=60)
class Meta:
unique_together = ['field1', 'field2']
class WriteableExample(serializers.ModelSerializer):
alias = serializers.CharField(source='field1')
class Meta:
model = ExampleModel
fields = ['alias', 'field2']
validators = [
UniqueTogetherValidator(
queryset=ExampleModel.objects.all(),
fields=['alias', 'field2']
)
]
class ReadOnlyExample(serializers.ModelSerializer):
alias = serializers.CharField(source='field1', default='test', read_only=True)
class Meta:
model = ExampleModel
fields = ['alias', 'field2']
validators = [
UniqueTogetherValidator(
queryset=ExampleModel.objects.all(),
fields=['alias', 'field2']
)
]
class ExampleTests(TestCase):
def test_writeable(self):
serializer = WriteableExample(data={'alias': 'test', 'field2': 'test'})
serializer.is_valid(raise_exception=True)
def test_read_only(self):
serializer = ReadOnlyExample(data={'field2': 'test'})
serializer.is_valid(raise_exception=True)
```
</details>
<details>
<summary><b>Test output</b></summary>
```
==================================================== FAILURES =====================================================
___________________________________________ ExampleTests.test_read_only ___________________________________________
tests/test_unique_together_example.py:52: in test_read_only
serializer.is_valid(raise_exception=True)
rest_framework/serializers.py:234: in is_valid
self._validated_data = self.run_validation(self.initial_data)
rest_framework/serializers.py:431: in run_validation
self.run_validators(value)
rest_framework/serializers.py:464: in run_validators
super().run_validators(to_validate)
rest_framework/fields.py:557: in run_validators
validator(value)
rest_framework/validators.py:157: in __call__
queryset = self.filter_queryset(attrs, queryset)
rest_framework/validators.py:143: in filter_queryset
return qs_filter(queryset, **filter_kwargs)
rest_framework/validators.py:28: in qs_filter
return queryset.filter(**kwargs)
.tox/venvs/py37-django22/lib/python3.7/site-packages/django/db/models/query.py:892: in filter
return self._filter_or_exclude(False, *args, **kwargs)
.tox/venvs/py37-django22/lib/python3.7/site-packages/django/db/models/query.py:910: in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
.tox/venvs/py37-django22/lib/python3.7/site-packages/django/db/models/sql/query.py:1290: in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
.tox/venvs/py37-django22/lib/python3.7/site-packages/django/db/models/sql/query.py:1318: in _add_q
split_subq=split_subq, simple_col=simple_col,
.tox/venvs/py37-django22/lib/python3.7/site-packages/django/db/models/sql/query.py:1190: in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
.tox/venvs/py37-django22/lib/python3.7/site-packages/django/db/models/sql/query.py:1049: in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
.tox/venvs/py37-django22/lib/python3.7/site-packages/django/db/models/sql/query.py:1420: in names_to_path
"Choices are: %s" % (name, ", ".join(available)))
E django.core.exceptions.FieldError: Cannot resolve keyword 'alias' into field. Choices are: field1, field2, id
___________________________________________ ExampleTests.test_writeable ___________________________________________
tests/test_unique_together_example.py:48: in test_writeable
serializer.is_valid(raise_exception=True)
rest_framework/serializers.py:242: in is_valid
raise ValidationError(self.errors)
E rest_framework.exceptions.ValidationError: {'alias': [ErrorDetail(string='This field is required.', code='required')]}
```
</details>
----
<details>
<summary><b>Original Description</b></summary>
## Checklist
- [+] I have verified that that issue exists against the `master` branch of Django REST framework.
- [+] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [+] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [+] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [+] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
according to the changes in drf 3.8.2 the read_only+default fields should be explicilty saved in perform_create of viewset or create, save or update method of serializer.
this perform_create is called after validating the data by `serializer.is_valid()` inside create method of CreateModelMixin
```
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
```
now in my codebase i had two cases:
case1 : when the name of field of serializer is same as model like:
model:
```
class A(models.Model):
a = models.ForeignKey(B, on_delete=models.CASCADE)
c = models.CharField(max_length=32)
....
```
serializer:
```
class SomeSerializer(serializers.ModelSerializer):
a = HyperlinkedRelatedField(view_name='c-detail', read_only=True, default=<some instance of Model B>)
class Meta:
model=A
fields=( 'a', 'c', ......)
validators = [
UniqueTogetherValidator(
queryset=A.objects.all(),
fields=('a', 'c')
)
]
```
In this case serializer.is_valid() is not failing if i POST something to this serializer and my overwritten perform_create is being called so problem here
because as we can see these fields are included in _read_only_defaults after https://github.com/encode/django-rest-framework/pull/5922 and here https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L451 the field.field_name is added in the return value that will be validated with uniquetogether so no issues come.
case 2: when the name of field of serializer is 'not' same as model's field and a source is added in the serializer field like:
model:
```
class A(models.Model):
a = models.ForeignKey(B, on_delete=models.CASCADE)
c = models.CharField(max_length=32)
....
```
serializer:
```
class SomeSerializer(serializers.ModelSerializer):
b = HyperlinkedRelatedField(source='a', view_name='c-detail', read_only=True, default=<some instance of Model B>)
class Meta:
model=A
fields=( 'b', 'c', ......)
validators = [
UniqueTogetherValidator(
queryset=A.objects.all(),
fields=('a', 'c')
)
]
```
in this case, if i POST something to this serializer, a ValidationError exception is thrown
saying
`{'a': [ErrorDetail(string='This field is required.', code='required')]}`
because since field.field_name is included in the return ordered dictionary as key so here in the unique together will fail as it expects ('a', 'c') but gets ('b', 'c').
## Expected behavior
in second case also it should work fine
## Actual behavior
throwing error `{'a': [ErrorDetail(string='This field is required.', code='required')]}`
## Possible source of error found
Since all the fields (including read_only) were earlier present in _wriable_fields, this is the place where it used to get the field name from source - https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L496
And since it started using the method _read_only_defaults for these read_only+default fields, it populates using field name rather than source name - https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L451
which maybe a bug
</details>
| Hi @anveshagarwal. After looking at your PR, I've updated the issue description. Note that the bug is not limited to read-only fields, however the writeable and read-only cases raise different errors.
@rpkilby So ideally uniquetogether validator in serializer should take the name of the field declared in serializer, not the name of the source? But till now it was taking the name of the source or field in the model.
> uniquetogether validator in serializer should take the name of the field declared in serializer, not the name of the source?
Yes, per the [`UniqueTogetherValidator` docs](https://www.django-rest-framework.org/api-guide/validators/#uniquetogethervalidator):
> * `fields` _required_ - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.
Thanks for sharing the docs. | 2019-12-11T12:35:58 |
encode/django-rest-framework | 7,098 | encode__django-rest-framework-7098 | [
"7097"
] | 0d2bbd317743f2459ccdf2bd750edb0c10261eaf | diff --git a/rest_framework/viewsets.py b/rest_framework/viewsets.py
--- a/rest_framework/viewsets.py
+++ b/rest_framework/viewsets.py
@@ -33,6 +33,15 @@ def _is_extra_action(attr):
return hasattr(attr, 'mapping') and isinstance(attr.mapping, MethodMapper)
+def _check_attr_name(func, name):
+ assert func.__name__ == name, (
+ 'Expected function (`{func.__name__}`) to match its attribute name '
+ '(`{name}`). If using a decorator, ensure the inner function is '
+ 'decorated with `functools.wraps`, or that `{func.__name__}.__name__` '
+ 'is otherwise set to `{name}`.').format(func=func, name=name)
+ return func
+
+
class ViewSetMixin:
"""
This is the magic.
@@ -164,7 +173,9 @@ def get_extra_actions(cls):
"""
Get the methods that are marked as an extra ViewSet `@action`.
"""
- return [method for _, method in getmembers(cls, _is_extra_action)]
+ return [_check_attr_name(method, name)
+ for name, method
+ in getmembers(cls, _is_extra_action)]
def get_extra_action_url_map(self):
"""
| diff --git a/tests/test_viewsets.py b/tests/test_viewsets.py
--- a/tests/test_viewsets.py
+++ b/tests/test_viewsets.py
@@ -1,4 +1,5 @@
from collections import OrderedDict
+from functools import wraps
import pytest
from django.conf.urls import include, url
@@ -33,6 +34,13 @@ class Action(models.Model):
pass
+def decorate(fn):
+ @wraps(fn)
+ def wrapper(self, request, *args, **kwargs):
+ return fn(self, request, *args, **kwargs)
+ return wrapper
+
+
class ActionViewSet(GenericViewSet):
queryset = Action.objects.all()
@@ -68,6 +76,16 @@ def custom_detail_action(self, request, *args, **kwargs):
def unresolvable_detail_action(self, request, *args, **kwargs):
raise NotImplementedError
+ @action(detail=False)
+ @decorate
+ def wrapped_list_action(self, request, *args, **kwargs):
+ raise NotImplementedError
+
+ @action(detail=True)
+ @decorate
+ def wrapped_detail_action(self, request, *args, **kwargs):
+ raise NotImplementedError
+
class ActionNamesViewSet(GenericViewSet):
@@ -191,6 +209,8 @@ def test_extra_actions(self):
'detail_action',
'list_action',
'unresolvable_detail_action',
+ 'wrapped_detail_action',
+ 'wrapped_list_action',
]
self.assertEqual(actual, expected)
@@ -204,9 +224,35 @@ def test_should_only_return_decorated_methods(self):
'detail_action',
'list_action',
'unresolvable_detail_action',
+ 'wrapped_detail_action',
+ 'wrapped_list_action',
]
self.assertEqual(actual, expected)
+ def test_attr_name_check(self):
+ def decorate(fn):
+ def wrapper(self, request, *args, **kwargs):
+ return fn(self, request, *args, **kwargs)
+ return wrapper
+
+ class ActionViewSet(GenericViewSet):
+ queryset = Action.objects.all()
+
+ @action(detail=False)
+ @decorate
+ def wrapped_list_action(self, request, *args, **kwargs):
+ raise NotImplementedError
+
+ view = ActionViewSet()
+ with pytest.raises(AssertionError) as excinfo:
+ view.get_extra_actions()
+
+ assert str(excinfo.value) == (
+ 'Expected function (`wrapper`) to match its attribute name '
+ '(`wrapped_list_action`). If using a decorator, ensure the inner '
+ 'function is decorated with `functools.wraps`, or that '
+ '`wrapper.__name__` is otherwise set to `wrapped_list_action`.')
+
@override_settings(ROOT_URLCONF='tests.test_viewsets')
class GetExtraActionUrlMapTests(TestCase):
@@ -218,6 +264,7 @@ def test_list_view(self):
expected = OrderedDict([
('Custom list action', 'http://testserver/api/actions/custom_list_action/'),
('List action', 'http://testserver/api/actions/list_action/'),
+ ('Wrapped list action', 'http://testserver/api/actions/wrapped_list_action/'),
])
self.assertEqual(view.get_extra_action_url_map(), expected)
@@ -229,6 +276,7 @@ def test_detail_view(self):
expected = OrderedDict([
('Custom detail action', 'http://testserver/api/actions/1/custom_detail_action/'),
('Detail action', 'http://testserver/api/actions/1/detail_action/'),
+ ('Wrapped detail action', 'http://testserver/api/actions/1/wrapped_detail_action/'),
# "Unresolvable detail action" excluded, since it's not resolvable
])
| use list_route add multiple decorate => 405 error
## Steps to reproduce
I use list_route, add multiple decorate
```
def audit_log():
def _log_record(func):
def record(self, request, *args, **kwargs):
print("enter$$$$$$$$$")
res = func(self, request, *args, **kwargs)
return res
return record
return _log_record
class HostInfoViewSet(ModelViewSet):
@list_route(methods=['post'], url_path='valid')
@audit_log()
def get_valid_snooze(self, request, *args, **kwargs):
print('@@@@@@@TEST')
return Response("@@@@@@@TEST")
```
## Expected behavior
old version:
django==2.0.4
djangorestframework==3.7.*


## Actual behavior
new version:
Django==2.2.5
djangorestframework==3.9.4
occur 405 error

| 2019-12-20T22:29:56 |
|
encode/django-rest-framework | 7,105 | encode__django-rest-framework-7105 | [
"6858"
] | d985c7cbb999b2bc18a109249c583e91f4c27aec | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -393,7 +393,7 @@ def _map_serializer(self, serializer):
schema['writeOnly'] = True
if field.allow_null:
schema['nullable'] = True
- if field.default and field.default != empty: # why don't they use None?!
+ if field.default and field.default != empty and not callable(field.default): # why don't they use None?!
schema['default'] = field.default
if field.help_text:
schema['description'] = str(field.help_text)
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -571,6 +571,22 @@ def test_serializer_hstorefield(self):
properties = response_schema['items']['properties']
assert properties['hstore']['type'] == 'object'
+ def test_serializer_callable_default(self):
+ path = '/'
+ method = 'GET'
+ view = create_view(
+ views.ExampleGenericAPIView,
+ method,
+ create_request(path),
+ )
+ inspector = AutoSchema()
+ inspector.view = view
+
+ responses = inspector._get_responses(path, method)
+ response_schema = responses['200']['content']['application/json']['schema']
+ properties = response_schema['items']['properties']
+ assert 'default' not in properties['uuid_field']
+
def test_serializer_validators(self):
path = '/'
method = 'GET'
diff --git a/tests/schemas/views.py b/tests/schemas/views.py
--- a/tests/schemas/views.py
+++ b/tests/schemas/views.py
@@ -58,6 +58,7 @@ class ExampleSerializer(serializers.Serializer):
date = serializers.DateField()
datetime = serializers.DateTimeField()
hstore = serializers.HStoreField()
+ uuid_field = serializers.UUIDField(default=uuid.uuid4)
class ExampleGenericAPIView(generics.GenericAPIView):
| OpenAPI schema generation does not handle callable defaults
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
On any serializer used by a GenericAPIView, set the default for a field to any callable.
``` python
class OhNoSerializer(serializers.Serializer):
something = serializers.FloatField(default=float)
class OhNoAPIView(CreateAPIView):
serializer_class = OhNoSerializer
...
```
## Expected behavior
Output of `./manage.py generateschema`:
``` yaml
paths:
/api/oh/no:
post:
operationId: CreateOhNo
parameters: []
requestBody:
content:
application/json:
schema:
required:
- something
properties:
something:
type: number
default: 0.0
```
## Actual behavior
With `./manage.py generateschema`:
``` yaml
paths:
/api/oh/no:
post:
operationId: CreateOhNo
parameters: []
requestBody:
content:
application/json:
schema:
required:
- something
properties:
something:
type: number
default: !!python/name:builtins.float ''
```
With `./manage.py generateschema --format openapi-json`:
```
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/lucidiot/.virtualenvs/drf/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/lucidiot/.virtualenvs/drf/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/lucidiot/.virtualenvs/drf/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/lucidiot/.virtualenvs/drf/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/home/lucidiot/dev/django-rest-framework/rest_framework/management/commands/generateschema.py", line 42, in handle
output = renderer.render(schema, renderer_context={})
File "/home/lucidiot/dev/django-rest-framework/rest_framework/renderers.py", line 1064, in render
return json.dumps(data, indent=2).encode('utf-8')
File "/home/lucidiot/dev/django-rest-framework/rest_framework/utils/json.py", line 25, in dumps
return json.dumps(*args, **kwargs)
File "/usr/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/usr/lib/python3.6/json/encoder.py", line 201, in encode
chunks = list(chunks)
File "/usr/lib/python3.6/json/encoder.py", line 430, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "/usr/lib/python3.6/json/encoder.py", line 404, in _iterencode_dict
yield from chunks
File "/usr/lib/python3.6/json/encoder.py", line 404, in _iterencode_dict
yield from chunks
File "/usr/lib/python3.6/json/encoder.py", line 404, in _iterencode_dict
yield from chunks
[Previous line repeated 7 more times]
File "/usr/lib/python3.6/json/encoder.py", line 437, in _iterencode
o = _default(o)
File "/usr/lib/python3.6/json/encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'type' is not JSON serializable
```
--------------
How to handle defaults that depend on the request, like `CurrentUserDefault`, or user-defined defaults that can depend on *anything* ?
| This also happens if you use some TimeField or any other non-JSON serializable field, but I think it could be easily avoidable if the DjangoJSONEncoder class is used at https://github.com/encode/django-rest-framework/blob/a73d3c309f0736f46dd46c99e15e1102af26dacb/rest_framework/renderers.py#L1064
```python
from django.core.serializers.json import DjangoJSONEncoder
return json.dumps(data, indent=2, cls=DjangoJSONEncoder).encode('utf-8')
``` | 2019-12-25T08:32:32 |
encode/django-rest-framework | 7,124 | encode__django-rest-framework-7124 | [
"6984"
] | 797518af6d996308781e283601057ff82ed8684c | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -1,3 +1,4 @@
+import re
import warnings
from collections import OrderedDict
from decimal import Decimal
@@ -65,9 +66,9 @@ def get_schema(self, request=None, public=False):
Generate a OpenAPI schema.
"""
self._initialise_endpoints()
+ components_schemas = {}
# Iterate endpoints generating per method path operations.
- # TODO: …and reference components.
paths = {}
_, view_endpoints = self._get_paths_and_endpoints(None if public else request)
for path, method, view in view_endpoints:
@@ -75,6 +76,16 @@ def get_schema(self, request=None, public=False):
continue
operation = view.schema.get_operation(path, method)
+ components = view.schema.get_components(path, method)
+ for k in components.keys():
+ if k not in components_schemas:
+ continue
+ if components_schemas[k] == components[k]:
+ continue
+ warnings.warn('Schema component "{}" has been overriden with a different value.'.format(k))
+
+ components_schemas.update(components)
+
# Normalise path for any provided mount url.
if path.startswith('/'):
path = path[1:]
@@ -92,6 +103,11 @@ def get_schema(self, request=None, public=False):
'paths': paths,
}
+ if len(components_schemas) > 0:
+ schema['components'] = {
+ 'schemas': components_schemas
+ }
+
return schema
# View Inspectors
@@ -99,14 +115,16 @@ def get_schema(self, request=None, public=False):
class AutoSchema(ViewInspector):
- def __init__(self, operation_id_base=None, tags=None):
+ def __init__(self, tags=None, operation_id_base=None, component_name=None):
"""
:param operation_id_base: user-defined name in operationId. If empty, it will be deducted from the Model/Serializer/View name.
+ :param component_name: user-defined component's name. If empty, it will be deducted from the Serializer's class name.
"""
if tags and not all(isinstance(tag, str) for tag in tags):
raise ValueError('tags must be a list or tuple of string.')
self._tags = tags
self.operation_id_base = operation_id_base
+ self.component_name = component_name
super().__init__()
request_media_types = []
@@ -140,6 +158,43 @@ def get_operation(self, path, method):
return operation
+ def get_component_name(self, serializer):
+ """
+ Compute the component's name from the serializer.
+ Raise an exception if the serializer's class name is "Serializer" (case-insensitive).
+ """
+ if self.component_name is not None:
+ return self.component_name
+
+ # use the serializer's class name as the component name.
+ component_name = serializer.__class__.__name__
+ # We remove the "serializer" string from the class name.
+ pattern = re.compile("serializer", re.IGNORECASE)
+ component_name = pattern.sub("", component_name)
+
+ if component_name == "":
+ raise Exception(
+ '"{}" is an invalid class name for schema generation. '
+ 'Serializer\'s class name should be unique and explicit. e.g. "ItemSerializer"'
+ .format(serializer.__class__.__name__)
+ )
+
+ return component_name
+
+ def get_components(self, path, method):
+ """
+ Return components with their properties from the serializer.
+ """
+ serializer = self._get_serializer(path, method)
+
+ if not isinstance(serializer, serializers.Serializer):
+ return {}
+
+ component_name = self.get_component_name(serializer)
+
+ content = self._map_serializer(serializer)
+ return {component_name: content}
+
def get_operation_id_base(self, path, method, action):
"""
Compute the base part for operation ID from the model, serializer or view name.
@@ -434,10 +489,6 @@ def _map_min_max(self, field, content):
def _map_serializer(self, serializer):
# Assuming we have a valid serializer instance.
- # TODO:
- # - field is Nested or List serializer.
- # - Handle read_only/write_only for request/response differences.
- # - could do this with readOnly/writeOnly and then filter dict.
required = []
properties = {}
@@ -542,6 +593,9 @@ def _get_serializer(self, path, method):
.format(view.__class__.__name__, method, path))
return None
+ def _get_reference(self, serializer):
+ return {'$ref': '#/components/schemas/{}'.format(self.get_component_name(serializer))}
+
def _get_request_body(self, path, method):
if method not in ('PUT', 'PATCH', 'POST'):
return {}
@@ -551,20 +605,13 @@ def _get_request_body(self, path, method):
serializer = self._get_serializer(path, method)
if not isinstance(serializer, serializers.Serializer):
- return {}
-
- content = self._map_serializer(serializer)
- # No required fields for PATCH
- if method == 'PATCH':
- content.pop('required', None)
- # No read_only fields for request.
- for name, schema in content['properties'].copy().items():
- if 'readOnly' in schema:
- del content['properties'][name]
+ item_schema = {}
+ else:
+ item_schema = self._get_reference(serializer)
return {
'content': {
- ct: {'schema': content}
+ ct: {'schema': item_schema}
for ct in self.request_media_types
}
}
@@ -580,17 +627,12 @@ def _get_responses(self, path, method):
self.response_media_types = self.map_renderers(path, method)
- item_schema = {}
serializer = self._get_serializer(path, method)
- if isinstance(serializer, serializers.Serializer):
- item_schema = self._map_serializer(serializer)
- # No write_only fields for response.
- for name, schema in item_schema['properties'].copy().items():
- if 'writeOnly' in schema:
- del item_schema['properties'][name]
- if 'required' in item_schema:
- item_schema['required'] = [f for f in item_schema['required'] if f != name]
+ if not isinstance(serializer, serializers.Serializer):
+ item_schema = {}
+ else:
+ item_schema = self._get_reference(serializer)
if is_list_view(path, method, self.view):
response_schema = {
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -85,12 +85,12 @@ def test_list_field_mapping(self):
assert inspector._map_field(field) == mapping
def test_lazy_string_field(self):
- class Serializer(serializers.Serializer):
+ class ItemSerializer(serializers.Serializer):
text = serializers.CharField(help_text=_('lazy string'))
inspector = AutoSchema()
- data = inspector._map_serializer(Serializer())
+ data = inspector._map_serializer(ItemSerializer())
assert isinstance(data['properties']['text']['description'], str), "description must be str"
def test_boolean_default_field(self):
@@ -186,6 +186,33 @@ def test_request_body(self):
path = '/'
method = 'POST'
+ class ItemSerializer(serializers.Serializer):
+ text = serializers.CharField()
+ read_only = serializers.CharField(read_only=True)
+
+ class View(generics.GenericAPIView):
+ serializer_class = ItemSerializer
+
+ view = create_view(
+ View,
+ method,
+ create_request(path)
+ )
+ inspector = AutoSchema()
+ inspector.view = view
+
+ request_body = inspector._get_request_body(path, method)
+ print(request_body)
+ assert request_body['content']['application/json']['schema']['$ref'] == '#/components/schemas/Item'
+
+ components = inspector.get_components(path, method)
+ assert components['Item']['required'] == ['text']
+ assert sorted(list(components['Item']['properties'].keys())) == ['read_only', 'text']
+
+ def test_invalid_serializer_class_name(self):
+ path = '/'
+ method = 'POST'
+
class Serializer(serializers.Serializer):
text = serializers.CharField()
read_only = serializers.CharField(read_only=True)
@@ -201,20 +228,22 @@ class View(generics.GenericAPIView):
inspector = AutoSchema()
inspector.view = view
- request_body = inspector._get_request_body(path, method)
- assert request_body['content']['application/json']['schema']['required'] == ['text']
- assert list(request_body['content']['application/json']['schema']['properties'].keys()) == ['text']
+ serializer = inspector._get_serializer(path, method)
+
+ with pytest.raises(Exception) as exc:
+ inspector.get_component_name(serializer)
+ assert "is an invalid class name for schema generation" in str(exc.value)
def test_empty_required(self):
path = '/'
method = 'POST'
- class Serializer(serializers.Serializer):
+ class ItemSerializer(serializers.Serializer):
read_only = serializers.CharField(read_only=True)
write_only = serializers.CharField(write_only=True, required=False)
class View(generics.GenericAPIView):
- serializer_class = Serializer
+ serializer_class = ItemSerializer
view = create_view(
View,
@@ -224,23 +253,24 @@ class View(generics.GenericAPIView):
inspector = AutoSchema()
inspector.view = view
- request_body = inspector._get_request_body(path, method)
+ components = inspector.get_components(path, method)
+ component = components['Item']
# there should be no empty 'required' property, see #6834
- assert 'required' not in request_body['content']['application/json']['schema']
+ assert 'required' not in component
for response in inspector._get_responses(path, method).values():
- assert 'required' not in response['content']['application/json']['schema']
+ assert 'required' not in component
def test_empty_required_with_patch_method(self):
path = '/'
method = 'PATCH'
- class Serializer(serializers.Serializer):
+ class ItemSerializer(serializers.Serializer):
read_only = serializers.CharField(read_only=True)
write_only = serializers.CharField(write_only=True, required=False)
class View(generics.GenericAPIView):
- serializer_class = Serializer
+ serializer_class = ItemSerializer
view = create_view(
View,
@@ -250,22 +280,23 @@ class View(generics.GenericAPIView):
inspector = AutoSchema()
inspector.view = view
- request_body = inspector._get_request_body(path, method)
+ components = inspector.get_components(path, method)
+ component = components['Item']
# there should be no empty 'required' property, see #6834
- assert 'required' not in request_body['content']['application/json']['schema']
+ assert 'required' not in component
for response in inspector._get_responses(path, method).values():
- assert 'required' not in response['content']['application/json']['schema']
+ assert 'required' not in component
def test_response_body_generation(self):
path = '/'
method = 'POST'
- class Serializer(serializers.Serializer):
+ class ItemSerializer(serializers.Serializer):
text = serializers.CharField()
write_only = serializers.CharField(write_only=True)
class View(generics.GenericAPIView):
- serializer_class = Serializer
+ serializer_class = ItemSerializer
view = create_view(
View,
@@ -276,9 +307,11 @@ class View(generics.GenericAPIView):
inspector.view = view
responses = inspector._get_responses(path, method)
- assert '201' in responses
- assert responses['201']['content']['application/json']['schema']['required'] == ['text']
- assert list(responses['201']['content']['application/json']['schema']['properties'].keys()) == ['text']
+ assert responses['201']['content']['application/json']['schema']['$ref'] == '#/components/schemas/Item'
+
+ components = inspector.get_components(path, method)
+ assert sorted(components['Item']['required']) == ['text', 'write_only']
+ assert sorted(list(components['Item']['properties'].keys())) == ['text', 'write_only']
assert 'description' in responses['201']
def test_response_body_nested_serializer(self):
@@ -288,12 +321,12 @@ def test_response_body_nested_serializer(self):
class NestedSerializer(serializers.Serializer):
number = serializers.IntegerField()
- class Serializer(serializers.Serializer):
+ class ItemSerializer(serializers.Serializer):
text = serializers.CharField()
nested = NestedSerializer()
class View(generics.GenericAPIView):
- serializer_class = Serializer
+ serializer_class = ItemSerializer
view = create_view(
View,
@@ -304,7 +337,11 @@ class View(generics.GenericAPIView):
inspector.view = view
responses = inspector._get_responses(path, method)
- schema = responses['201']['content']['application/json']['schema']
+ assert responses['201']['content']['application/json']['schema']['$ref'] == '#/components/schemas/Item'
+ components = inspector.get_components(path, method)
+ assert components['Item']
+
+ schema = components['Item']
assert sorted(schema['required']) == ['nested', 'text']
assert sorted(list(schema['properties'].keys())) == ['nested', 'text']
assert schema['properties']['nested']['type'] == 'object'
@@ -339,19 +376,25 @@ class View(generics.GenericAPIView):
'schema': {
'type': 'array',
'items': {
- 'type': 'object',
- 'properties': {
- 'text': {
- 'type': 'string',
- },
- },
- 'required': ['text'],
+ '$ref': '#/components/schemas/Item'
},
},
},
},
},
}
+ components = inspector.get_components(path, method)
+ assert components == {
+ 'Item': {
+ 'type': 'object',
+ 'properties': {
+ 'text': {
+ 'type': 'string',
+ },
+ },
+ 'required': ['text'],
+ }
+ }
def test_paginated_list_response_body_generation(self):
"""Test that pagination properties are added for a paginated list view."""
@@ -391,13 +434,7 @@ class View(generics.GenericAPIView):
'item': {
'type': 'array',
'items': {
- 'type': 'object',
- 'properties': {
- 'text': {
- 'type': 'string',
- },
- },
- 'required': ['text'],
+ '$ref': '#/components/schemas/Item'
},
},
},
@@ -405,6 +442,18 @@ class View(generics.GenericAPIView):
},
},
}
+ components = inspector.get_components(path, method)
+ assert components == {
+ 'Item': {
+ 'type': 'object',
+ 'properties': {
+ 'text': {
+ 'type': 'string',
+ },
+ },
+ 'required': ['text'],
+ }
+ }
def test_delete_response_body_generation(self):
"""Test that a view's delete method generates a proper response body schema."""
@@ -508,10 +557,10 @@ class View(generics.CreateAPIView):
inspector = AutoSchema()
inspector.view = view
- request_body = inspector._get_request_body(path, method)
- mp_media = request_body['content']['multipart/form-data']
- attachment = mp_media['schema']['properties']['attachment']
- assert attachment['format'] == 'binary'
+ components = inspector.get_components(path, method)
+ component = components['Item']
+ properties = component['properties']
+ assert properties['attachment']['format'] == 'binary'
def test_retrieve_response_body_generation(self):
"""
@@ -551,19 +600,26 @@ class View(generics.GenericAPIView):
'content': {
'application/json': {
'schema': {
- 'type': 'object',
- 'properties': {
- 'text': {
- 'type': 'string',
- },
- },
- 'required': ['text'],
+ '$ref': '#/components/schemas/Item'
},
},
},
},
}
+ components = inspector.get_components(path, method)
+ assert components == {
+ 'Item': {
+ 'type': 'object',
+ 'properties': {
+ 'text': {
+ 'type': 'string',
+ },
+ },
+ 'required': ['text'],
+ }
+ }
+
def test_operation_id_generation(self):
path = '/'
method = 'GET'
@@ -689,9 +745,9 @@ def test_serializer_datefield(self):
inspector = AutoSchema()
inspector.view = view
- responses = inspector._get_responses(path, method)
- response_schema = responses['200']['content']['application/json']['schema']
- properties = response_schema['items']['properties']
+ components = inspector.get_components(path, method)
+ component = components['Example']
+ properties = component['properties']
assert properties['date']['type'] == properties['datetime']['type'] == 'string'
assert properties['date']['format'] == 'date'
assert properties['datetime']['format'] == 'date-time'
@@ -707,9 +763,9 @@ def test_serializer_hstorefield(self):
inspector = AutoSchema()
inspector.view = view
- responses = inspector._get_responses(path, method)
- response_schema = responses['200']['content']['application/json']['schema']
- properties = response_schema['items']['properties']
+ components = inspector.get_components(path, method)
+ component = components['Example']
+ properties = component['properties']
assert properties['hstore']['type'] == 'object'
def test_serializer_callable_default(self):
@@ -723,9 +779,9 @@ def test_serializer_callable_default(self):
inspector = AutoSchema()
inspector.view = view
- responses = inspector._get_responses(path, method)
- response_schema = responses['200']['content']['application/json']['schema']
- properties = response_schema['items']['properties']
+ components = inspector.get_components(path, method)
+ component = components['Example']
+ properties = component['properties']
assert 'default' not in properties['uuid_field']
def test_serializer_validators(self):
@@ -739,9 +795,9 @@ def test_serializer_validators(self):
inspector = AutoSchema()
inspector.view = view
- responses = inspector._get_responses(path, method)
- response_schema = responses['200']['content']['application/json']['schema']
- properties = response_schema['items']['properties']
+ components = inspector.get_components(path, method)
+ component = components['ExampleValidated']
+ properties = component['properties']
assert properties['integer']['type'] == 'integer'
assert properties['integer']['maximum'] == 99
@@ -819,6 +875,7 @@ class ExampleStringTagsViewSet(views.ExampleGenericViewSet):
def test_auto_generated_apiview_tags(self):
class RestaurantAPIView(views.ExampleGenericAPIView):
+ schema = AutoSchema(operation_id_base="restaurant")
pass
class BranchAPIView(views.ExampleGenericAPIView):
@@ -932,3 +989,54 @@ def test_schema_information_empty(self):
assert schema['info']['title'] == ''
assert schema['info']['version'] == ''
+
+ def test_serializer_model(self):
+ """Construction of the top level dictionary."""
+ patterns = [
+ url(r'^example/?$', views.ExampleGenericAPIViewModel.as_view()),
+ ]
+ generator = SchemaGenerator(patterns=patterns)
+
+ request = create_request('/')
+ schema = generator.get_schema(request=request)
+
+ print(schema)
+ assert 'components' in schema
+ assert 'schemas' in schema['components']
+ assert 'ExampleModel' in schema['components']['schemas']
+
+ def test_component_name(self):
+ patterns = [
+ url(r'^example/?$', views.ExampleAutoSchemaComponentName.as_view()),
+ ]
+
+ generator = SchemaGenerator(patterns=patterns)
+
+ request = create_request('/')
+ schema = generator.get_schema(request=request)
+
+ print(schema)
+ assert 'components' in schema
+ assert 'schemas' in schema['components']
+ assert 'Ulysses' in schema['components']['schemas']
+
+ def test_duplicate_component_name(self):
+ patterns = [
+ url(r'^duplicate1/?$', views.ExampleAutoSchemaDuplicate1.as_view()),
+ url(r'^duplicate2/?$', views.ExampleAutoSchemaDuplicate2.as_view()),
+ ]
+
+ generator = SchemaGenerator(patterns=patterns)
+ request = create_request('/')
+
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter('always')
+ schema = generator.get_schema(request=request)
+
+ assert len(w) == 1
+ assert issubclass(w[-1].category, UserWarning)
+ assert 'has been overriden with a different value.' in str(w[-1].message)
+
+ assert 'components' in schema
+ assert 'schemas' in schema['components']
+ assert 'Duplicate' in schema['components']['schemas']
diff --git a/tests/schemas/views.py b/tests/schemas/views.py
--- a/tests/schemas/views.py
+++ b/tests/schemas/views.py
@@ -9,6 +9,7 @@
from rest_framework import generics, permissions, serializers
from rest_framework.decorators import action
from rest_framework.response import Response
+from rest_framework.schemas.openapi import AutoSchema
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
@@ -167,3 +168,50 @@ class ExampleOperationIdDuplicate2(generics.GenericAPIView):
def get(self, *args, **kwargs):
pass
+
+
+class ExampleGenericAPIViewModel(generics.GenericAPIView):
+ serializer_class = ExampleSerializerModel
+
+ def get(self, *args, **kwargs):
+ from datetime import datetime
+ now = datetime.now()
+
+ serializer = self.get_serializer(data=now.date(), datetime=now)
+ return Response(serializer.data)
+
+
+class ExampleAutoSchemaComponentName(generics.GenericAPIView):
+ serializer_class = ExampleSerializerModel
+ schema = AutoSchema(component_name="Ulysses")
+
+ def get(self, *args, **kwargs):
+ from datetime import datetime
+ now = datetime.now()
+
+ serializer = self.get_serializer(data=now.date(), datetime=now)
+ return Response(serializer.data)
+
+
+class ExampleAutoSchemaDuplicate1(generics.GenericAPIView):
+ serializer_class = ExampleValidatedSerializer
+ schema = AutoSchema(component_name="Duplicate")
+
+ def get(self, *args, **kwargs):
+ from datetime import datetime
+ now = datetime.now()
+
+ serializer = self.get_serializer(data=now.date(), datetime=now)
+ return Response(serializer.data)
+
+
+class ExampleAutoSchemaDuplicate2(generics.GenericAPIView):
+ serializer_class = ExampleSerializerModel
+ schema = AutoSchema(component_name="Duplicate")
+
+ def get(self, *args, **kwargs):
+ from datetime import datetime
+ now = datetime.now()
+
+ serializer = self.get_serializer(data=now.date(), datetime=now)
+ return Response(serializer.data)
| OpenAPI 3.0 should generate and reference #/components/schemas/
## Checklist
- [X ] I have verified that that issue exists against the `master` branch of Django REST framework.
- [X ] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [X ] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [X ] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [ X] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Swagger 2.0 supports the concept of a definition #/definitions/{ModelName}. This is superseded in OpenAPI 3.0 with #/components/schemas/{ModelName}
## Expected behavior
1. OpenAPI 3.0 output should contain #/components/schemas/{ModelName}
2. Each schemas should minimally contain the same type of information found in Swagger 2.0 definitions.
3. Optionally, #/paths/... can reference #/components/schemas/{ModelName} rather than a full definition
4. #/components/schemas/{ModelName} should include "title" and format="uri"
## Actual behavior
1. #/components/schemas is not generated.
2. Information has to be scoured from the #/paths/...
3. Some Information found in Swagger 2.0 definitions such as string format information is not present in any equivalent form.
4. Information in i.e. #/paths.../properties/schemas is often duplicated (bigger schema file)
| Yes. This would be a great a addition. A super contributing opportunity!
Is the following considered a supported DRF use case?
Use Case: Javascript client using drf-yasg generated Swagger 2.0, utilizing #/definitions to define client side object, migrates to drf generated OpenAPI3.0.
Not "supported" no. 🙂 We'd need logic to go from serializers/models to component definitions, and then operations would need to reference those.
I started implementing this over here: https://github.com/django-json-api/django-rest-framework-json-api/pull/689. I've been sort of on hold with this, with feedback being some of the stuff I did would best be implemented upstream here. However, I've been busy with other stuff at work lately. Feel free to use anything useful you see there. Most of the relevant code is in [openapi.py](https://github.com/django-json-api/django-rest-framework-json-api/blob/18c677b012595c07a23cf1376a54e2db086c4977/rest_framework_json_api/schemas/openapi.py)
Super. Good stuff @n2ygk! Thanks for your efforts.
I'd love to have this feature. @n2ygk you mentioned that you were working on an implementation for this over in another project. Do you have an idea of the efforts needed to get that code back into drf? Hopefully I'd be able to dedicate some time to this.
I just made a PR for this issue. It's working without issue on our large codebase. Feel free to give it a try ;) | 2020-01-08T15:20:43 |
encode/django-rest-framework | 7,137 | encode__django-rest-framework-7137 | [
"7023",
"7080"
] | 373e521f3685c48eb22e6fbb1d7079f161a4a67b | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -268,13 +268,7 @@ def _map_field(self, field):
'items': {},
}
if not isinstance(field.child, _UnvalidatedField):
- map_field = self._map_field(field.child)
- items = {
- "type": map_field.get('type')
- }
- if 'format' in map_field:
- items['format'] = map_field.get('format')
- mapping['items'] = items
+ mapping['items'] = self._map_field(field.child)
return mapping
# DateField and DateTimeField type is string
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -51,7 +51,9 @@ def test_list_field_mapping(self):
(serializers.ListField(child=serializers.FloatField()), {'items': {'type': 'number'}, 'type': 'array'}),
(serializers.ListField(child=serializers.CharField()), {'items': {'type': 'string'}, 'type': 'array'}),
(serializers.ListField(child=serializers.IntegerField(max_value=4294967295)),
- {'items': {'type': 'integer', 'format': 'int64'}, 'type': 'array'}),
+ {'items': {'type': 'integer', 'maximum': 4294967295, 'format': 'int64'}, 'type': 'array'}),
+ (serializers.ListField(child=serializers.ChoiceField(choices=[('a', 'Choice A'), ('b', 'Choice B')])),
+ {'items': {'enum': ['a', 'b']}, 'type': 'array'}),
(serializers.IntegerField(min_value=2147483648),
{'type': 'integer', 'minimum': 2147483648, 'format': 'int64'}),
]
| OpenApi AutoSchema inspection produces invalid type `null` on ArrayField(base_field=ChoicesField())
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Create array field with base_field provided choices:
```python
class A(Model):
field = ArrayField(base_field=CharField(max_length=256, choices=(1,2,3)))
```
## Expected behavior
```js
properties: {field: {
type: array
items: {
enum: [1, 2, 3]
type: "string"
}
}}
```
or
```js
properties: {field: {
type: array
items: {
enum: [1, 2, 3]
}
}}
```
## Actual behavior
```js
properties: {
field: {
type: array
items: {
type: null
}
}}
```
## Note
Looks like choice field processing produces `{enum}`
https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas/openapi.py#L256
But list field expects `type` (`self._map_field(field.child).get('type')`)
https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas/openapi.py#L269
Add failing test case for schema generation
**Notes**:
As per OpenAPI specs, type is required. While generating schema, type is not provided for choice field. This leads to wrong schema in swagger and javascript error in redoc.
Someone has already reported this issue. See #7023
| I have same issue. I would like to fix this issue.
| 2020-01-10T02:39:39 |
encode/django-rest-framework | 7,142 | encode__django-rest-framework-7142 | [
"6643"
] | 442a20650254bd24165ddd69654b6f855df8f386 | diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -175,8 +175,13 @@ def get_attribute(self, instance):
value = attribute_instance.serializable_value(self.source_attrs[-1])
if is_simple_callable(value):
# Handle edge case where the relationship `source` argument
- # points to a `get_relationship()` method on the model
- value = value().pk
+ # points to a `get_relationship()` method on the model.
+ value = value()
+
+ # Handle edge case where relationship `source` argument points
+ # to an instance instead of a pk (e.g., a `@property`).
+ value = getattr(value, 'pk', value)
+
return PKOnlyObject(pk=value)
except AttributeError:
pass
| diff --git a/tests/models.py b/tests/models.py
--- a/tests/models.py
+++ b/tests/models.py
@@ -37,6 +37,15 @@ class ManyToManySource(RESTFrameworkModel):
class ForeignKeyTarget(RESTFrameworkModel):
name = models.CharField(max_length=100)
+ def get_first_source(self):
+ """Used for testing related field against a callable."""
+ return self.sources.all().order_by('pk')[0]
+
+ @property
+ def first_source(self):
+ """Used for testing related field against a property."""
+ return self.sources.all().order_by('pk')[0]
+
class UUIDForeignKeyTarget(RESTFrameworkModel):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4)
diff --git a/tests/test_relations_pk.py b/tests/test_relations_pk.py
--- a/tests/test_relations_pk.py
+++ b/tests/test_relations_pk.py
@@ -30,6 +30,25 @@ class Meta:
fields = ('id', 'name', 'sources')
+class ForeignKeyTargetCallableSourceSerializer(serializers.ModelSerializer):
+ first_source = serializers.PrimaryKeyRelatedField(
+ source='get_first_source',
+ read_only=True,
+ )
+
+ class Meta:
+ model = ForeignKeyTarget
+ fields = ('id', 'name', 'first_source')
+
+
+class ForeignKeyTargetPropertySourceSerializer(serializers.ModelSerializer):
+ first_source = serializers.PrimaryKeyRelatedField(read_only=True)
+
+ class Meta:
+ model = ForeignKeyTarget
+ fields = ('id', 'name', 'first_source')
+
+
class ForeignKeySourceSerializer(serializers.ModelSerializer):
class Meta:
model = ForeignKeySource
@@ -389,6 +408,34 @@ class Meta:
assert len(queryset) == 1
+class PKRelationTests(TestCase):
+
+ def setUp(self):
+ self.target = ForeignKeyTarget.objects.create(name='target-1')
+ ForeignKeySource.objects.create(name='source-1', target=self.target)
+ ForeignKeySource.objects.create(name='source-2', target=self.target)
+
+ def test_relation_field_callable_source(self):
+ serializer = ForeignKeyTargetCallableSourceSerializer(self.target)
+ expected = {
+ 'id': 1,
+ 'name': 'target-1',
+ 'first_source': 1,
+ }
+ with self.assertNumQueries(1):
+ self.assertEqual(serializer.data, expected)
+
+ def test_relation_field_property_source(self):
+ serializer = ForeignKeyTargetPropertySourceSerializer(self.target)
+ expected = {
+ 'id': 1,
+ 'name': 'target-1',
+ 'first_source': 1,
+ }
+ with self.assertNumQueries(1):
+ self.assertEqual(serializer.data, expected)
+
+
class PKNullableForeignKeyTests(TestCase):
def setUp(self):
target = ForeignKeyTarget(name='target-1')
| PrimaryKeyRelatedField from property method wrongly generates PKOnlyObject
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
**It seems related to #4653, but that one was closed with no action taken.**
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Define the following models and serializer:
```python
class Foo(models.Model):
pass
class Bar(models.Model):
@property
def foo(self):
return Foo.objects.first()
class BarSerializer(serializers.ModelSerializer):
foo = serializers.PrimaryKeyRelatedField(
queryset=Foo.objects.all()
)
class Meta:
model = Bar
fields = ('id', 'foo')
```
Create `Bar` instance and attempt to render it:
```python
>>> Foo.objects.create()
<Foo: Foo object (2)>
>>> bar = Bar.objects.create()
>>> bar.foo
<Foo: Foo object (1)>
>>> serializer = BarSerializer(bar)
>>> serializer.data
{'foo': <Foo: Foo object (1)>, 'id': 2}
>>> JSONRenderer().render(serializer.data)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/clara/.virtualenvs/django_example_project/lib/python3.5/site-packages/rest_framework/renderers.py", line 107, in render
allow_nan=not self.strict, separators=separators
File "/home/clara/.virtualenvs/django_example_project/lib/python3.5/site-packages/rest_framework/utils/json.py", line 28, in dumps
return json.dumps(*args, **kwargs)
File "/usr/lib/python3.5/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "/home/clara/.virtualenvs/django_example_project/lib/python3.5/site-packages/rest_framework/utils/encoders.py", line 68, in default
return super(JSONEncoder, self).default(obj)
File "/usr/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Foo: Foo object (1)> is not JSON serializable
```
## Expected behavior
The serialization and deserialization should behave the same way they would if the field was a real FK in the model, that is, **extract the PK from the related object** in the **serialization**, and **obtain the related object** from the PK in the **deserialization**.
`serializer.data` should be
```
{
'id': 2,
'foo': 1
}
```
Which can be rendered to JSON.
## Actual behavior
`serializer.data` is
```
{
'id': 2,
'foo': <Foo: Foo object (1)>
}
```
Which causes the error in the JSON rendering.
------------------------------
If I understand it correctly, this situation should fall into the **edge case** handled in `RelatedField.get_attribute()`:
```python
value = instance.serializable_value(self.source_attrs[-1])
if is_simple_callable(value):
# Handle edge case where the relationship `source` argument
# points to a `get_relationship()` method on the model
value = value().pk
```
but because it is a `@property` method, it does not return a callable and causes the method to assume it is a PK.
I tried changing the source to `foo.pk`, that corrects the serialization behaviour, but messes up the deserialization behaviour (which was correct).
| I'm going to close this off as unintended usage. Related fields are designed to work across ORM relationships, and this is just a regular Python property that happens to look kind of like a relationship. However, all of the ORM metadata that backs these fields is not present (since it's not an actual model field), so naturally the related serializer fields may not work.
That said, you should be able to achieve the desired result with the following:
```python
class BarSerializer(serializers.ModelSerializer):
foo = serializers.IntegerField(source='foo.pk')
class Meta:
model = Bar
fields = ['id', 'foo']
```
It would be nice if this worked.
I just hit this too and spent a bunch of time tearing my hair out trying to figure out why. Might be nice if the framework could spit out an error or something when folks make this mistake. | 2020-01-15T04:24:36 |
encode/django-rest-framework | 7,143 | encode__django-rest-framework-7143 | [
"7100"
] | 442a20650254bd24165ddd69654b6f855df8f386 | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -13,7 +13,7 @@
import copy
import inspect
import traceback
-from collections import OrderedDict
+from collections import OrderedDict, defaultdict
from collections.abc import Mapping
from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
@@ -1508,28 +1508,55 @@ def get_unique_together_validators(self):
# which may map onto a model field. Any dotted field name lookups
# cannot map to a field, and must be a traversal, so we're not
# including those.
- field_names = {
- field.source for field in self._writable_fields
+ field_sources = OrderedDict(
+ (field.field_name, field.source) for field in self._writable_fields
if (field.source != '*') and ('.' not in field.source)
- }
+ )
# Special Case: Add read_only fields with defaults.
- field_names |= {
- field.source for field in self.fields.values()
+ field_sources.update(OrderedDict(
+ (field.field_name, field.source) for field in self.fields.values()
if (field.read_only) and (field.default != empty) and (field.source != '*') and ('.' not in field.source)
- }
+ ))
+
+ # Invert so we can find the serializer field names that correspond to
+ # the model field names in the unique_together sets. This also allows
+ # us to check that multiple fields don't map to the same source.
+ source_map = defaultdict(list)
+ for name, source in field_sources.items():
+ source_map[source].append(name)
# Note that we make sure to check `unique_together` both on the
# base model class, but also on any parent classes.
validators = []
for parent_class in model_class_inheritance_tree:
for unique_together in parent_class._meta.unique_together:
- if field_names.issuperset(set(unique_together)):
- validator = UniqueTogetherValidator(
- queryset=parent_class._default_manager,
- fields=unique_together
+ # Skip if serializer does not map to all unique together sources
+ if not set(source_map).issuperset(set(unique_together)):
+ continue
+
+ for source in unique_together:
+ assert len(source_map[source]) == 1, (
+ "Unable to create `UniqueTogetherValidator` for "
+ "`{model}.{field}` as `{serializer}` has multiple "
+ "fields ({fields}) that map to this model field. "
+ "Either remove the extra fields, or override "
+ "`Meta.validators` with a `UniqueTogetherValidator` "
+ "using the desired field names."
+ .format(
+ model=self.Meta.model.__name__,
+ serializer=self.__class__.__name__,
+ field=source,
+ fields=', '.join(source_map[source]),
+ )
)
- validators.append(validator)
+
+ field_names = tuple(source_map[f][0] for f in unique_together)
+ validator = UniqueTogetherValidator(
+ queryset=parent_class._default_manager,
+ fields=field_names
+ )
+ validators.append(validator)
return validators
def get_unique_for_date_validators(self):
| diff --git a/tests/test_validators.py b/tests/test_validators.py
--- a/tests/test_validators.py
+++ b/tests/test_validators.py
@@ -344,6 +344,49 @@ class Meta:
]
}
+ def test_default_validator_with_fields_with_source(self):
+ class TestSerializer(serializers.ModelSerializer):
+ name = serializers.CharField(source='race_name')
+
+ class Meta:
+ model = UniquenessTogetherModel
+ fields = ['name', 'position']
+
+ serializer = TestSerializer()
+ expected = dedent("""
+ TestSerializer():
+ name = CharField(source='race_name')
+ position = IntegerField()
+ class Meta:
+ validators = [<UniqueTogetherValidator(queryset=UniquenessTogetherModel.objects.all(), fields=('name', 'position'))>]
+ """)
+ assert repr(serializer) == expected
+
+ def test_default_validator_with_multiple_fields_with_same_source(self):
+ class TestSerializer(serializers.ModelSerializer):
+ name = serializers.CharField(source='race_name')
+ other_name = serializers.CharField(source='race_name')
+
+ class Meta:
+ model = UniquenessTogetherModel
+ fields = ['name', 'other_name', 'position']
+
+ serializer = TestSerializer(data={
+ 'name': 'foo',
+ 'other_name': 'foo',
+ 'position': 1,
+ })
+ with pytest.raises(AssertionError) as excinfo:
+ serializer.is_valid()
+
+ expected = (
+ "Unable to create `UniqueTogetherValidator` for "
+ "`UniquenessTogetherModel.race_name` as `TestSerializer` has "
+ "multiple fields (name, other_name) that map to this model field. "
+ "Either remove the extra fields, or override `Meta.validators` "
+ "with a `UniqueTogetherValidator` using the desired field names.")
+ assert str(excinfo.value) == expected
+
def test_allow_explict_override(self):
"""
Ensure validators can be explicitly removed..
| ModelSerializer UniqueTogetherValidator is incompatible with field source
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
## Steps to reproduce
In DRF == 3.10.3 and below it was a valid case
```python
# models.py
class MyModel(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
date_from = models.DateField()
date_to = models.DateField()
class Meta:
unique_together = (
('date_from', 'user'),
('date_to', 'user'),
)
# serializers.py
class MyModelSerializer(serializers.ModelSerializer):
date_start = serializers.DateField(source='date_from')
date_end = serializers.DateField(source='date_to')
class Meta:
model = MyModel
fields = 'date_start', 'date_end', 'user'
data = {
'user': 1,
'date_start': '2019-11-13',
'date_end': '2019-11-14'
}
serializer = MyModelSerializer(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()
```
In DRF == 3.11.0 I get an error in is_valid() method
```
~/PycharmProjects/env/staff.3.7.5/lib/python3.7/site-packages/rest_framework/utils/serializer_helpers.py in __getitem__(self, key)
146
147 def __getitem__(self, key):
--> 148 return self.fields[key]
149
150 def __delitem__(self, key):
KeyError: 'date_from'
```
This case is no longer valid?
It was a convenient way to redirect field names.
| Why aren't your fields in a list?
@napsterv it's equivalent to a tuple so it's fine anyway.
@hauworkarea could you paste the entire traceback please ?
@xordoquy that's entire traceback
```
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-3-7ffae1e9ca9d> in <module>
6
7 serializer = UserVacationSer(data=data)
----> 8 serializer.is_valid(raise_exception=True)
9 serializer.save()
~/PycharmProjects/env/staff.3.7.5/lib/python3.7/site-packages/rest_framework/serializers.py in is_valid(self, raise_exception)
232 if not hasattr(self, '_validated_data'):
233 try:
--> 234 self._validated_data = self.run_validation(self.initial_data)
235 except ValidationError as exc:
236 self._validated_data = {}
~/PycharmProjects/env/staff.3.7.5/lib/python3.7/site-packages/rest_framework/serializers.py in run_validation(self, data)
433 value = self.to_internal_value(data)
434 try:
--> 435 self.run_validators(value)
436 value = self.validate(value)
437 assert value is not None, '.validate() should return the validated data'
~/PycharmProjects/env/staff.3.7.5/lib/python3.7/site-packages/rest_framework/serializers.py in run_validators(self, value)
466 else:
467 to_validate = value
--> 468 super().run_validators(to_validate)
469
470 def to_internal_value(self, data):
~/PycharmProjects/env/staff.3.7.5/lib/python3.7/site-packages/rest_framework/fields.py in run_validators(self, value)
586 try:
587 if getattr(validator, 'requires_context', False):
--> 588 validator(value, self)
589 else:
590 validator(value)
~/PycharmProjects/env/staff.3.7.5/lib/python3.7/site-packages/rest_framework/validators.py in __call__(self, attrs, serializer)
146
147 def __call__(self, attrs, serializer):
--> 148 self.enforce_required_fields(attrs, serializer)
149 queryset = self.queryset
150 queryset = self.filter_queryset(attrs, queryset, serializer)
~/PycharmProjects/env/staff.3.7.5/lib/python3.7/site-packages/rest_framework/validators.py in enforce_required_fields(self, attrs, serializer)
106 missing_items = {
107 field_name: self.missing_message
--> 108 for field_name in self.fields
109 if serializer.fields[field_name].source not in attrs
110 }
~/PycharmProjects/env/staff.3.7.5/lib/python3.7/site-packages/rest_framework/validators.py in <dictcomp>(.0)
107 field_name: self.missing_message
108 for field_name in self.fields
--> 109 if serializer.fields[field_name].source not in attrs
110 }
111 if missing_items:
~/PycharmProjects/env/staff.3.7.5/lib/python3.7/site-packages/rest_framework/utils/serializer_helpers.py in __getitem__(self, key)
146
147 def __getitem__(self, key):
--> 148 return self.fields[key]
149
150 def __delitem__(self, key):
KeyError: 'date_from'
```
It seems that the problem occurs when there is a unique_together in the meta class of the model.
Yes, the model contains unique_together.
```python
# models.py
class MyModel(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
date_from = models.DateField()
date_to = models.DateField()
class Meta:
unique_together = (
('date_from', 'user'),
('date_to', 'user'),
)
```
Corrected the original description.
I'm having the same issue.
`UniqueTogetherValidator.enforce_required_fields` assumes the presence of its listed fields in the dict comprehension:
```
missing_items = {
field_name: self.missing_message
for field_name in self.fields
if serializer.fields[field_name].source not in attrs
}
```
I can make my failing tests pass by replacing this with:
```
fields_from_serializer = [
field
for field in serializer.fields.values()
if field.source in self.fields
]
missing_items = {
field.field_name: self.missing_message
for field in fields_from_serializer
if field.source not in attrs
}
# or just
missing_items = {
field.field_name: self.missing_message
for field in serializer.fields.values()
if field.source in self.fields
and field.source not in attrs
}
```
and similarly, in `UniqueTogetherValidator.filter_queryset`, replacing
```
sources = [
serializer.fields[field_name].source
for field_name in self.fields
]
# with:
sources = [
field.source
for field in serializer.fields.values()
if field.source in self.fields
]
```
I can't be 100% sure the different way of finding the fields doesn't break any assumptions about when the fields should be present.
I'm getting the same issue with DRF 3.11
I have unique_together constraint where one field is ForeignKey.
Serializer
```
class SomeSerializer(SomeBaseSerializer):
xxxx_id = serializers.PrimaryKeyRelatedField(source='xxxx', write_only=True,
queryset=XXXmodel.objects.all())
class Meta:
model = SomeModel
fields = ('field_1', 'field_2', 'xxxx_id')
```
Model
```
class SomeModel(BaseModel):
xxxx = models.ForeignKey(
'app.App',
null=False,
blank=False,
on_delete=models.CASCADE
)
field_1 = CleanCharField(max_length=64, null=False, blank=False)
field_2 = models.DecimalField(max_digits=5, decimal_places=1, null=False, blank=False)
class Meta:
app_label = 'app'
db_table = 'app_table'
unique_together = ('xxxx', 'field_2')
```
Thanks - I'll look into this. This stems from #7086, which fixed a related bug. It looks like those changes in turn broke `UniqueTogetherValidator`s that are generated by `ModelSerializer`s.
For now, a workaround would be to declare the `UniqueTogetherValidator`s directly on your serializer class. Using the example the issue description...
```python
class MyModelSerializer(serializers.ModelSerializer):
date_start = serializers.DateField(source='date_from')
date_end = serializers.DateField(source='date_to')
class Meta:
model = MyModel
fields = ['date_start', 'date_end', 'user']
validators = [
UniqueTogetherValidator(queryset=MyModel.objects.all(), fields=['user', 'date_start']),
UniqueTogetherValidator(queryset=MyModel.objects.all(), fields=['user', 'date_end']),
]
```
| 2020-01-15T09:02:52 |
encode/django-rest-framework | 7,144 | encode__django-rest-framework-7144 | [
"7120"
] | 442a20650254bd24165ddd69654b6f855df8f386 | diff --git a/rest_framework/settings.py b/rest_framework/settings.py
--- a/rest_framework/settings.py
+++ b/rest_framework/settings.py
@@ -182,14 +182,19 @@ def import_from_string(val, setting_name):
class APISettings:
"""
- A settings object, that allows API settings to be accessed as properties.
- For example:
+ A settings object that allows REST Framework settings to be accessed as
+ properties. For example:
from rest_framework.settings import api_settings
print(api_settings.DEFAULT_RENDERER_CLASSES)
Any setting with string import paths will be automatically resolved
and return the class, rather than the string literal.
+
+ Note:
+ This is an internal class that is only compatible with settings namespaced
+ under the REST_FRAMEWORK name. It is not intended to be used by 3rd-party
+ apps, and test helpers like `override_settings` may not work as expected.
"""
def __init__(self, user_settings=None, defaults=None, import_strings=None):
if user_settings:
| APISettings should be declared as internal
## Summary
**EDIT:** At the end of this issue i realized that this problem is the fault of the django-rest-framework-jwt library, but it is an easy to make mistake, because the documentation of APISettings does not declare it as internal. I'm not sure if there are many projects using this class wrongly for their own code.
The APISettings class located in `rest_framework/settings.py` uses caching which has previously led to problems with the override_settings method provided in django (see #2466 as well as #2473).
Unfortunately the function `reload_api_settings` which looks like this:
```python
def reload_api_settings(*args, **kwargs):
setting = kwargs['setting']
if setting == 'REST_FRAMEWORK':
api_settings.reload()
```
only reloads the settings when the setting sent by the signal is `REST_FRAMEWORK`.
When the an app (like https://github.com/jpadilla/django-rest-framework-jwt ) is used which makes use of the APISettings class to construct it's own `api_settings` singleton, the condition in the `reload_api_settings` function causes overrides of library settings (e.g. `JWT_AUTH` see https://jpadilla.github.io/django-rest-framework-jwt/ ) to be ignored.
I'm not a hundred percent sure if this is really an issue of django-rest-framework or of django-rest-framework-jwt using the the internal? APISettings class.
## Checklist
- [X] I have verified that that issue exists against the `master` branch of Django REST framework.
- [X] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [X] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [X] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [X] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
- Use django-rest-framework-jwt with django-rest-framework
- Perform request that accesses `JWT_AUTH` settings
- Use `override_setting` to overrde a setting from the `JWT_AUTH` dict
- Change will not be reflected since settings are cached and signal is ignored
## Expected behavior
## Actual behavior
| 2020-01-15T09:17:42 |
||
encode/django-rest-framework | 7,158 | encode__django-rest-framework-7158 | [
"7157"
] | e4a26ad58a0e3d13e7cb788b724398592b1543b3 | diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py
--- a/rest_framework/authentication.py
+++ b/rest_framework/authentication.py
@@ -220,6 +220,6 @@ class RemoteUserAuthentication(BaseAuthentication):
header = "REMOTE_USER"
def authenticate(self, request):
- user = authenticate(remote_user=request.META.get(self.header))
+ user = authenticate(request=request, remote_user=request.META.get(self.header))
if user and user.is_active:
return (user, None)
| RemoteUserAuthentication.authenticate calls django.contrib.auth.authenticate without request argument
## Checklist
- [X] I have verified that that issue exists against the `master` branch of Django REST framework.
- [X] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [X] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [X] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [X] I have reduced the issue to the simplest possible case.
- [x] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Expected behavior
`user = authenticate(request=request, remote_user=request.META.get(self.header))`
## Actual behavior
`user = authenticate(remote_user=request.META.get(self.header))`
| Feel free to open a PR about that. It looks like wee didn't notice that one when moving to Django 1.11 | 2020-01-23T15:51:33 |
|
encode/django-rest-framework | 7,217 | encode__django-rest-framework-7217 | [
"7216"
] | ddfb9672ae703ce15392072dd110415147b5171a | diff --git a/rest_framework/viewsets.py b/rest_framework/viewsets.py
--- a/rest_framework/viewsets.py
+++ b/rest_framework/viewsets.py
@@ -25,11 +25,12 @@
from django.views.decorators.csrf import csrf_exempt
from rest_framework import generics, mixins, views
+from rest_framework.decorators import MethodMapper
from rest_framework.reverse import reverse
def _is_extra_action(attr):
- return hasattr(attr, 'mapping')
+ return hasattr(attr, 'mapping') and isinstance(attr.mapping, MethodMapper)
class ViewSetMixin:
| diff --git a/tests/test_viewsets.py b/tests/test_viewsets.py
--- a/tests/test_viewsets.py
+++ b/tests/test_viewsets.py
@@ -81,10 +81,20 @@ def suffixed_action(self, request, *args, **kwargs):
raise NotImplementedError
+class ThingWithMapping:
+ def __init__(self):
+ self.mapping = {}
+
+
+class ActionViewSetWithMapping(ActionViewSet):
+ mapper = ThingWithMapping()
+
+
router = SimpleRouter()
router.register(r'actions', ActionViewSet)
router.register(r'actions-alt', ActionViewSet, basename='actions-alt')
router.register(r'names', ActionNamesViewSet, basename='names')
+router.register(r'mapping', ActionViewSetWithMapping, basename='mapping')
urlpatterns = [
@@ -161,6 +171,18 @@ def test_extra_actions(self):
self.assertEqual(actual, expected)
+ def test_should_only_return_decorated_methods(self):
+ view = ActionViewSetWithMapping()
+ actual = [action.__name__ for action in view.get_extra_actions()]
+ expected = [
+ 'custom_detail_action',
+ 'custom_list_action',
+ 'detail_action',
+ 'list_action',
+ 'unresolvable_detail_action',
+ ]
+ self.assertEqual(actual, expected)
+
@override_settings(ROOT_URLCONF='tests.test_viewsets')
class GetExtraActionUrlMapTests(TestCase):
| ViewSet extra action detection is too permissive.
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [x] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Add any attribute to a ViewSet to which `hasattr(attr, 'mapping')` returns True. A case I got in a work project is that, because of a certain mock, one of the attributes of a viewset became a `MagicMock` instance. `hasattr(MagicMock(), 'mapping')` returns True (actually it returns True for **any** attribute you pass as the second parameter of `hasattr`), causing the same issue.
## Expected behavior
This attribute should not be accounted as an "action"
## Actual behavior
By itself, `get_extra_actions` will return any attribute with a `mapping` attribute.
If the viewset is used with a router, the test suite fails to initialize because SimpleRouter expect `get_extra_actions` to only return methods:
```
tests/test_viewsets.py:102: in <module>
url(r'^api/', include(router.urls)),
rest_framework/routers.py:78: in urls
self._urls = self.get_urls()
rest_framework/routers.py:237: in get_urls
routes = self.get_routes(viewset)
rest_framework/routers.py:156: in get_routes
not_allowed = [
rest_framework/routers.py:158: in <listcomp>
if action.__name__ in known_actions
E AttributeError: 'ThingWithMapping' object has no attribute '__name__'
```
| 2020-03-05T05:46:30 |
|
encode/django-rest-framework | 7,223 | encode__django-rest-framework-7223 | [
"6196"
] | 4a98533746db44c997882ba01d5515a29a61dcc3 | diff --git a/rest_framework/viewsets.py b/rest_framework/viewsets.py
--- a/rest_framework/viewsets.py
+++ b/rest_framework/viewsets.py
@@ -93,6 +93,10 @@ def as_view(cls, actions=None, **initkwargs):
def view(request, *args, **kwargs):
self = cls(**initkwargs)
+
+ if 'get' in actions and 'head' not in actions:
+ actions['head'] = actions['get']
+
# We also store the mapping of request methods to actions,
# so that we can later set the action attribute.
# eg. `self.action = 'list'` on an incoming GET request.
@@ -104,9 +108,6 @@ def view(request, *args, **kwargs):
handler = getattr(self, action)
setattr(self, method, handler)
- if hasattr(self, 'get') and not hasattr(self, 'head'):
- self.head = self.get
-
self.request = request
self.args = args
self.kwargs = kwargs
| diff --git a/tests/test_viewsets.py b/tests/test_viewsets.py
--- a/tests/test_viewsets.py
+++ b/tests/test_viewsets.py
@@ -37,14 +37,18 @@ class ActionViewSet(GenericViewSet):
queryset = Action.objects.all()
def list(self, request, *args, **kwargs):
- return Response()
+ response = Response()
+ response.view = self
+ return response
def retrieve(self, request, *args, **kwargs):
return Response()
@action(detail=False)
def list_action(self, request, *args, **kwargs):
- raise NotImplementedError
+ response = Response()
+ response.view = self
+ return response
@action(detail=False, url_name='list-custom')
def custom_list_action(self, request, *args, **kwargs):
@@ -155,6 +159,22 @@ def test_args_kwargs_request_action_map_on_self(self):
self.assertNotIn(attribute, dir(bare_view))
self.assertIn(attribute, dir(view))
+ def test_viewset_action_attr(self):
+ view = ActionViewSet.as_view(actions={'get': 'list'})
+
+ get = view(factory.get('/'))
+ head = view(factory.head('/'))
+ assert get.view.action == 'list'
+ assert head.view.action == 'list'
+
+ def test_viewset_action_attr_for_extra_action(self):
+ view = ActionViewSet.as_view(actions=dict(ActionViewSet.list_action.mapping))
+
+ get = view(factory.get('/'))
+ head = view(factory.head('/'))
+ assert get.view.action == 'list_action'
+ assert head.view.action == 'list_action'
+
class GetExtraActionsTests(TestCase):
| self.action is set to None during HEAD request
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
## Steps to reproduce
Send a HEAD request to a viewset which prints `self.action` in `get_queryset`:
```
class MyViewSet(viewsets.ModelViewSet):
def get_queryset(self):
print self.action
```
## Expected behavior
During a `HEAD` request this should, just like during `GET` request, print `list` or `retrieve` depending on the route requested.
## Actual behavior
`None` is printed
| This is a side effect of:
1. [default head being set to get](https://github.com/encode/django-rest-framework/blob/b090ae9d30f26117f474479b853289a46c6ca615/rest_framework/viewsets.py#L109)
2. routers not mapping `head`
The `self.action` mapping is performed [here](https://github.com/encode/django-rest-framework/blob/b090ae9d30f26117f474479b853289a46c6ca615/rest_framework/viewsets.py#L145)
One fix seems to be to just add 'head' with the same value as 'get' to the mappings in SimpleRouter: https://github.com/encode/django-rest-framework/blob/master/rest_framework/routers.py#L123.
Not sure how it should be tested and if it creates some other problems though.
indeed. I don't see any side effect and it doesn't look like the mapping is tested.
We'll need to add a line about it in the release note though.
> One fix seems to be to just add 'head' with the same value as 'get' to the mappings in SimpleRouter: https://github.com/encode/django-rest-framework/blob/master/rest_framework/routers.py#L123.
One more action is needed to fix it for dynamic (detail) routes: add `head` [here](https://github.com/encode/django-rest-framework/blob/3.9.2/rest_framework/decorators.py#L135) or [here](https://github.com/encode/django-rest-framework/blob/3.9.2/rest_framework/routers.py#L232) something like this:
```python
if 'get' in action.mapping and 'head' not in action.mapping:
action.mapping['head'] = action.mapping['get']
```
It doesn't seem this was implemented yet, so I made these workarounds.
```python3
class PatchedDefaultRouter(routers.DefaultRouter):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for route in self.routes:
if hasattr(route, 'mapping') and 'get' in route.mapping and 'head' not in route.mapping:
route.mapping['head'] = route.mapping['get']
def _get_dynamic_route(self, route, action):
result = super()._get_dynamic_route(route, action)
if 'get' in result.mapping and 'head' not in result.mapping:
result.mapping['head'] = result.mapping['get']
return result
class PatchedSimpleRouter(routers.SimpleRouter):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for route in self.routes:
if hasattr(route, 'mapping'):
route.mapping['head'] = 'retrieve' if route.detail else 'list'
def _get_dynamic_route(self, route, action):
result = super()._get_dynamic_route(route, action)
if 'get' in result.mapping and 'head' not in result.mapping:
result.mapping['head'] = result.mapping['get']
return result
``` | 2020-03-08T02:18:33 |
encode/django-rest-framework | 7,239 | encode__django-rest-framework-7239 | [
"7231"
] | 5cc6ace9c45ac42cf59d52643ab9cbb6c565d23e | diff --git a/rest_framework/request.py b/rest_framework/request.py
--- a/rest_framework/request.py
+++ b/rest_framework/request.py
@@ -179,6 +179,13 @@ def __init__(self, request, parsers=None, authenticators=None,
forced_auth = ForcedAuthentication(force_user, force_token)
self.authenticators = (forced_auth,)
+ def __repr__(self):
+ return '<%s.%s: %s %r>' % (
+ self.__class__.__module__,
+ self.__class__.__name__,
+ self.method,
+ self.get_full_path())
+
def _default_negotiator(self):
return api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS()
| diff --git a/tests/test_request.py b/tests/test_request.py
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -272,6 +272,12 @@ def test_default_secure_true(self):
class TestHttpRequest(TestCase):
+ def test_repr(self):
+ http_request = factory.get('/path')
+ request = Request(http_request)
+
+ assert repr(request) == "<rest_framework.request.Request: GET '/path'>"
+
def test_attribute_access_proxy(self):
http_request = factory.get('/')
request = Request(http_request)
| Implement `Request.__repr__` to show useful information about the request
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
The path, for starters, would be useful.
| The first thing to do on this issue would be to confirm:
* What the `__repr__` behavior of a standard Django request instance is.
* What the `__repr__` behavior of our Request instances currently is.
* Talk through what exact changes would be suggested.
> What the `__repr__` behavior of a standard Django request instance is.
`<WSGIRequest: GET '/foo'>`
> What the `__repr__` behavior of our Request instances currently is.
`<rest_framework.request.Request at 0x10f43dcd0>`
| 2020-03-20T23:58:10 |
encode/django-rest-framework | 7,254 | encode__django-rest-framework-7254 | [
"7253"
] | 734c534dbb9c5758af335dba1fdbc2690388f076 | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -15,6 +15,7 @@
from rest_framework import exceptions, renderers, serializers
from rest_framework.compat import uritemplate
from rest_framework.fields import _UnvalidatedField, empty
+from rest_framework.settings import api_settings
from .generators import BaseSchemaGenerator
from .inspectors import ViewInspector
@@ -442,11 +443,17 @@ def _map_field(self, field):
content['format'] = field.protocol
return content
- # DecimalField has multipleOf based on decimal_places
if isinstance(field, serializers.DecimalField):
- content = {
- 'type': 'number'
- }
+ if getattr(field, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING):
+ content = {
+ 'type': 'string',
+ 'format': 'decimal',
+ }
+ else:
+ content = {
+ 'type': 'number'
+ }
+
if field.decimal_places:
content['multipleOf'] = float('.' + (field.decimal_places - 1) * '0' + '1')
if field.max_whole_digits:
@@ -457,7 +464,7 @@ def _map_field(self, field):
if isinstance(field, serializers.FloatField):
content = {
- 'type': 'number'
+ 'type': 'number',
}
self._map_min_max(field, content)
return content
@@ -556,7 +563,8 @@ def _map_field_validators(self, field, schema):
schema['maximum'] = v.limit_value
elif isinstance(v, MinValueValidator):
schema['minimum'] = v.limit_value
- elif isinstance(v, DecimalValidator):
+ elif isinstance(v, DecimalValidator) and \
+ not getattr(field, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING):
if v.decimal_places:
schema['multipleOf'] = float('.' + (v.decimal_places - 1) * '0' + '1')
if v.max_digits:
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -838,6 +838,16 @@ def test_serializer_validators(self):
assert properties['decimal2']['type'] == 'number'
assert properties['decimal2']['multipleOf'] == .0001
+ assert properties['decimal3'] == {
+ 'type': 'string', 'format': 'decimal', 'maximum': 1000000, 'minimum': -1000000, 'multipleOf': 0.01
+ }
+ assert properties['decimal4'] == {
+ 'type': 'string', 'format': 'decimal', 'maximum': 1000000, 'minimum': -1000000, 'multipleOf': 0.01
+ }
+ assert properties['decimal5'] == {
+ 'type': 'string', 'format': 'decimal', 'maximum': 10000, 'minimum': -10000, 'multipleOf': 0.01
+ }
+
assert properties['email']['type'] == 'string'
assert properties['email']['format'] == 'email'
assert properties['email']['default'] == '[email protected]'
diff --git a/tests/schemas/views.py b/tests/schemas/views.py
--- a/tests/schemas/views.py
+++ b/tests/schemas/views.py
@@ -119,9 +119,13 @@ class ExampleValidatedSerializer(serializers.Serializer):
MinLengthValidator(limit_value=2),
)
)
- decimal1 = serializers.DecimalField(max_digits=6, decimal_places=2)
- decimal2 = serializers.DecimalField(max_digits=5, decimal_places=0,
+ decimal1 = serializers.DecimalField(max_digits=6, decimal_places=2, coerce_to_string=False)
+ decimal2 = serializers.DecimalField(max_digits=5, decimal_places=0, coerce_to_string=False,
validators=(DecimalValidator(max_digits=17, decimal_places=4),))
+ decimal3 = serializers.DecimalField(max_digits=8, decimal_places=2, coerce_to_string=True)
+ decimal4 = serializers.DecimalField(max_digits=8, decimal_places=2, coerce_to_string=True,
+ validators=(DecimalValidator(max_digits=17, decimal_places=4),))
+ decimal5 = serializers.DecimalField(max_digits=6, decimal_places=2)
email = serializers.EmailField(default='[email protected]')
url = serializers.URLField(default='http://www.example.com', allow_null=True)
uuid = serializers.UUIDField()
| Decimal fields rendered as number instead of string in OpenAPI schema
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
1. Create a serializer with a decimal field.
2. Use the serializer in a `ViewSet`.
3. Render the OpenAPI schema.
## Expected behavior
The decimal field should have a type of `string`.
## Actual behavior
The decimal field has a type of `number`.
This issue was introduced by #6674.
| Additional context: Besides the schema being wrong—the API returns decimals as strings—JS/TS clients need to represent decimals as strings to avoid losing precision. | 2020-04-04T23:19:25 |
encode/django-rest-framework | 7,264 | encode__django-rest-framework-7264 | [
"7253"
] | e6c1afbcf97e7080c0632ac9e2d60a6d10bd1a5c | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -15,6 +15,7 @@
from rest_framework import exceptions, renderers, serializers
from rest_framework.compat import uritemplate
from rest_framework.fields import _UnvalidatedField, empty
+from rest_framework.settings import api_settings
from .generators import BaseSchemaGenerator
from .inspectors import ViewInspector
@@ -325,30 +326,29 @@ def _get_pagination_parameters(self, path, method):
def _map_choicefield(self, field):
choices = list(OrderedDict.fromkeys(field.choices)) # preserve order and remove duplicates
- if all(isinstance(choice, bool) for choice in choices):
- type = 'boolean'
- elif all(isinstance(choice, int) for choice in choices):
- type = 'integer'
- elif all(isinstance(choice, (int, float, Decimal)) for choice in choices): # `number` includes `integer`
- # Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.21
- type = 'number'
- elif all(isinstance(choice, str) for choice in choices):
- type = 'string'
- else:
- type = None
-
mapping = {
# The value of `enum` keyword MUST be an array and SHOULD be unique.
# Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.20
'enum': choices
}
- # If We figured out `type` then and only then we should set it. It must be a string.
- # Ref: https://swagger.io/docs/specification/data-models/data-types/#mixed-type
- # It is optional but it can not be null.
- # Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.21
- if type:
- mapping['type'] = type
+ if all(isinstance(choice, bool) for choice in choices):
+ mapping['type'] = 'boolean'
+ elif all(isinstance(choice, int) for choice in choices):
+ mapping['type'] = 'integer'
+ elif all(isinstance(choice, Decimal) for choice in choices):
+ mapping['format'] = 'decimal'
+ if api_settings.COERCE_DECIMAL_TO_STRING:
+ mapping['enum'] = [str(choice) for choice in mapping['enum']]
+ mapping['type'] = 'string'
+ else:
+ mapping['type'] = 'number'
+ elif all(isinstance(choice, (int, float, Decimal)) for choice in choices): # `number` includes `integer`
+ # Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.21
+ mapping['type'] = 'number'
+ elif all(isinstance(choice, str) for choice in choices):
+ mapping['type'] = 'string'
+
return mapping
def _map_field(self, field):
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -1,5 +1,6 @@
import uuid
import warnings
+from decimal import Decimal
import pytest
from django.conf.urls import url
@@ -78,6 +79,9 @@ def test_list_field_mapping(self):
(1, 'One'), (2, 'Two'), (3, 'Three'), (2, 'Two'), (3, 'Three'), (1, 'One'),
])),
{'items': {'enum': [1, 2, 3], 'type': 'integer'}, 'type': 'array'}),
+ (serializers.ListField(child=
+ serializers.ChoiceField(choices=[(Decimal('1.111'), 'one'), (Decimal('2.222'), 'two')])),
+ {'items': {'enum': ['1.111', '2.222'], 'type': 'string', 'format': 'decimal'}, 'type': 'array'}),
(serializers.IntegerField(min_value=2147483648),
{'type': 'integer', 'minimum': 2147483648, 'format': 'int64'}),
]
@@ -85,6 +89,15 @@ def test_list_field_mapping(self):
with self.subTest(field=field):
assert inspector._map_field(field) == mapping
+ @override_settings(REST_FRAMEWORK={'COERCE_DECIMAL_TO_STRING': False})
+ def test_decimal_schema_for_choice_field(self):
+ inspector = AutoSchema()
+ field = serializers.ListField(
+ child=serializers.ChoiceField(choices=[(Decimal('1.111'), 'one'), (Decimal('2.222'), 'two')]))
+ mapping = {'items': {'enum': [Decimal('1.111'), Decimal('2.222')], 'type': 'number'}, 'type': 'array'}
+ assert inspector._map_field(field) == mapping
+
+
def test_lazy_string_field(self):
class ItemSerializer(serializers.Serializer):
text = serializers.CharField(help_text=_('lazy string'))
| Decimal fields rendered as number instead of string in OpenAPI schema
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
1. Create a serializer with a decimal field.
2. Use the serializer in a `ViewSet`.
3. Render the OpenAPI schema.
## Expected behavior
The decimal field should have a type of `string`.
## Actual behavior
The decimal field has a type of `number`.
This issue was introduced by #6674.
| Additional context: Besides the schema being wrong—the API returns decimals as strings—JS/TS clients need to represent decimals as strings to avoid losing precision. | 2020-04-08T14:59:24 |
encode/django-rest-framework | 7,290 | encode__django-rest-framework-7290 | [
"7287"
] | 3eef5f47f3c0faaf71ba9aee755433d003ce4759 | diff --git a/rest_framework/viewsets.py b/rest_framework/viewsets.py
--- a/rest_framework/viewsets.py
+++ b/rest_framework/viewsets.py
@@ -150,6 +150,11 @@ def reverse_action(self, url_name, *args, **kwargs):
Reverse the action for the given `url_name`.
"""
url_name = '%s-%s' % (self.basename, url_name)
+ namespace = None
+ if self.request and self.request.resolver_match:
+ namespace = self.request.resolver_match.namespace
+ if namespace:
+ url_name = namespace + ':' + url_name
kwargs.setdefault('request', self.request)
return reverse(url_name, *args, **kwargs)
| "Action" button does not render in API if `app_name` is set
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
In `api_views.py`:
```python
class SomeViewSet(viewsets.ModelViewSet):
queryset = ...
serializer_class = ...
@action(method=['POST'], detail=False, )
def some_action(self, request):
# ..
return Response("Hi")
```
In `api_urls.py`:
```python
from rest_framework import routers
from . import api_views
router = routers.DefaultRouter()
router.register(r'some_link', api_views.SomeViewSet)
```
in `urls.py`:
```python
from .api_urls import router
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include((router.urls, "api"))),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
```
## Expected behaviour
To see "Actions" button on http://127.0.0.1:8000/api/some_link/ page.
## Actual behaviour
The button is not there.
## How to fix
Remove app name in `urlpaths`; however, this breaks `{% url ... %}` syntax in Django templates.
| 2020-04-25T07:39:04 |
||
encode/django-rest-framework | 7,306 | encode__django-rest-framework-7306 | [
"7038"
] | 4349ce1a542a1b83f7e19979831bbc427f92ad55 | diff --git a/rest_framework/views.py b/rest_framework/views.py
--- a/rest_framework/views.py
+++ b/rest_framework/views.py
@@ -166,13 +166,13 @@ def http_method_not_allowed(self, request, *args, **kwargs):
"""
raise exceptions.MethodNotAllowed(request.method)
- def permission_denied(self, request, message=None):
+ def permission_denied(self, request, message=None, code=None):
"""
If request is not permitted, determine what kind of exception to raise.
"""
if request.authenticators and not request.successful_authenticator:
raise exceptions.NotAuthenticated()
- raise exceptions.PermissionDenied(detail=message)
+ raise exceptions.PermissionDenied(detail=message, code=code)
def throttled(self, request, wait):
"""
@@ -331,7 +331,9 @@ def check_permissions(self, request):
for permission in self.get_permissions():
if not permission.has_permission(request, self):
self.permission_denied(
- request, message=getattr(permission, 'message', None)
+ request,
+ message=getattr(permission, 'message', None),
+ code=getattr(permission, 'code', None)
)
def check_object_permissions(self, request, obj):
@@ -342,7 +344,9 @@ def check_object_permissions(self, request, obj):
for permission in self.get_permissions():
if not permission.has_object_permission(request, self, obj):
self.permission_denied(
- request, message=getattr(permission, 'message', None)
+ request,
+ message=getattr(permission, 'message', None),
+ code=getattr(permission, 'code', None)
)
def check_throttles(self, request):
| diff --git a/tests/test_permissions.py b/tests/test_permissions.py
--- a/tests/test_permissions.py
+++ b/tests/test_permissions.py
@@ -438,6 +438,7 @@ def has_permission(self, request, view):
class BasicPermWithDetail(permissions.BasePermission):
message = 'Custom: You cannot access this resource'
+ code = 'permission_denied_custom'
def has_permission(self, request, view):
return False
@@ -450,6 +451,7 @@ def has_object_permission(self, request, view, obj):
class BasicObjectPermWithDetail(permissions.BasePermission):
message = 'Custom: You cannot access this resource'
+ code = 'permission_denied_custom'
def has_object_permission(self, request, view, obj):
return False
@@ -492,30 +494,35 @@ def setUp(self):
credentials = basic_auth_header('username', 'password')
self.request = factory.get('/1', format='json', HTTP_AUTHORIZATION=credentials)
self.custom_message = 'Custom: You cannot access this resource'
+ self.custom_code = 'permission_denied_custom'
def test_permission_denied(self):
response = denied_view(self.request, pk=1)
detail = response.data.get('detail')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertNotEqual(detail, self.custom_message)
+ self.assertNotEqual(detail.code, self.custom_code)
def test_permission_denied_with_custom_detail(self):
response = denied_view_with_detail(self.request, pk=1)
detail = response.data.get('detail')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(detail, self.custom_message)
+ self.assertEqual(detail.code, self.custom_code)
def test_permission_denied_for_object(self):
response = denied_object_view(self.request, pk=1)
detail = response.data.get('detail')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertNotEqual(detail, self.custom_message)
+ self.assertNotEqual(detail.code, self.custom_code)
def test_permission_denied_for_object_with_custom_detail(self):
response = denied_object_view_with_detail(self.request, pk=1)
detail = response.data.get('detail')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(detail, self.custom_message)
+ self.assertEqual(detail.code, self.custom_code)
class PermissionsCompositionTests(TestCase):
| Permission also need code property
## Checklist
- [v ] I have verified that that issue exists against the `master` branch of Django REST framework.
- [ v] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [v] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [v] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [v] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
as you know, each permission_denied is not the same.
and maybe each permission_denied require different behavior.
so, DRF enables override the message of Permission.
but, when communicating with clients that are independent of Django.
(like SPA, Android, IOS)
i think code is better than a message.
because error handling is the client's responsibility.
so, Permission also needs to override code property.
| I think we'd probably consider a pull request adding support for an optional `code` associated with permissions, yup. | 2020-04-30T19:59:31 |
encode/django-rest-framework | 7,341 | encode__django-rest-framework-7341 | [
"6131"
] | acbd9d8222e763c7f9c7dc2de23c430c702e06d4 | diff --git a/rest_framework/authtoken/admin.py b/rest_framework/authtoken/admin.py
--- a/rest_framework/authtoken/admin.py
+++ b/rest_framework/authtoken/admin.py
@@ -1,10 +1,51 @@
from django.contrib import admin
+from django.contrib.admin.utils import quote
+from django.contrib.admin.views.main import ChangeList
+from django.contrib.auth import get_user_model
+from django.core.exceptions import ValidationError
+from django.urls import reverse
-from rest_framework.authtoken.models import Token
+from rest_framework.authtoken.models import Token, TokenProxy
+
+User = get_user_model()
+
+
+class TokenChangeList(ChangeList):
+ """Map to matching User id"""
+ def url_for_result(self, result):
+ pk = result.user.pk
+ return reverse('admin:%s_%s_change' % (self.opts.app_label,
+ self.opts.model_name),
+ args=(quote(pk),),
+ current_app=self.model_admin.admin_site.name)
[email protected](Token)
class TokenAdmin(admin.ModelAdmin):
list_display = ('key', 'user', 'created')
fields = ('user',)
ordering = ('-created',)
+ actions = None # Actions not compatible with mapped IDs.
+
+ def get_changelist(self, request, **kwargs):
+ return TokenChangeList
+
+ def get_object(self, request, object_id, from_field=None):
+ """
+ Map from User ID to matching Token.
+ """
+ queryset = self.get_queryset(request)
+ field = User._meta.pk
+ try:
+ object_id = field.to_python(object_id)
+ user = User.objects.get(**{field.name: object_id})
+ return queryset.get(user=user)
+ except (queryset.model.DoesNotExist, User.DoesNotExist, ValidationError, ValueError):
+ return None
+
+ def delete_model(self, request, obj):
+ # Map back to actual Token, since delete() uses pk.
+ token = Token.objects.get(key=obj.key)
+ return super().delete_model(request, token)
+
+
+admin.site.register(TokenProxy, TokenAdmin)
diff --git a/rest_framework/authtoken/models.py b/rest_framework/authtoken/models.py
--- a/rest_framework/authtoken/models.py
+++ b/rest_framework/authtoken/models.py
@@ -37,3 +37,16 @@ def generate_key(self):
def __str__(self):
return self.key
+
+
+class TokenProxy(Token):
+ """
+ Proxy mapping pk to user pk for use in admin.
+ """
+ @property
+ def pk(self):
+ return self.user.pk
+
+ class Meta:
+ proxy = True
+ verbose_name = "token"
| Token admin page leaks access tokens into log files
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Visit the change page for a [Token](https://github.com/encode/django-rest-framework/blob/90ed2c1ef7c652ce0a98075c422d25a632d62507/rest_framework/authtoken/models.py#L15) in Django admin. Since the primary key **is** the key, the key is used to reference the token in the URL. This leaks the auth token into access logs.
<img width="812" alt="drf-auth-token" src="https://user-images.githubusercontent.com/541083/44262770-8adafb80-a25f-11e8-98a9-2be4c8cc5963.png">
The access permissions for users with access to the admin page (high) and those with permissions to view logs (medium) are different.
## Expected behavior
Auth tokens should use an integer as the primary key that is used in urls and for foreign key references. The token value itself should be a non-keyed attribute with a unique index.
## Actual behavior
Primary key is the secret key material.
| OK. Yep. Not ideal.
The answer to token related questions has traditionally been that the supplied implementation is deliberately (over-)simple and that you should use a custom implementation if you need something more complex/better. (Bottom line here is that we've steered away from adding any more complexity here to keep the maintenance burden reasonable.)
> The access permissions for users with access to the admin page (high) and those with permissions to view logs (medium) are different.
I think this isn't true for people who would/should be using the supplied implementation in production.
(In those cases they'd be one and the same person.)
Not sure what others might say...
> The answer to token related questions has traditionally been that the supplied implementation is deliberately (over-)simple and that you should use a custom implementation if you need something more complex/better.
I get this position, but then the docs should **strongly** recommend users away from the built in implementation at a minimum, and deprecate at the extreme end of things. The 3rd party recommendation for token/signature auth is https://github.com/etoccalino/django-rest-framework-httpsignature which hasn't been updated in 3 years. I would imagine there'd be a lot more interest in 3rd party token providers if one wasn't provided out of the box.
This is a pretty serious information disclosure IMO, so I'm not sure the default position for authtoken is the right way to go in this case.
No. Which is why I didn’t close it...
Sorry if my response came off rougher than intended, that was not my goal.
No problems! 😃
(Wondering if we could just mung the ModelAdmin to use a hash of the key in the url...)
Sneaky, but that idea feels dangerous too, though I can't say why.
A migration should be able to handle the job. The tricky bit would be foreign keys in other tables, but that seems unlikely. DRF doesn't create FKs to Tokens, and I can't see many reasons that users would either.
I don't think I've tried to migrate primary key fields before, but I seem to remember there being an operation that handles it, and the corresponding foreign key updates too.
Yup. It’d need a data migration, but otherwise I guess easy enough to switch around.
Pull requests welcome. Thanks for the report!
Does the token need to necessarily be unique?
I understand the problem, but you should consider that depending on what migration you create (to solve this issue), you might cause many others issues (e.g., introducing a new PK field will most likely break some other packages that rely on the current behaviour).
I wonder if it is possible to add an auto-increment integer field on the token table which is used as a reference within the Django Admin Page for the Auth Token, but not as the Primary Key of the table?
----
FYI, I've just verified that I also have the same issue with my extended token implementation (see [django-rest-multitokenauth](https://github.com/anx-ckreuzberger/django-rest-multiauthtoken)) - so thanks for pointing that mistake in the Admin Panel out! I'm looking forward to see the solution here, so I can adapt my python package.
FYI, this is how I fixed it within my MultiTokenAuth package:
https://github.com/anx-ckreuzberger/django-rest-multiauthtoken/commit/7e11ed606271eff0693a9280f8a30349c7e90b27
I guess the same fix could be applied here, with the caveat of potentially breaking other peoples code if they have a foreign key to the token table
Hello,
I was just skimming through auth related issues before evaluating this library for an upcoming project. I have a simple question, would appreciate any help.
Can this issue be avoided by simply not registering the Token model in admin?
@raunaqss Yes, you don't need to register it.
Tho thanks for re-raising this.
Do we know which way we are going with this ?
Should we hash the url or migrate the pk ?
I can make a PR.
A migration will very likely be the sensible approach here.
I'm pretty wary about including a migration in the 3.11 release, since eg. it could be problematic/unexpected for folks with very large API key tables.
I think a sensible thing to do will probably be to start by releasing a migration to this seperately, so that we can make sure some folks are able to test it all out first *independently* of our releases.
Once we're happy with it all then we can consider including the migration directly.
Let's have a look at releasing a migration for this seperately, rather than pushing it in the 3.11 release itself. I'm too wary of implications for users with very large API key tables to push a migration on all our users in a major release.
This issue has been open for a long time, and, while it seems [@jarshwah's observation](https://github.com/encode/django-rest-framework/issues/6131#issuecomment-413846991) is addressed by [django-rest-knox](https://github.com/James1345/django-rest-knox), we probably want to be more secure by default. Even if drf's intention is for `TokenAuthentication` to be simple, many developers are bound to implement an insecure authentication mechanism. I'm not sure code that leaks secret material by design should be included out of the box.
Has any progress been made in resolving this issue? Is anyone open to taking up a bounty on the issue? I would be interested in contributing code or paying a bounty if so.
I'll prfioritize it for 3.12.
> I would be interested in contributing code
Very welcome to issue a PR for it, sure.
> I would be interested in contributing code or paying a bounty if so.
Becoming a sponsor is a good way to contribute. Sponsors have priority support and can esclate an issue if needed. https://fund.django-rest-framework.org/topics/funding/#corporate-plans
That all sounds great! I'm now a sponsor of drf and encode. I'll be sure to update this issue if/when I start work on a resolution.
Fantastic, thank you so much. 🙏
Okay, so it's *really* not obvious how to tackle this gracefully.
We'd really like the model to just use an auto incrementing int for the primary key, and have the "key" field be a standard unique, indexed field, but we can't migrate to that. So what are our options...
* We could introduce something like `rest_framework.authtoken2` and have the docs refer to that instead, so that new projects get a better set of defaults.
* We could continue to use the existing field as the PK, and add a new field for the actual token value. It's not clear if we could introduce a data migration copying the values across, as it might? be problematic for users with large existing data sets. This looks decent... https://stackoverflow.com/questions/41500811/copy-a-database-column-into-another-in-django We'd also need to be pretty careful about still correct behaviour for unmigrated codebases. If we were working on a deployed app we'd normally want to start by introducing the new field, and ensuring that we're writing the same values to both fields while *still* having the codebase refer to the old field for a period of time. And only once that's all deployed & sync'ed, introduce the code change switching to using the new field.
* We could continue as we are but introduce some admin changes.
Does anyone have any preliminary thoughts on this?
Also: This is why this one has been pending for so long - there's no easy answer to it. 😬 | 2020-05-17T14:34:29 |
|
encode/django-rest-framework | 7,385 | encode__django-rest-framework-7385 | [
"7384"
] | 28983cb28b5729fbf2c861747c59398c8da76ba9 | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -121,6 +121,10 @@ def __new__(cls, *args, **kwargs):
return cls.many_init(*args, **kwargs)
return super().__new__(cls, *args, **kwargs)
+ # Allow type checkers to make serializers generic.
+ def __class_getitem__(cls, *args, **kwargs):
+ return cls
+
@classmethod
def many_init(cls, *args, **kwargs):
"""
| diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -1,6 +1,7 @@
import inspect
import pickle
import re
+import sys
from collections import ChainMap
from collections.abc import Mapping
@@ -204,6 +205,13 @@ class ExampleSerializer(serializers.Serializer):
exceptions.ErrorDetail(string='Raised error', code='invalid')
]}
+ @pytest.mark.skipif(
+ sys.version_info < (3, 7),
+ reason="subscriptable classes requires Python 3.7 or higher",
+ )
+ def test_serializer_is_subscriptable(self):
+ assert serializers.Serializer is serializers.Serializer["foo"]
+
class TestValidateMethod:
def test_non_field_error_validate_method(self):
diff --git a/tests/test_serializer_lists.py b/tests/test_serializer_lists.py
--- a/tests/test_serializer_lists.py
+++ b/tests/test_serializer_lists.py
@@ -1,3 +1,5 @@
+import sys
+
import pytest
from django.http import QueryDict
from django.utils.datastructures import MultiValueDict
@@ -55,6 +57,13 @@ def test_validate_html_input(self):
assert serializer.is_valid()
assert serializer.validated_data == expected_output
+ @pytest.mark.skipif(
+ sys.version_info < (3, 7),
+ reason="subscriptable classes requires Python 3.7 or higher",
+ )
+ def test_list_serializer_is_subscriptable(self):
+ assert serializers.ListSerializer is serializers.ListSerializer["foo"]
+
class TestListSerializerContainingNestedSerializer:
"""
| Implement ModelSerializer.__class_getitem__
To allow type checking efforts to properly type the methods of `ModelSerializer` it needs to be made generic with regards to the model it serializes. Since django-rest-framework has chosen to not own any annotations themselves the only way to achieve that will be to implement `__class_getitem__`. Stub implementors can then make the class generic and calling `ModelSerializer[Author]` will not yield subscriptability errors at runtime.
Note that this is the unfortunate direction [Django has chosen as well](https://github.com/django/django/commit/578c03b276e435bcd3ce9eb17b81e85135c2d3f3).
[This is the relevant issue in djangorestframework-stubs](https://github.com/typeddjango/djangorestframework-stubs/issues/71) for reference.
[This is the relevant Python docs on generic classes.](https://docs.python.org/3/library/typing.html#user-defined-generic-types)
| 2020-06-21T22:07:05 |
|
encode/django-rest-framework | 7,389 | encode__django-rest-framework-7389 | [
"7204"
] | 19915d19170c48961cc4cb97d773c99cba11aff1 | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -554,7 +554,9 @@ def map_field_validators(self, field, schema):
if isinstance(v, URLValidator):
schema['format'] = 'uri'
if isinstance(v, RegexValidator):
- schema['pattern'] = v.regex.pattern
+ # In Python, the token \Z does what \z does in other engines.
+ # https://stackoverflow.com/questions/53283160
+ schema['pattern'] = v.regex.pattern.replace('\\Z', '\\z')
elif isinstance(v, MaxLengthValidator):
attr_name = 'maxLength'
if isinstance(field, serializers.ListField):
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -855,6 +855,7 @@ def test_serializer_validators(self):
assert properties['url']['type'] == 'string'
assert properties['url']['nullable'] is True
assert properties['url']['default'] == 'http://www.example.com'
+ assert '\\Z' not in properties['url']['pattern']
assert properties['uuid']['type'] == 'string'
assert properties['uuid']['format'] == 'uuid'
| Error mapping Python regex to OpenAPI.
## Checklist
- [ v ] I have verified that that issue exists against the `master` branch of Django REST framework.
- [ v ] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [ v ] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [ x ] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [ v ] I have reduced the issue to the simplest possible case.
- [ x ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Use `URLField` in model and use openapi schema generator. Then copy-paste generated JSON to editor.swagger.io
## Expected behavior
Regexp should be valid for openapi.
## Actual behavior
Regexp is invalid.

```yml
pattern: "^(?:[a-z0-9\\.\\-\\+]*)://(?:[^\\s:@/]+(?::[^\\s:@/]*)?@)?(?:(?:25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}|\\[[0-9a-f:\\.]+\\]|([a-z¡-\uFFFF0-9](?:[a-z¡-\uFFFF0-9-]{0,61}[a-z¡-\uFFFF0-9])?(?:\\.(?!-)[a-z¡-\uFFFF0-9-]{1,63}(?<!-))*\\.(?!-)(?:[a-z¡-\uFFFF-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\.?|localhost))(?::\\d{2,5})?(?:[/?#][^\\s]*)?\\Z"
```
| The regex comes straight off the validator, which we attach in `map_field_validators()`. It's a good regex, so why isn't it acceptable to the Swagger validator?
I can only find one match for "regex" in [the spec](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md).
So..
1. What's the required regex format?
2. Is there any way of mapping to that from the validator?
3. If not, do we need to skip adding the `pattern` for all cases, or can we identify a subset?
@carltongibson I found the root cause of this problem.
Swagger Editor does not allow regex to be wrapped in `"`(double-quotes). It must be wrapped in `'`(single-quotes).
For example:
pattern: '^(\d+\.)?(\d+\.)?(\*|\d+)$' => No error
pattern: ^(\d+\.)?(\d+\.)?(\*|\d+)$ => No error
pattern: "^(\d+\.)?(\d+\.)?(\*|\d+)$" => **Error**
I also found that pyyaml wraps it in `"`. Also, not all regex are wrapped like this. Checkout: https://i.pinimg.com/originals/76/d9/52/76d952bf3c40d001dbdcb39c65f3c4f1.png
Hi @dhaval-mehta. Nice.
So two questions:
> Swagger Editor does not allow regex to be wrapped in "(double-quotes). It must be wrapped in '(single-quotes).
Is that a reasonable restriction? What do the Swagger folks say about that?
> I also found that pyyaml wraps it in ". Also, not all regex are wrapped like this.
What do the pyyaml folks say about that?
I'm not seeing anything we can action as yet... 🤔 | 2020-06-24T10:47:27 |
encode/django-rest-framework | 7,434 | encode__django-rest-framework-7434 | [
"6131"
] | 599e2b183db846a632b1efd148e6bc97d926ee5c | diff --git a/rest_framework/authtoken/admin.py b/rest_framework/authtoken/admin.py
--- a/rest_framework/authtoken/admin.py
+++ b/rest_framework/authtoken/admin.py
@@ -1,10 +1,51 @@
from django.contrib import admin
+from django.contrib.admin.utils import quote
+from django.contrib.admin.views.main import ChangeList
+from django.contrib.auth import get_user_model
+from django.core.exceptions import ValidationError
+from django.urls import reverse
-from rest_framework.authtoken.models import Token
+from rest_framework.authtoken.models import Token, TokenProxy
+
+User = get_user_model()
+
+
+class TokenChangeList(ChangeList):
+ """Map to matching User id"""
+ def url_for_result(self, result):
+ pk = result.user.pk
+ return reverse('admin:%s_%s_change' % (self.opts.app_label,
+ self.opts.model_name),
+ args=(quote(pk),),
+ current_app=self.model_admin.admin_site.name)
[email protected](Token)
class TokenAdmin(admin.ModelAdmin):
list_display = ('key', 'user', 'created')
fields = ('user',)
ordering = ('-created',)
+ actions = None # Actions not compatible with mapped IDs.
+
+ def get_changelist(self, request, **kwargs):
+ return TokenChangeList
+
+ def get_object(self, request, object_id, from_field=None):
+ """
+ Map from User ID to matching Token.
+ """
+ queryset = self.get_queryset(request)
+ field = User._meta.pk
+ try:
+ object_id = field.to_python(object_id)
+ user = User.objects.get(**{field.name: object_id})
+ return queryset.get(user=user)
+ except (queryset.model.DoesNotExist, User.DoesNotExist, ValidationError, ValueError):
+ return None
+
+ def delete_model(self, request, obj):
+ # Map back to actual Token, since delete() uses pk.
+ token = Token.objects.get(key=obj.key)
+ return super().delete_model(request, token)
+
+
+admin.site.register(TokenProxy, TokenAdmin)
diff --git a/rest_framework/authtoken/models.py b/rest_framework/authtoken/models.py
--- a/rest_framework/authtoken/models.py
+++ b/rest_framework/authtoken/models.py
@@ -37,3 +37,16 @@ def generate_key(self):
def __str__(self):
return self.key
+
+
+class TokenProxy(Token):
+ """
+ Proxy mapping pk to user pk for use in admin.
+ """
+ @property
+ def pk(self):
+ return self.user.pk
+
+ class Meta:
+ proxy = True
+ verbose_name = "token"
| Token admin page leaks access tokens into log files
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Visit the change page for a [Token](https://github.com/encode/django-rest-framework/blob/90ed2c1ef7c652ce0a98075c422d25a632d62507/rest_framework/authtoken/models.py#L15) in Django admin. Since the primary key **is** the key, the key is used to reference the token in the URL. This leaks the auth token into access logs.
<img width="812" alt="drf-auth-token" src="https://user-images.githubusercontent.com/541083/44262770-8adafb80-a25f-11e8-98a9-2be4c8cc5963.png">
The access permissions for users with access to the admin page (high) and those with permissions to view logs (medium) are different.
## Expected behavior
Auth tokens should use an integer as the primary key that is used in urls and for foreign key references. The token value itself should be a non-keyed attribute with a unique index.
## Actual behavior
Primary key is the secret key material.
| OK. Yep. Not ideal.
The answer to token related questions has traditionally been that the supplied implementation is deliberately (over-)simple and that you should use a custom implementation if you need something more complex/better. (Bottom line here is that we've steered away from adding any more complexity here to keep the maintenance burden reasonable.)
> The access permissions for users with access to the admin page (high) and those with permissions to view logs (medium) are different.
I think this isn't true for people who would/should be using the supplied implementation in production.
(In those cases they'd be one and the same person.)
Not sure what others might say...
> The answer to token related questions has traditionally been that the supplied implementation is deliberately (over-)simple and that you should use a custom implementation if you need something more complex/better.
I get this position, but then the docs should **strongly** recommend users away from the built in implementation at a minimum, and deprecate at the extreme end of things. The 3rd party recommendation for token/signature auth is https://github.com/etoccalino/django-rest-framework-httpsignature which hasn't been updated in 3 years. I would imagine there'd be a lot more interest in 3rd party token providers if one wasn't provided out of the box.
This is a pretty serious information disclosure IMO, so I'm not sure the default position for authtoken is the right way to go in this case.
No. Which is why I didn’t close it...
Sorry if my response came off rougher than intended, that was not my goal.
No problems! 😃
(Wondering if we could just mung the ModelAdmin to use a hash of the key in the url...)
Sneaky, but that idea feels dangerous too, though I can't say why.
A migration should be able to handle the job. The tricky bit would be foreign keys in other tables, but that seems unlikely. DRF doesn't create FKs to Tokens, and I can't see many reasons that users would either.
I don't think I've tried to migrate primary key fields before, but I seem to remember there being an operation that handles it, and the corresponding foreign key updates too.
Yup. It’d need a data migration, but otherwise I guess easy enough to switch around.
Pull requests welcome. Thanks for the report!
Does the token need to necessarily be unique?
I understand the problem, but you should consider that depending on what migration you create (to solve this issue), you might cause many others issues (e.g., introducing a new PK field will most likely break some other packages that rely on the current behaviour).
I wonder if it is possible to add an auto-increment integer field on the token table which is used as a reference within the Django Admin Page for the Auth Token, but not as the Primary Key of the table?
----
FYI, I've just verified that I also have the same issue with my extended token implementation (see [django-rest-multitokenauth](https://github.com/anx-ckreuzberger/django-rest-multiauthtoken)) - so thanks for pointing that mistake in the Admin Panel out! I'm looking forward to see the solution here, so I can adapt my python package.
FYI, this is how I fixed it within my MultiTokenAuth package:
https://github.com/anx-ckreuzberger/django-rest-multiauthtoken/commit/7e11ed606271eff0693a9280f8a30349c7e90b27
I guess the same fix could be applied here, with the caveat of potentially breaking other peoples code if they have a foreign key to the token table
Hello,
I was just skimming through auth related issues before evaluating this library for an upcoming project. I have a simple question, would appreciate any help.
Can this issue be avoided by simply not registering the Token model in admin?
@raunaqss Yes, you don't need to register it.
Tho thanks for re-raising this.
Do we know which way we are going with this ?
Should we hash the url or migrate the pk ?
I can make a PR.
A migration will very likely be the sensible approach here.
I'm pretty wary about including a migration in the 3.11 release, since eg. it could be problematic/unexpected for folks with very large API key tables.
I think a sensible thing to do will probably be to start by releasing a migration to this seperately, so that we can make sure some folks are able to test it all out first *independently* of our releases.
Once we're happy with it all then we can consider including the migration directly.
Let's have a look at releasing a migration for this seperately, rather than pushing it in the 3.11 release itself. I'm too wary of implications for users with very large API key tables to push a migration on all our users in a major release.
This issue has been open for a long time, and, while it seems [@jarshwah's observation](https://github.com/encode/django-rest-framework/issues/6131#issuecomment-413846991) is addressed by [django-rest-knox](https://github.com/James1345/django-rest-knox), we probably want to be more secure by default. Even if drf's intention is for `TokenAuthentication` to be simple, many developers are bound to implement an insecure authentication mechanism. I'm not sure code that leaks secret material by design should be included out of the box.
Has any progress been made in resolving this issue? Is anyone open to taking up a bounty on the issue? I would be interested in contributing code or paying a bounty if so.
I'll prfioritize it for 3.12.
> I would be interested in contributing code
Very welcome to issue a PR for it, sure.
> I would be interested in contributing code or paying a bounty if so.
Becoming a sponsor is a good way to contribute. Sponsors have priority support and can esclate an issue if needed. https://fund.django-rest-framework.org/topics/funding/#corporate-plans
That all sounds great! I'm now a sponsor of drf and encode. I'll be sure to update this issue if/when I start work on a resolution.
Fantastic, thank you so much. 🙏
Okay, so it's *really* not obvious how to tackle this gracefully.
We'd really like the model to just use an auto incrementing int for the primary key, and have the "key" field be a standard unique, indexed field, but we can't migrate to that. So what are our options...
* We could introduce something like `rest_framework.authtoken2` and have the docs refer to that instead, so that new projects get a better set of defaults.
* We could continue to use the existing field as the PK, and add a new field for the actual token value. It's not clear if we could introduce a data migration copying the values across, as it might? be problematic for users with large existing data sets. This looks decent... https://stackoverflow.com/questions/41500811/copy-a-database-column-into-another-in-django We'd also need to be pretty careful about still correct behaviour for unmigrated codebases. If we were working on a deployed app we'd normally want to start by introducing the new field, and ensuring that we're writing the same values to both fields while *still* having the codebase refer to the old field for a period of time. And only once that's all deployed & sync'ed, introduce the code change switching to using the new field.
* We could continue as we are but introduce some admin changes.
Does anyone have any preliminary thoughts on this?
Also: This is why this one has been pending for so long - there's no easy answer to it. 😬 | 2020-07-29T13:51:45 |
|
encode/django-rest-framework | 7,467 | encode__django-rest-framework-7467 | [
"7466"
] | 374c0d414237708a28eccc412c078c06d0d82be2 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1758,6 +1758,7 @@ class JSONField(Field):
def __init__(self, *args, **kwargs):
self.binary = kwargs.pop('binary', False)
self.encoder = kwargs.pop('encoder', None)
+ self.decoder = kwargs.pop('decoder', None)
super().__init__(*args, **kwargs)
def get_value(self, dictionary):
@@ -1777,7 +1778,7 @@ def to_internal_value(self, data):
if self.binary or getattr(data, 'is_json_string', False):
if isinstance(data, bytes):
data = data.decode()
- return json.loads(data)
+ return json.loads(data, cls=self.decoder)
else:
json.dumps(data, cls=self.encoder)
except (TypeError, ValueError):
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -884,6 +884,8 @@ class ModelSerializer(Serializer):
models.GenericIPAddressField: IPAddressField,
models.FilePathField: FilePathField,
}
+ if hasattr(models, 'JSONField'):
+ serializer_field_mapping[models.JSONField] = JSONField
if postgres_fields:
serializer_field_mapping[postgres_fields.HStoreField] = HStoreField
serializer_field_mapping[postgres_fields.ArrayField] = ListField
@@ -1242,10 +1244,13 @@ def build_standard_field(self, field_name, model_field):
# `allow_blank` is only valid for textual fields.
field_kwargs.pop('allow_blank', None)
- if postgres_fields and isinstance(model_field, postgres_fields.JSONField):
+ is_django_jsonfield = hasattr(models, 'JSONField') and isinstance(model_field, models.JSONField)
+ if (postgres_fields and isinstance(model_field, postgres_fields.JSONField)) or is_django_jsonfield:
# Populate the `encoder` argument of `JSONField` instances generated
- # for the PostgreSQL specific `JSONField`.
+ # for the model `JSONField`.
field_kwargs['encoder'] = getattr(model_field, 'encoder', None)
+ if is_django_jsonfield:
+ field_kwargs['decoder'] = getattr(model_field, 'decoder', None)
if postgres_fields and isinstance(model_field, postgres_fields.ArrayField):
# Populate the `child` argument on `ListField` instances generated
diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py
--- a/rest_framework/utils/field_mapping.py
+++ b/rest_framework/utils/field_mapping.py
@@ -92,7 +92,8 @@ def get_field_kwargs(field_name, model_field):
kwargs['allow_unicode'] = model_field.allow_unicode
if isinstance(model_field, models.TextField) and not model_field.choices or \
- (postgres_fields and isinstance(model_field, postgres_fields.JSONField)):
+ (postgres_fields and isinstance(model_field, postgres_fields.JSONField)) or \
+ (hasattr(models, 'JSONField') and isinstance(model_field, models.JSONField)):
kwargs['style'] = {'base_template': 'textarea.html'}
if isinstance(model_field, models.AutoField) or not model_field.editable:
| diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py
--- a/tests/test_model_serializer.py
+++ b/tests/test_model_serializer.py
@@ -7,6 +7,7 @@
"""
import datetime
import decimal
+import json # noqa
import sys
import tempfile
from collections import OrderedDict
@@ -478,6 +479,7 @@ class Meta:
""")
self.assertEqual(repr(TestSerializer()), expected)
+ @pytest.mark.skipif(hasattr(models, 'JSONField'), reason='has models.JSONField')
def test_json_field(self):
class JSONFieldModel(models.Model):
json_field = postgres_fields.JSONField()
@@ -496,6 +498,30 @@ class Meta:
self.assertEqual(repr(TestSerializer()), expected)
+class CustomJSONDecoder(json.JSONDecoder):
+ pass
+
+
[email protected](not hasattr(models, 'JSONField'), reason='no models.JSONField')
+class TestDjangoJSONFieldMapping(TestCase):
+ def test_json_field(self):
+ class JSONFieldModel(models.Model):
+ json_field = models.JSONField()
+ json_field_with_encoder = models.JSONField(encoder=DjangoJSONEncoder, decoder=CustomJSONDecoder)
+
+ class TestSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = JSONFieldModel
+ fields = ['json_field', 'json_field_with_encoder']
+
+ expected = dedent("""
+ TestSerializer():
+ json_field = JSONField(decoder=None, encoder=None, style={'base_template': 'textarea.html'})
+ json_field_with_encoder = JSONField(decoder=<class 'tests.test_model_serializer.CustomJSONDecoder'>, encoder=<class 'django.core.serializers.json.DjangoJSONEncoder'>, style={'base_template': 'textarea.html'})
+ """)
+ self.assertEqual(repr(TestSerializer()), expected)
+
+
# Tests for relational field mappings.
# ------------------------------------
| ModelSerializer Missing support for Django 3.1 JSONField
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Django 3.1 includes a new generic JSONField to replace the PostgreSQL-specific one:
https://docs.djangoproject.com/en/3.1/releases/3.1/#jsonfield-for-all-supported-database-backends
This is missing in ModelSerializer's field mapping, so a `django.db.models.JSONField` does not get mapped to a JSONField in the serializer.
## Expected behavior
The serializer behaves the same as when using the postgresql version of the field.
## Actual behavior
The new field type is treated as a text field (including schema generation, etc)
| Yes, this will need updating (but it should be straightforward I'm thinking 🤔)
Would be a good PR. | 2020-08-05T19:25:21 |
encode/django-rest-framework | 7,497 | encode__django-rest-framework-7497 | [
"7477"
] | eff97efa283529c6503b9ebde6506691cecb17a2 | diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -595,7 +595,7 @@ def map_renderers(self, path, method):
media_types = []
for renderer in self.view.renderer_classes:
# BrowsableAPIRenderer not relevant to OpenAPI spec
- if renderer == renderers.BrowsableAPIRenderer:
+ if issubclass(renderer, renderers.BrowsableAPIRenderer):
continue
media_types.append(renderer.media_type)
return media_types
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -10,7 +10,9 @@
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.compat import uritemplate
from rest_framework.parsers import JSONParser, MultiPartParser
-from rest_framework.renderers import JSONRenderer, OpenAPIRenderer
+from rest_framework.renderers import (
+ BaseRenderer, BrowsableAPIRenderer, JSONRenderer, OpenAPIRenderer
+)
from rest_framework.request import Request
from rest_framework.schemas.openapi import AutoSchema, SchemaGenerator
@@ -507,9 +509,16 @@ def test_renderer_mapping(self):
path = '/{id}/'
method = 'GET'
+ class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
+ media_type = 'image/jpeg' # that's a wild API renderer
+
+ class TextRenderer(BaseRenderer):
+ media_type = 'text/plain'
+ format = 'text'
+
class View(generics.CreateAPIView):
serializer_class = views.ExampleSerializer
- renderer_classes = [JSONRenderer]
+ renderer_classes = [JSONRenderer, TextRenderer, BrowsableAPIRenderer, CustomBrowsableAPIRenderer]
view = create_view(
View,
@@ -524,8 +533,8 @@ class View(generics.CreateAPIView):
# schema support is there
success_response = responses['200']
- assert len(success_response['content'].keys()) == 1
- assert 'application/json' in success_response['content']
+ # Check that the API renderers aren't included, but custom renderers are
+ assert set(success_response['content']) == {'application/json', 'text/plain'}
def test_openapi_yaml_rendering_without_aliases(self):
renderer = OpenAPIRenderer()
| Subclasses of BrowsableAPIRenderer should not be output in schema
https://github.com/encode/django-rest-framework/blob/5ce237e00471d885f05e6d979ec777552809b3b1/rest_framework/schemas/openapi.py#L598
A popular library djangorestframework-camel-case defines a subclass of BrowsableAPIRenderer called CamelCaseBrowsableAPIRenderer. This equality check should use issubclass() to determine type hierarchy as opposed to a strict equality comparison of types.
| Hi @jordmantheman. Thanks for the report. Yes, that sounds reasonable. A PR would be very timely there.
There's a `test_renderer_mapping` that could be fleshed out. I'd suggest ensure that neither the base class, nor any subclasses are included. :+1: | 2020-08-26T13:44:10 |
encode/django-rest-framework | 7,512 | encode__django-rest-framework-7512 | [
"7406"
] | 9990b5928139072c8e010c8b5c86616f0d40ef9d | diff --git a/rest_framework/urls.py b/rest_framework/urls.py
--- a/rest_framework/urls.py
+++ b/rest_framework/urls.py
@@ -6,7 +6,7 @@
urlpatterns = [
...
- url(r'^auth/', include('rest_framework.urls'))
+ path('auth/', include('rest_framework.urls'))
]
You should make sure your authentication settings include `SessionAuthentication`.
diff --git a/rest_framework/versioning.py b/rest_framework/versioning.py
--- a/rest_framework/versioning.py
+++ b/rest_framework/versioning.py
@@ -60,8 +60,8 @@ class URLPathVersioning(BaseVersioning):
An example URL conf for two views that accept two different versions.
urlpatterns = [
- url(r'^(?P<version>[v1|v2]+)/users/$', users_list, name='users-list'),
- url(r'^(?P<version>[v1|v2]+)/users/(?P<pk>[0-9]+)/$', users_detail, name='users-detail')
+ re_path(r'^(?P<version>[v1|v2]+)/users/$', users_list, name='users-list'),
+ re_path(r'^(?P<version>[v1|v2]+)/users/(?P<pk>[0-9]+)/$', users_detail, name='users-detail')
]
GET /1.0/something/ HTTP/1.1
@@ -99,14 +99,14 @@ class NamespaceVersioning(BaseVersioning):
# users/urls.py
urlpatterns = [
- url(r'^/users/$', users_list, name='users-list'),
- url(r'^/users/(?P<pk>[0-9]+)/$', users_detail, name='users-detail')
+ path('/users/', users_list, name='users-list'),
+ path('/users/<int:pk>/', users_detail, name='users-detail')
]
# urls.py
urlpatterns = [
- url(r'^v1/', include('users.urls', namespace='v1')),
- url(r'^v2/', include('users.urls', namespace='v2'))
+ path('v1/', include('users.urls', namespace='v1')),
+ path('v2/', include('users.urls', namespace='v2'))
]
GET /1.0/something/ HTTP/1.1
| diff --git a/tests/authentication/test_authentication.py b/tests/authentication/test_authentication.py
--- a/tests/authentication/test_authentication.py
+++ b/tests/authentication/test_authentication.py
@@ -2,10 +2,10 @@
import pytest
from django.conf import settings
-from django.conf.urls import include, url
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.test import TestCase, override_settings
+from django.urls import include, path
from rest_framework import (
HTTP_HEADER_ENCODING, exceptions, permissions, renderers, status
@@ -47,34 +47,34 @@ def put(self, request):
urlpatterns = [
- url(
- r'^session/$',
+ path(
+ 'session/',
MockView.as_view(authentication_classes=[SessionAuthentication])
),
- url(
- r'^basic/$',
+ path(
+ 'basic/',
MockView.as_view(authentication_classes=[BasicAuthentication])
),
- url(
- r'^remote-user/$',
+ path(
+ 'remote-user/',
MockView.as_view(authentication_classes=[RemoteUserAuthentication])
),
- url(
- r'^token/$',
+ path(
+ 'token/',
MockView.as_view(authentication_classes=[TokenAuthentication])
),
- url(
- r'^customtoken/$',
+ path(
+ 'customtoken/',
MockView.as_view(authentication_classes=[CustomTokenAuthentication])
),
- url(
- r'^customkeywordtoken/$',
+ path(
+ 'customkeywordtoken/',
MockView.as_view(
authentication_classes=[CustomKeywordTokenAuthentication]
)
),
- url(r'^auth-token/$', obtain_auth_token),
- url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')),
+ path('auth-token/', obtain_auth_token),
+ path('auth/', include('rest_framework.urls', namespace='rest_framework')),
]
diff --git a/tests/browsable_api/auth_urls.py b/tests/browsable_api/auth_urls.py
--- a/tests/browsable_api/auth_urls.py
+++ b/tests/browsable_api/auth_urls.py
@@ -1,8 +1,8 @@
-from django.conf.urls import include, url
+from django.urls import include, path
from .views import MockView
urlpatterns = [
- url(r'^$', MockView.as_view()),
- url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')),
+ path('', MockView.as_view()),
+ path('auth/', include('rest_framework.urls', namespace='rest_framework')),
]
diff --git a/tests/browsable_api/no_auth_urls.py b/tests/browsable_api/no_auth_urls.py
--- a/tests/browsable_api/no_auth_urls.py
+++ b/tests/browsable_api/no_auth_urls.py
@@ -1,7 +1,7 @@
-from django.conf.urls import url
+from django.urls import path
from .views import MockView
urlpatterns = [
- url(r'^$', MockView.as_view()),
+ path('', MockView.as_view()),
]
diff --git a/tests/browsable_api/test_browsable_nested_api.py b/tests/browsable_api/test_browsable_nested_api.py
--- a/tests/browsable_api/test_browsable_nested_api.py
+++ b/tests/browsable_api/test_browsable_nested_api.py
@@ -1,6 +1,6 @@
-from django.conf.urls import url
from django.test import TestCase
from django.test.utils import override_settings
+from django.urls import path
from rest_framework import serializers
from rest_framework.generics import ListCreateAPIView
@@ -23,7 +23,7 @@ class NestedSerializersView(ListCreateAPIView):
urlpatterns = [
- url(r'^api/$', NestedSerializersView.as_view(), name='api'),
+ path('api/', NestedSerializersView.as_view(), name='api'),
]
diff --git a/tests/schemas/test_coreapi.py b/tests/schemas/test_coreapi.py
--- a/tests/schemas/test_coreapi.py
+++ b/tests/schemas/test_coreapi.py
@@ -1,11 +1,10 @@
import unittest
import pytest
-from django.conf.urls import include, url
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.test import TestCase, override_settings
-from django.urls import path
+from django.urls import include, path
from rest_framework import (
filters, generics, pagination, permissions, serializers
@@ -145,8 +144,8 @@ def schema_view(request):
router = DefaultRouter()
router.register('example', ExampleViewSet, basename='example')
urlpatterns = [
- url(r'^$', schema_view),
- url(r'^', include(router.urls))
+ path('', schema_view),
+ path('', include(router.urls))
]
@@ -407,9 +406,9 @@ def get(self, *args, **kwargs):
class TestSchemaGenerator(TestCase):
def setUp(self):
self.patterns = [
- url(r'^example/?$', views.ExampleListView.as_view()),
- url(r'^example/(?P<pk>\d+)/?$', views.ExampleDetailView.as_view()),
- url(r'^example/(?P<pk>\d+)/sub/?$', views.ExampleDetailView.as_view()),
+ path('example/', views.ExampleListView.as_view()),
+ path('example/<int:pk>/', views.ExampleDetailView.as_view()),
+ path('example/<int:pk>/sub/', views.ExampleDetailView.as_view()),
]
def test_schema_for_regular_views(self):
@@ -513,9 +512,9 @@ def test_schema_for_regular_views(self):
class TestSchemaGeneratorNotAtRoot(TestCase):
def setUp(self):
self.patterns = [
- url(r'^api/v1/example/?$', views.ExampleListView.as_view()),
- url(r'^api/v1/example/(?P<pk>\d+)/?$', views.ExampleDetailView.as_view()),
- url(r'^api/v1/example/(?P<pk>\d+)/sub/?$', views.ExampleDetailView.as_view()),
+ path('api/v1/example/', views.ExampleListView.as_view()),
+ path('api/v1/example/<int:pk>/', views.ExampleDetailView.as_view()),
+ path('api/v1/example/<int:pk>/sub/', views.ExampleDetailView.as_view()),
]
def test_schema_for_regular_views(self):
@@ -569,7 +568,7 @@ def setUp(self):
router = DefaultRouter()
router.register('example1', MethodLimitedViewSet, basename='example1')
self.patterns = [
- url(r'^', include(router.urls))
+ path('', include(router.urls))
]
def test_schema_for_regular_views(self):
@@ -635,8 +634,8 @@ def setUp(self):
router.register('example1', Http404ExampleViewSet, basename='example1')
router.register('example2', PermissionDeniedExampleViewSet, basename='example2')
self.patterns = [
- url('^example/?$', views.ExampleListView.as_view()),
- url(r'^', include(router.urls))
+ path('example/', views.ExampleListView.as_view()),
+ path('', include(router.urls))
]
def test_schema_for_regular_views(self):
@@ -679,7 +678,7 @@ class ForeignKeySourceView(generics.CreateAPIView):
class TestSchemaGeneratorWithForeignKey(TestCase):
def setUp(self):
self.patterns = [
- url(r'^example/?$', ForeignKeySourceView.as_view()),
+ path('example/', ForeignKeySourceView.as_view()),
]
def test_schema_for_regular_views(self):
@@ -725,7 +724,7 @@ class ManyToManySourceView(generics.CreateAPIView):
class TestSchemaGeneratorWithManyToMany(TestCase):
def setUp(self):
self.patterns = [
- url(r'^example/?$', ManyToManySourceView.as_view()),
+ path('example/', ManyToManySourceView.as_view()),
]
def test_schema_for_regular_views(self):
@@ -1041,9 +1040,9 @@ def included_fbv(request):
class SchemaGenerationExclusionTests(TestCase):
def setUp(self):
self.patterns = [
- url('^excluded-cbv/$', ExcludedAPIView.as_view()),
- url('^excluded-fbv/$', excluded_fbv),
- url('^included-fbv/$', included_fbv),
+ path('excluded-cbv/', ExcludedAPIView.as_view()),
+ path('excluded-fbv/', excluded_fbv),
+ path('included-fbv/', included_fbv),
]
def test_schema_generator_excludes_correctly(self):
@@ -1136,8 +1135,8 @@ def simple_fbv(request):
pass
patterns = [
- url(r'^test', simple_fbv),
- url(r'^test/list/', simple_fbv),
+ path('test', simple_fbv),
+ path('test/list/', simple_fbv),
]
generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
@@ -1173,14 +1172,14 @@ def _verify_cbv_links(self, loc, url, methods=None, suffixes=None):
def test_manually_routing_generic_view(self):
patterns = [
- url(r'^test', NamingCollisionView.as_view()),
- url(r'^test/retrieve/', NamingCollisionView.as_view()),
- url(r'^test/update/', NamingCollisionView.as_view()),
+ path('test', NamingCollisionView.as_view()),
+ path('test/retrieve/', NamingCollisionView.as_view()),
+ path('test/update/', NamingCollisionView.as_view()),
# Fails with method names:
- url(r'^test/get/', NamingCollisionView.as_view()),
- url(r'^test/put/', NamingCollisionView.as_view()),
- url(r'^test/delete/', NamingCollisionView.as_view()),
+ path('test/get/', NamingCollisionView.as_view()),
+ path('test/put/', NamingCollisionView.as_view()),
+ path('test/delete/', NamingCollisionView.as_view()),
]
generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
@@ -1196,7 +1195,7 @@ def test_manually_routing_generic_view(self):
def test_from_router(self):
patterns = [
- url(r'from-router', include(naming_collisions_router.urls)),
+ path('from-router', include(naming_collisions_router.urls)),
]
generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
@@ -1228,8 +1227,8 @@ def test_from_router(self):
def test_url_under_same_key_not_replaced(self):
patterns = [
- url(r'example/(?P<pk>\d+)/$', BasicNamingCollisionView.as_view()),
- url(r'example/(?P<slug>\w+)/$', BasicNamingCollisionView.as_view()),
+ path('example/<int:pk>/', BasicNamingCollisionView.as_view()),
+ path('example/<str:slug>/', BasicNamingCollisionView.as_view()),
]
generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
@@ -1245,8 +1244,8 @@ def simple_fbv(request):
pass
patterns = [
- url(r'^test/list/', simple_fbv),
- url(r'^test/(?P<pk>\d+)/list/', simple_fbv),
+ path('test/list/', simple_fbv),
+ path('test/<int:pk>/list/', simple_fbv),
]
generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
diff --git a/tests/schemas/test_managementcommand.py b/tests/schemas/test_managementcommand.py
--- a/tests/schemas/test_managementcommand.py
+++ b/tests/schemas/test_managementcommand.py
@@ -3,10 +3,10 @@
import tempfile
import pytest
-from django.conf.urls import url
from django.core.management import call_command
from django.test import TestCase
from django.test.utils import override_settings
+from django.urls import path
from rest_framework.compat import uritemplate, yaml
from rest_framework.management.commands import generateschema
@@ -20,7 +20,7 @@ def get(self, request):
urlpatterns = [
- url(r'^$', FooView.as_view())
+ path('', FooView.as_view())
]
diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -2,8 +2,8 @@
import warnings
import pytest
-from django.conf.urls import url
from django.test import RequestFactory, TestCase, override_settings
+from django.urls import path
from django.utils.translation import gettext_lazy as _
from rest_framework import filters, generics, pagination, routers, serializers
@@ -719,8 +719,8 @@ def test_repeat_operation_ids(self):
def test_duplicate_operation_id(self):
patterns = [
- url(r'^duplicate1/?$', views.ExampleOperationIdDuplicate1.as_view()),
- url(r'^duplicate2/?$', views.ExampleOperationIdDuplicate2.as_view()),
+ path('duplicate1/', views.ExampleOperationIdDuplicate1.as_view()),
+ path('duplicate2/', views.ExampleOperationIdDuplicate2.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
@@ -874,7 +874,7 @@ class ExampleStringTagsViewSet(views.ExampleGenericAPIView):
schema = AutoSchema(tags=['example1', 'example2'])
url_patterns = [
- url(r'^test/?$', ExampleStringTagsViewSet.as_view()),
+ path('test/', ExampleStringTagsViewSet.as_view()),
]
generator = SchemaGenerator(patterns=url_patterns)
schema = generator.get_schema(request=create_request('/'))
@@ -911,8 +911,8 @@ class BranchAPIView(views.ExampleGenericAPIView):
pass
url_patterns = [
- url(r'^any-dash_underscore/?$', RestaurantAPIView.as_view()),
- url(r'^restaurants/branches/?$', BranchAPIView.as_view())
+ path('any-dash_underscore/', RestaurantAPIView.as_view()),
+ path('restaurants/branches/', BranchAPIView.as_view())
]
generator = SchemaGenerator(patterns=url_patterns)
schema = generator.get_schema(request=create_request('/'))
@@ -930,7 +930,7 @@ def test_override_settings(self):
def test_paths_construction(self):
"""Construction of the `paths` key."""
patterns = [
- url(r'^example/?$', views.ExampleListView.as_view()),
+ path('example/', views.ExampleListView.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
generator._initialise_endpoints()
@@ -946,8 +946,8 @@ def test_paths_construction(self):
def test_prefixed_paths_construction(self):
"""Construction of the `paths` key maintains a common prefix."""
patterns = [
- url(r'^v1/example/?$', views.ExampleListView.as_view()),
- url(r'^v1/example/{pk}/?$', views.ExampleDetailView.as_view()),
+ path('v1/example/', views.ExampleListView.as_view()),
+ path('v1/example/{pk}/', views.ExampleDetailView.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
generator._initialise_endpoints()
@@ -959,8 +959,8 @@ def test_prefixed_paths_construction(self):
def test_mount_url_prefixed_to_paths(self):
patterns = [
- url(r'^example/?$', views.ExampleListView.as_view()),
- url(r'^example/{pk}/?$', views.ExampleDetailView.as_view()),
+ path('example/', views.ExampleListView.as_view()),
+ path('example/{pk}/', views.ExampleDetailView.as_view()),
]
generator = SchemaGenerator(patterns=patterns, url='/api')
generator._initialise_endpoints()
@@ -973,7 +973,7 @@ def test_mount_url_prefixed_to_paths(self):
def test_schema_construction(self):
"""Construction of the top level dictionary."""
patterns = [
- url(r'^example/?$', views.ExampleListView.as_view()),
+ path('example/', views.ExampleListView.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
@@ -995,7 +995,7 @@ def test_schema_with_no_paths(self):
def test_schema_information(self):
"""Construction of the top level dictionary."""
patterns = [
- url(r'^example/?$', views.ExampleListView.as_view()),
+ path('example/', views.ExampleListView.as_view()),
]
generator = SchemaGenerator(patterns=patterns, title='My title', version='1.2.3', description='My description')
@@ -1009,7 +1009,7 @@ def test_schema_information(self):
def test_schema_information_empty(self):
"""Construction of the top level dictionary."""
patterns = [
- url(r'^example/?$', views.ExampleListView.as_view()),
+ path('example/', views.ExampleListView.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
@@ -1022,7 +1022,7 @@ def test_schema_information_empty(self):
def test_serializer_model(self):
"""Construction of the top level dictionary."""
patterns = [
- url(r'^example/?$', views.ExampleGenericAPIViewModel.as_view()),
+ path('example/', views.ExampleGenericAPIViewModel.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
@@ -1038,7 +1038,7 @@ def test_serializer_model(self):
def test_authtoken_serializer(self):
patterns = [
- url(r'^api-token-auth/', obtain_auth_token)
+ path('api-token-auth/', obtain_auth_token)
]
generator = SchemaGenerator(patterns=patterns)
@@ -1065,7 +1065,7 @@ def test_authtoken_serializer(self):
def test_component_name(self):
patterns = [
- url(r'^example/?$', views.ExampleAutoSchemaComponentName.as_view()),
+ path('example/', views.ExampleAutoSchemaComponentName.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
@@ -1080,8 +1080,8 @@ def test_component_name(self):
def test_duplicate_component_name(self):
patterns = [
- url(r'^duplicate1/?$', views.ExampleAutoSchemaDuplicate1.as_view()),
- url(r'^duplicate2/?$', views.ExampleAutoSchemaDuplicate2.as_view()),
+ path('duplicate1/', views.ExampleAutoSchemaDuplicate1.as_view()),
+ path('duplicate2/', views.ExampleAutoSchemaDuplicate2.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
@@ -1104,7 +1104,7 @@ class ExampleView(generics.DestroyAPIView):
schema = AutoSchema(operation_id_base='example')
url_patterns = [
- url(r'^example/?$', ExampleView.as_view()),
+ path('example/', ExampleView.as_view()),
]
generator = SchemaGenerator(patterns=url_patterns)
schema = generator.get_schema(request=create_request('/'))
diff --git a/tests/test_api_client.py b/tests/test_api_client.py
--- a/tests/test_api_client.py
+++ b/tests/test_api_client.py
@@ -2,9 +2,9 @@
import tempfile
import unittest
-from django.conf.urls import url
from django.http import HttpResponse
from django.test import override_settings
+from django.urls import path, re_path
from rest_framework.compat import coreapi, coreschema
from rest_framework.parsers import FileUploadParser
@@ -178,13 +178,13 @@ def get(self, request):
urlpatterns = [
- url(r'^$', SchemaView.as_view()),
- url(r'^example/$', ListView.as_view()),
- url(r'^example/(?P<id>[0-9]+)/$', DetailView.as_view()),
- url(r'^upload/$', UploadView.as_view()),
- url(r'^download/$', DownloadView.as_view()),
- url(r'^text/$', TextView.as_view()),
- url(r'^headers/$', HeadersView.as_view()),
+ path('', SchemaView.as_view()),
+ path('example/', ListView.as_view()),
+ re_path(r'^example/(?P<id>[0-9]+)/$', DetailView.as_view()),
+ path('upload/', UploadView.as_view()),
+ path('download/', DownloadView.as_view()),
+ path('text/', TextView.as_view()),
+ path('headers/', HeadersView.as_view()),
]
diff --git a/tests/test_atomic_requests.py b/tests/test_atomic_requests.py
--- a/tests/test_atomic_requests.py
+++ b/tests/test_atomic_requests.py
@@ -1,9 +1,9 @@
import unittest
-from django.conf.urls import url
from django.db import connection, connections, transaction
from django.http import Http404
from django.test import TestCase, TransactionTestCase, override_settings
+from django.urls import path
from rest_framework import status
from rest_framework.exceptions import APIException
@@ -44,7 +44,7 @@ def get(self, request, *args, **kwargs):
urlpatterns = (
- url(r'^$', NonAtomicAPIExceptionView.as_view()),
+ path('', NonAtomicAPIExceptionView.as_view()),
)
diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -697,7 +697,7 @@ class TestNullBooleanField(TestBooleanField):
None: None,
'other': True
}
- field = serializers.NullBooleanField()
+ field = serializers.BooleanField(allow_null=True)
class TestNullableBooleanField(TestNullBooleanField):
diff --git a/tests/test_htmlrenderer.py b/tests/test_htmlrenderer.py
--- a/tests/test_htmlrenderer.py
+++ b/tests/test_htmlrenderer.py
@@ -1,10 +1,10 @@
import django.template.loader
import pytest
-from django.conf.urls import url
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.http import Http404
from django.template import TemplateDoesNotExist, engines
from django.test import TestCase, override_settings
+from django.urls import path
from rest_framework import status
from rest_framework.decorators import api_view, renderer_classes
@@ -35,9 +35,9 @@ def not_found(request):
urlpatterns = [
- url(r'^$', example),
- url(r'^permission_denied$', permission_denied),
- url(r'^not_found$', not_found),
+ path('', example),
+ path('permission_denied', permission_denied),
+ path('not_found', not_found),
]
diff --git a/tests/test_lazy_hyperlinks.py b/tests/test_lazy_hyperlinks.py
--- a/tests/test_lazy_hyperlinks.py
+++ b/tests/test_lazy_hyperlinks.py
@@ -1,6 +1,6 @@
-from django.conf.urls import url
from django.db import models
from django.test import TestCase, override_settings
+from django.urls import path
from rest_framework import serializers
from rest_framework.renderers import JSONRenderer
@@ -29,7 +29,7 @@ def dummy_view(request):
urlpatterns = [
- url(r'^example/(?P<pk>[0-9]+)/$', dummy_view, name='example-detail'),
+ path('example/<int:pk>/', dummy_view, name='example-detail'),
]
diff --git a/tests/test_metadata.py b/tests/test_metadata.py
--- a/tests/test_metadata.py
+++ b/tests/test_metadata.py
@@ -311,7 +311,8 @@ class ExampleListSerializer(serializers.ListSerializer):
class TestSimpleMetadataFieldInfo(TestCase):
def test_null_boolean_field_info_type(self):
options = metadata.SimpleMetadata()
- field_info = options.get_field_info(serializers.NullBooleanField())
+ field_info = options.get_field_info(serializers.BooleanField(
+ allow_null=True))
assert field_info['type'] == 'boolean'
def test_related_field_choices(self):
diff --git a/tests/test_middleware.py b/tests/test_middleware.py
--- a/tests/test_middleware.py
+++ b/tests/test_middleware.py
@@ -1,7 +1,7 @@
-from django.conf.urls import url
from django.contrib.auth.models import User
from django.http import HttpRequest
from django.test import override_settings
+from django.urls import path
from rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.models import Token
@@ -17,8 +17,8 @@ def post(self, request):
urlpatterns = [
- url(r'^auth$', APIView.as_view(authentication_classes=(TokenAuthentication,))),
- url(r'^post$', PostView.as_view()),
+ path('auth', APIView.as_view(authentication_classes=(TokenAuthentication,))),
+ path('post', PostView.as_view()),
]
diff --git a/tests/test_relations.py b/tests/test_relations.py
--- a/tests/test_relations.py
+++ b/tests/test_relations.py
@@ -2,9 +2,9 @@
import pytest
from _pytest.monkeypatch import MonkeyPatch
-from django.conf.urls import url
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.test import override_settings
+from django.urls import re_path
from django.utils.datastructures import MultiValueDict
from rest_framework import relations, serializers
@@ -146,7 +146,7 @@ def test_pk_representation(self):
urlpatterns = [
- url(r'^example/(?P<name>.+)/$', lambda: None, name='example'),
+ re_path(r'^example/(?P<name>.+)/$', lambda: None, name='example'),
]
diff --git a/tests/test_relations_hyperlink.py b/tests/test_relations_hyperlink.py
--- a/tests/test_relations_hyperlink.py
+++ b/tests/test_relations_hyperlink.py
@@ -1,5 +1,5 @@
-from django.conf.urls import url
from django.test import TestCase, override_settings
+from django.urls import path
from rest_framework import serializers
from rest_framework.test import APIRequestFactory
@@ -17,14 +17,14 @@ def dummy_view(request, pk):
urlpatterns = [
- url(r'^dummyurl/(?P<pk>[0-9]+)/$', dummy_view, name='dummy-url'),
- url(r'^manytomanysource/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanysource-detail'),
- url(r'^manytomanytarget/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanytarget-detail'),
- url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'),
- url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'),
- url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'),
- url(r'^onetoonetarget/(?P<pk>[0-9]+)/$', dummy_view, name='onetoonetarget-detail'),
- url(r'^nullableonetoonesource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableonetoonesource-detail'),
+ path('dummyurl/<int:pk>/', dummy_view, name='dummy-url'),
+ path('manytomanysource/<int:pk>/', dummy_view, name='manytomanysource-detail'),
+ path('manytomanytarget/<int:pk>/', dummy_view, name='manytomanytarget-detail'),
+ path('foreignkeysource/<int:pk>/', dummy_view, name='foreignkeysource-detail'),
+ path('foreignkeytarget/<int:pk>/', dummy_view, name='foreignkeytarget-detail'),
+ path('nullableforeignkeysource/<int:pk>/', dummy_view, name='nullableforeignkeysource-detail'),
+ path('onetoonetarget/<int:pk>/', dummy_view, name='onetoonetarget-detail'),
+ path('nullableonetoonesource/<int:pk>/', dummy_view, name='nullableonetoonesource-detail'),
]
diff --git a/tests/test_renderers.py b/tests/test_renderers.py
--- a/tests/test_renderers.py
+++ b/tests/test_renderers.py
@@ -3,12 +3,12 @@
from collections.abc import MutableMapping
import pytest
-from django.conf.urls import include, url
from django.core.cache import cache
from django.db import models
from django.http.request import HttpRequest
from django.template import loader
from django.test import TestCase, override_settings
+from django.urls import include, path, re_path
from django.utils.safestring import SafeText
from django.utils.translation import gettext_lazy as _
@@ -111,14 +111,14 @@ def get(self, request, **kwargs):
urlpatterns = [
- url(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
- url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
- url(r'^cache$', MockGETView.as_view()),
- url(r'^parseerror$', MockPOSTView.as_view(renderer_classes=[JSONRenderer, BrowsableAPIRenderer])),
- url(r'^html$', HTMLView.as_view()),
- url(r'^html1$', HTMLView1.as_view()),
- url(r'^empty$', EmptyGETView.as_view()),
- url(r'^api', include('rest_framework.urls', namespace='rest_framework'))
+ re_path(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
+ path('', MockView.as_view(renderer_classes=[RendererA, RendererB])),
+ path('cache', MockGETView.as_view()),
+ path('parseerror', MockPOSTView.as_view(renderer_classes=[JSONRenderer, BrowsableAPIRenderer])),
+ path('html', HTMLView.as_view()),
+ path('html1', HTMLView1.as_view()),
+ path('empty', EmptyGETView.as_view()),
+ path('api', include('rest_framework.urls', namespace='rest_framework'))
]
@@ -637,7 +637,7 @@ class AuthExampleViewSet(ExampleViewSet):
router = SimpleRouter()
router.register('examples', ExampleViewSet, basename='example')
router.register('auth-examples', AuthExampleViewSet, basename='auth-example')
- urlpatterns = [url(r'^api/', include(router.urls))]
+ urlpatterns = [path('api/', include(router.urls))]
def setUp(self):
self.renderer = BrowsableAPIRenderer()
diff --git a/tests/test_request.py b/tests/test_request.py
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -5,7 +5,6 @@
import tempfile
import pytest
-from django.conf.urls import url
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.contrib.auth.models import User
@@ -13,6 +12,7 @@
from django.core.files.uploadedfile import SimpleUploadedFile
from django.http.request import RawPostDataException
from django.test import TestCase, override_settings
+from django.urls import path
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
@@ -153,9 +153,9 @@ def post(self, request):
urlpatterns = [
- url(r'^$', MockView.as_view()),
- url(r'^echo/$', EchoView.as_view()),
- url(r'^upload/$', FileUploadView.as_view())
+ path('', MockView.as_view()),
+ path('echo/', EchoView.as_view()),
+ path('upload/', FileUploadView.as_view())
]
diff --git a/tests/test_requests_client.py b/tests/test_requests_client.py
--- a/tests/test_requests_client.py
+++ b/tests/test_requests_client.py
@@ -1,10 +1,10 @@
import unittest
-from django.conf.urls import url
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.shortcuts import redirect
from django.test import override_settings
+from django.urls import path
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
@@ -90,10 +90,10 @@ def post(self, request):
urlpatterns = [
- url(r'^$', Root.as_view(), name='root'),
- url(r'^headers/$', HeadersView.as_view(), name='headers'),
- url(r'^session/$', SessionView.as_view(), name='session'),
- url(r'^auth/$', AuthView.as_view(), name='auth'),
+ path('', Root.as_view(), name='root'),
+ path('headers/', HeadersView.as_view(), name='headers'),
+ path('session/', SessionView.as_view(), name='session'),
+ path('auth/', AuthView.as_view(), name='auth'),
]
diff --git a/tests/test_response.py b/tests/test_response.py
--- a/tests/test_response.py
+++ b/tests/test_response.py
@@ -1,5 +1,5 @@
-from django.conf.urls import include, url
from django.test import TestCase, override_settings
+from django.urls import include, path, re_path
from rest_framework import generics, routers, serializers, status, viewsets
from rest_framework.parsers import JSONParser
@@ -117,15 +117,15 @@ class HTMLNewModelView(generics.ListCreateAPIView):
urlpatterns = [
- url(r'^setbyview$', MockViewSettingContentType.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
- url(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
- url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
- url(r'^html$', HTMLView.as_view()),
- url(r'^json$', JSONView.as_view()),
- url(r'^html1$', HTMLView1.as_view()),
- url(r'^html_new_model$', HTMLNewModelView.as_view()),
- url(r'^html_new_model_viewset', include(new_model_viewset_router.urls)),
- url(r'^restframework', include('rest_framework.urls', namespace='rest_framework'))
+ path('setbyview', MockViewSettingContentType.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
+ re_path(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
+ path('', MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
+ path('html', HTMLView.as_view()),
+ path('json', JSONView.as_view()),
+ path('html1', HTMLView1.as_view()),
+ path('html_new_model', HTMLNewModelView.as_view()),
+ path('html_new_model_viewset', include(new_model_viewset_router.urls)),
+ path('restframework', include('rest_framework.urls', namespace='rest_framework'))
]
diff --git a/tests/test_reverse.py b/tests/test_reverse.py
--- a/tests/test_reverse.py
+++ b/tests/test_reverse.py
@@ -1,6 +1,5 @@
-from django.conf.urls import url
from django.test import TestCase, override_settings
-from django.urls import NoReverseMatch
+from django.urls import NoReverseMatch, path
from rest_framework.reverse import reverse
from rest_framework.test import APIRequestFactory
@@ -13,7 +12,7 @@ def null_view(request):
urlpatterns = [
- url(r'^view$', null_view, name='view'),
+ path('view', null_view, name='view'),
]
diff --git a/tests/test_routers.py b/tests/test_routers.py
--- a/tests/test_routers.py
+++ b/tests/test_routers.py
@@ -1,11 +1,10 @@
from collections import namedtuple
import pytest
-from django.conf.urls import include, url
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.test import TestCase, override_settings
-from django.urls import resolve, reverse
+from django.urls import include, path, resolve, reverse
from rest_framework import permissions, serializers, viewsets
from rest_framework.decorators import action
@@ -118,7 +117,7 @@ class TestSimpleRouter(URLPatternsTestCase, TestCase):
router.register('basics', BasicViewSet, basename='basic')
urlpatterns = [
- url(r'^api/', include(router.urls)),
+ path('api/', include(router.urls)),
]
def setUp(self):
@@ -163,8 +162,8 @@ def test_register_after_accessing_urls(self):
class TestRootView(URLPatternsTestCase, TestCase):
urlpatterns = [
- url(r'^non-namespaced/', include(namespaced_router.urls)),
- url(r'^namespaced/', include((namespaced_router.urls, 'namespaced'), namespace='namespaced')),
+ path('non-namespaced/', include(namespaced_router.urls)),
+ path('namespaced/', include((namespaced_router.urls, 'namespaced'), namespace='namespaced')),
]
def test_retrieve_namespaced_root(self):
@@ -181,8 +180,8 @@ class TestCustomLookupFields(URLPatternsTestCase, TestCase):
Ensure that custom lookup fields are correctly routed.
"""
urlpatterns = [
- url(r'^example/', include(notes_router.urls)),
- url(r'^example2/', include(kwarged_notes_router.urls)),
+ path('example/', include(notes_router.urls)),
+ path('example2/', include(kwarged_notes_router.urls)),
]
def setUp(self):
@@ -238,8 +237,8 @@ class TestLookupUrlKwargs(URLPatternsTestCase, TestCase):
Setup a deep lookup_field, but map it to a simple URL kwarg.
"""
urlpatterns = [
- url(r'^example/', include(notes_router.urls)),
- url(r'^example2/', include(kwarged_notes_router.urls)),
+ path('example/', include(notes_router.urls)),
+ path('example2/', include(kwarged_notes_router.urls)),
]
def setUp(self):
@@ -426,7 +425,7 @@ def test_inherited_list_and_detail_route_decorators(self):
class TestEmptyPrefix(URLPatternsTestCase, TestCase):
urlpatterns = [
- url(r'^empty-prefix/', include(empty_prefix_router.urls)),
+ path('empty-prefix/', include(empty_prefix_router.urls)),
]
def test_empty_prefix_list(self):
@@ -443,7 +442,7 @@ def test_empty_prefix_detail(self):
class TestRegexUrlPath(URLPatternsTestCase, TestCase):
urlpatterns = [
- url(r'^regex/', include(regex_url_path_router.urls)),
+ path('regex/', include(regex_url_path_router.urls)),
]
def test_regex_url_path_list(self):
@@ -462,7 +461,7 @@ def test_regex_url_path_detail(self):
class TestViewInitkwargs(URLPatternsTestCase, TestCase):
urlpatterns = [
- url(r'^example/', include(notes_router.urls)),
+ path('example/', include(notes_router.urls)),
]
def test_suffix(self):
diff --git a/tests/test_testing.py b/tests/test_testing.py
--- a/tests/test_testing.py
+++ b/tests/test_testing.py
@@ -1,9 +1,9 @@
from io import BytesIO
-from django.conf.urls import url
from django.contrib.auth.models import User
from django.shortcuts import redirect
from django.test import TestCase, override_settings
+from django.urls import path
from rest_framework import fields, serializers
from rest_framework.decorators import api_view
@@ -47,10 +47,10 @@ def post_view(request):
urlpatterns = [
- url(r'^view/$', view),
- url(r'^session-view/$', session_view),
- url(r'^redirect-view/$', redirect_view),
- url(r'^post-view/$', post_view)
+ path('view/', view),
+ path('session-view/', session_view),
+ path('redirect-view/', redirect_view),
+ path('post-view/', post_view)
]
@@ -284,7 +284,7 @@ def test_empty_request_content_type(self):
class TestUrlPatternTestCase(URLPatternsTestCase):
urlpatterns = [
- url(r'^$', view),
+ path('', view),
]
@classmethod
diff --git a/tests/test_urlpatterns.py b/tests/test_urlpatterns.py
--- a/tests/test_urlpatterns.py
+++ b/tests/test_urlpatterns.py
@@ -1,8 +1,7 @@
from collections import namedtuple
-from django.conf.urls import include, url
from django.test import TestCase
-from django.urls import Resolver404, URLResolver, path, re_path
+from django.urls import Resolver404, URLResolver, include, path, re_path
from django.urls.resolvers import RegexPattern
from rest_framework.test import APIRequestFactory
@@ -61,7 +60,7 @@ def _test_trailing_slash(self, urlpatterns):
def test_trailing_slash(self):
urlpatterns = [
- url(r'^test/$', dummy_view),
+ path('test/', dummy_view),
]
self._test_trailing_slash(urlpatterns)
@@ -81,7 +80,7 @@ def _test_format_suffix(self, urlpatterns):
def test_format_suffix(self):
urlpatterns = [
- url(r'^test$', dummy_view),
+ path('test', dummy_view),
]
self._test_format_suffix(urlpatterns)
@@ -116,7 +115,7 @@ def _test_default_args(self, urlpatterns):
def test_default_args(self):
urlpatterns = [
- url(r'^test$', dummy_view, {'foo': 'bar'}),
+ path('test', dummy_view, {'foo': 'bar'}),
]
self._test_default_args(urlpatterns)
@@ -135,15 +134,6 @@ def _test_included_urls(self, urlpatterns):
self._resolve_urlpatterns(urlpatterns, test_paths)
def test_included_urls(self):
- nested_patterns = [
- url(r'^path$', dummy_view)
- ]
- urlpatterns = [
- url(r'^test/', include(nested_patterns), {'foo': 'bar'}),
- ]
- self._test_included_urls(urlpatterns)
-
- def test_included_urls_django2(self):
nested_patterns = [
path('path', dummy_view)
]
@@ -152,44 +142,35 @@ def test_included_urls_django2(self):
]
self._test_included_urls(urlpatterns)
- def test_included_urls_django2_mixed(self):
- nested_patterns = [
- path('path', dummy_view)
- ]
- urlpatterns = [
- url('^test/', include(nested_patterns), {'foo': 'bar'}),
- ]
- self._test_included_urls(urlpatterns)
-
- def test_included_urls_django2_mixed_args(self):
+ def test_included_urls_mixed(self):
nested_patterns = [
path('path/<int:child>', dummy_view),
- url('^url/(?P<child>[0-9]+)$', dummy_view)
+ re_path(r'^re_path/(?P<child>[0-9]+)$', dummy_view)
]
urlpatterns = [
- url('^purl/(?P<parent>[0-9]+)/', include(nested_patterns), {'foo': 'bar'}),
+ re_path(r'^pre_path/(?P<parent>[0-9]+)/', include(nested_patterns), {'foo': 'bar'}),
path('ppath/<int:parent>/', include(nested_patterns), {'foo': 'bar'}),
]
test_paths = [
- # parent url() nesting child path()
- URLTestPath('/purl/87/path/42', (), {'parent': '87', 'child': 42, 'foo': 'bar', }),
- URLTestPath('/purl/87/path/42.api', (), {'parent': '87', 'child': 42, 'foo': 'bar', 'format': 'api'}),
- URLTestPath('/purl/87/path/42.asdf', (), {'parent': '87', 'child': 42, 'foo': 'bar', 'format': 'asdf'}),
+ # parent re_path() nesting child path()
+ URLTestPath('/pre_path/87/path/42', (), {'parent': '87', 'child': 42, 'foo': 'bar', }),
+ URLTestPath('/pre_path/87/path/42.api', (), {'parent': '87', 'child': 42, 'foo': 'bar', 'format': 'api'}),
+ URLTestPath('/pre_path/87/path/42.asdf', (), {'parent': '87', 'child': 42, 'foo': 'bar', 'format': 'asdf'}),
- # parent path() nesting child url()
- URLTestPath('/ppath/87/url/42', (), {'parent': 87, 'child': '42', 'foo': 'bar', }),
- URLTestPath('/ppath/87/url/42.api', (), {'parent': 87, 'child': '42', 'foo': 'bar', 'format': 'api'}),
- URLTestPath('/ppath/87/url/42.asdf', (), {'parent': 87, 'child': '42', 'foo': 'bar', 'format': 'asdf'}),
+ # parent path() nesting child re_path()
+ URLTestPath('/ppath/87/re_path/42', (), {'parent': 87, 'child': '42', 'foo': 'bar', }),
+ URLTestPath('/ppath/87/re_path/42.api', (), {'parent': 87, 'child': '42', 'foo': 'bar', 'format': 'api'}),
+ URLTestPath('/ppath/87/re_path/42.asdf', (), {'parent': 87, 'child': '42', 'foo': 'bar', 'format': 'asdf'}),
# parent path() nesting child path()
URLTestPath('/ppath/87/path/42', (), {'parent': 87, 'child': 42, 'foo': 'bar', }),
URLTestPath('/ppath/87/path/42.api', (), {'parent': 87, 'child': 42, 'foo': 'bar', 'format': 'api'}),
URLTestPath('/ppath/87/path/42.asdf', (), {'parent': 87, 'child': 42, 'foo': 'bar', 'format': 'asdf'}),
- # parent url() nesting child url()
- URLTestPath('/purl/87/url/42', (), {'parent': '87', 'child': '42', 'foo': 'bar', }),
- URLTestPath('/purl/87/url/42.api', (), {'parent': '87', 'child': '42', 'foo': 'bar', 'format': 'api'}),
- URLTestPath('/purl/87/url/42.asdf', (), {'parent': '87', 'child': '42', 'foo': 'bar', 'format': 'asdf'}),
+ # parent re_path() nesting child re_path()
+ URLTestPath('/pre_path/87/re_path/42', (), {'parent': '87', 'child': '42', 'foo': 'bar', }),
+ URLTestPath('/pre_path/87/re_path/42.api', (), {'parent': '87', 'child': '42', 'foo': 'bar', 'format': 'api'}),
+ URLTestPath('/pre_path/87/re_path/42.asdf', (), {'parent': '87', 'child': '42', 'foo': 'bar', 'format': 'asdf'}),
]
self._resolve_urlpatterns(urlpatterns, test_paths)
@@ -202,13 +183,13 @@ def _test_allowed_formats(self, urlpatterns):
]
self._resolve_urlpatterns(urlpatterns, test_paths, allowed=allowed_formats)
- def test_allowed_formats(self):
+ def test_allowed_formats_re_path(self):
urlpatterns = [
- url('^test$', dummy_view),
+ re_path(r'^test$', dummy_view),
]
self._test_allowed_formats(urlpatterns)
- def test_allowed_formats_django2(self):
+ def test_allowed_formats_path(self):
urlpatterns = [
path('test', dummy_view),
]
diff --git a/tests/test_utils.py b/tests/test_utils.py
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,7 +1,7 @@
from unittest import mock
-from django.conf.urls import url
from django.test import TestCase, override_settings
+from django.urls import path
from rest_framework.decorators import action
from rest_framework.routers import SimpleRouter
@@ -64,12 +64,12 @@ def suffixed_action(self, request, *args, **kwargs):
router = SimpleRouter()
router.register(r'resources', ResourceViewSet)
urlpatterns = [
- url(r'^$', Root.as_view()),
- url(r'^resource/$', ResourceRoot.as_view()),
- url(r'^resource/customname$', CustomNameResourceInstance.as_view()),
- url(r'^resource/(?P<key>[0-9]+)$', ResourceInstance.as_view()),
- url(r'^resource/(?P<key>[0-9]+)/$', NestedResourceRoot.as_view()),
- url(r'^resource/(?P<key>[0-9]+)/(?P<other>[A-Za-z]+)$', NestedResourceInstance.as_view()),
+ path('', Root.as_view()),
+ path('resource/', ResourceRoot.as_view()),
+ path('resource/customname', CustomNameResourceInstance.as_view()),
+ path('resource/<int:key>', ResourceInstance.as_view()),
+ path('resource/<int:key>/', NestedResourceRoot.as_view()),
+ path('resource/<int:key>/<str:other>', NestedResourceInstance.as_view()),
]
urlpatterns += router.urls
diff --git a/tests/test_versioning.py b/tests/test_versioning.py
--- a/tests/test_versioning.py
+++ b/tests/test_versioning.py
@@ -1,6 +1,6 @@
import pytest
-from django.conf.urls import include, url
from django.test import override_settings
+from django.urls import include, path, re_path
from rest_framework import serializers, status, versioning
from rest_framework.decorators import APIView
@@ -144,14 +144,14 @@ class FakeResolverMatch:
class TestURLReversing(URLPatternsTestCase, APITestCase):
included = [
- url(r'^namespaced/$', dummy_view, name='another'),
- url(r'^example/(?P<pk>\d+)/$', dummy_pk_view, name='example-detail')
+ path('namespaced/', dummy_view, name='another'),
+ path('example/<int:pk>/', dummy_pk_view, name='example-detail')
]
urlpatterns = [
- url(r'^v1/', include((included, 'v1'), namespace='v1')),
- url(r'^another/$', dummy_view, name='another'),
- url(r'^(?P<version>[v1|v2]+)/another/$', dummy_view, name='another'),
+ path('v1/', include((included, 'v1'), namespace='v1')),
+ path('another/', dummy_view, name='another'),
+ re_path(r'^(?P<version>[v1|v2]+)/another/$', dummy_view, name='another'),
]
def test_reverse_unversioned(self):
@@ -310,12 +310,12 @@ def test_missing_with_default_and_none_allowed(self):
class TestHyperlinkedRelatedField(URLPatternsTestCase, APITestCase):
included = [
- url(r'^namespaced/(?P<pk>\d+)/$', dummy_pk_view, name='namespaced'),
+ path('namespaced/<int:pk>/', dummy_pk_view, name='namespaced'),
]
urlpatterns = [
- url(r'^v1/', include((included, 'v1'), namespace='v1')),
- url(r'^v2/', include((included, 'v2'), namespace='v2'))
+ path('v1/', include((included, 'v1'), namespace='v1')),
+ path('v2/', include((included, 'v2'), namespace='v2'))
]
def setUp(self):
@@ -342,17 +342,17 @@ def test_bug_2489(self):
class TestNamespaceVersioningHyperlinkedRelatedFieldScheme(URLPatternsTestCase, APITestCase):
nested = [
- url(r'^namespaced/(?P<pk>\d+)/$', dummy_pk_view, name='nested'),
+ path('namespaced/<int:pk>/', dummy_pk_view, name='nested'),
]
included = [
- url(r'^namespaced/(?P<pk>\d+)/$', dummy_pk_view, name='namespaced'),
- url(r'^nested/', include((nested, 'nested-namespace'), namespace='nested-namespace'))
+ path('namespaced/<int:pk>/', dummy_pk_view, name='namespaced'),
+ path('nested/', include((nested, 'nested-namespace'), namespace='nested-namespace'))
]
urlpatterns = [
- url(r'^v1/', include((included, 'restframeworkv1'), namespace='v1')),
- url(r'^v2/', include((included, 'restframeworkv2'), namespace='v2')),
- url(r'^non-api/(?P<pk>\d+)/$', dummy_pk_view, name='non-api-view')
+ path('v1/', include((included, 'restframeworkv1'), namespace='v1')),
+ path('v2/', include((included, 'restframeworkv2'), namespace='v2')),
+ path('non-api/<int:pk>/', dummy_pk_view, name='non-api-view')
]
def _create_field(self, view_name, version):
diff --git a/tests/test_viewsets.py b/tests/test_viewsets.py
--- a/tests/test_viewsets.py
+++ b/tests/test_viewsets.py
@@ -2,9 +2,9 @@
from functools import wraps
import pytest
-from django.conf.urls import include, url
from django.db import models
from django.test import TestCase, override_settings
+from django.urls import include, path
from rest_framework import status
from rest_framework.decorators import action
@@ -124,7 +124,7 @@ class ActionViewSetWithMapping(ActionViewSet):
urlpatterns = [
- url(r'^api/', include(router.urls)),
+ path('api/', include(router.urls)),
]
diff --git a/tests/urls.py b/tests/urls.py
--- a/tests/urls.py
+++ b/tests/urls.py
@@ -3,14 +3,14 @@
We need only the docs urls for DocumentationRenderer tests.
"""
-from django.conf.urls import url
+from django.urls import path
from rest_framework.compat import coreapi
from rest_framework.documentation import include_docs_urls
if coreapi:
urlpatterns = [
- url(r'^docs/', include_docs_urls(title='Test Suite API')),
+ path('docs/', include_docs_urls(title='Test Suite API')),
]
else:
urlpatterns = []
| url() is deprecated in Django 3.1
CI is raising warnings as `url()` is deprecated in the upcoming release of Django.
https://travis-ci.org/github/encode/django-rest-framework/jobs/707134589
| check https://github.com/encode/django-rest-framework/pull/7325 | 2020-09-02T12:08:46 |
encode/django-rest-framework | 7,513 | encode__django-rest-framework-7513 | [
"7417"
] | 327cbef29977bb999f292d3c8b7b3efc2491691d | diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py
--- a/rest_framework/authentication.py
+++ b/rest_framework/authentication.py
@@ -136,7 +136,10 @@ def enforce_csrf(self, request):
"""
Enforce CSRF validation for session based authentication.
"""
- check = CSRFCheck()
+ def dummy_get_response(request): # pragma: no cover
+ return None
+
+ check = CSRFCheck(dummy_get_response)
# populates request.META['CSRF_COOKIE'], which is used in process_view()
check.process_request(request)
reason = check.process_view(request, None, (), {})
| diff --git a/tests/test_request.py b/tests/test_request.py
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -205,8 +205,12 @@ def setUp(self):
# available to login and logout functions
self.wrapped_request = factory.get('/')
self.request = Request(self.wrapped_request)
- SessionMiddleware().process_request(self.wrapped_request)
- AuthenticationMiddleware().process_request(self.wrapped_request)
+
+ def dummy_get_response(request): # pragma: no cover
+ return None
+
+ SessionMiddleware(dummy_get_response).process_request(self.wrapped_request)
+ AuthenticationMiddleware(dummy_get_response).process_request(self.wrapped_request)
User.objects.create_user('ringo', '[email protected]', 'yellow')
self.user = authenticate(username='ringo', password='yellow')
| Passing None for the middleware get_response argument is deprecated.
Looking at the travis builds on master in addition to the `url()` deprecation there is also a few failing with this warning.
```
/home/travis/build/encode/django-rest-framework/rest_framework/authentication.py:139: RemovedInDjango40Warning: Passing None for the middleware get_response argument is deprecated.
check = CSRFCheck()
```
I couldn't see anything raised already but my search skills for `url()` let me down somewhat 🙈
| 2020-09-02T12:18:29 |
|
encode/django-rest-framework | 7,522 | encode__django-rest-framework-7522 | [
"7117"
] | 04f39c42ee28bd462fcc9088909b18f2b321501d | diff --git a/rest_framework/permissions.py b/rest_framework/permissions.py
--- a/rest_framework/permissions.py
+++ b/rest_framework/permissions.py
@@ -78,8 +78,11 @@ def has_permission(self, request, view):
def has_object_permission(self, request, view, obj):
return (
- self.op1.has_object_permission(request, view, obj) or
- self.op2.has_object_permission(request, view, obj)
+ self.op1.has_permission(request, view)
+ and self.op1.has_object_permission(request, view, obj)
+ ) or (
+ self.op2.has_permission(request, view)
+ and self.op2.has_object_permission(request, view, obj)
)
| diff --git a/tests/test_permissions.py b/tests/test_permissions.py
--- a/tests/test_permissions.py
+++ b/tests/test_permissions.py
@@ -635,7 +635,7 @@ def test_object_or_lazyness(self):
composed_perm = (permissions.IsAuthenticated | permissions.AllowAny)
hasperm = composed_perm().has_object_permission(request, None, None)
assert hasperm is True
- assert mock_deny.call_count == 1
+ assert mock_deny.call_count == 0
assert mock_allow.call_count == 1
def test_and_lazyness(self):
@@ -677,3 +677,16 @@ def test_object_and_lazyness(self):
assert hasperm is False
assert mock_deny.call_count == 1
mock_allow.assert_not_called()
+
+ def test_unimplemented_has_object_permission(self):
+ "test for issue 6402 https://github.com/encode/django-rest-framework/issues/6402"
+ request = factory.get('/1', format='json')
+ request.user = AnonymousUser()
+
+ class IsAuthenticatedUserOwner(permissions.IsAuthenticated):
+ def has_object_permission(self, request, view, obj):
+ return True
+
+ composed_perm = (IsAuthenticatedUserOwner | permissions.IsAdminUser)
+ hasperm = composed_perm().has_object_permission(request, None, None)
+ assert hasperm is False
| bitwise permissions not working when combine has_object_permission and has_permission
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Set
```
from rest_framework import viewsets
from rest_framework.permissions import IsAdminUser
class IsCompanyMemberPermission(IsAuthenticated):
"""
Allows access only to company owner members.
"""
def has_object_permission(self, request, view, obj):
return obj == request.user.company
class MyViewSet(viewsets.ModelViewSet):
def get_permissions(self):
if self.action in ['update', 'partial_update', 'destroy']:
self.permission_classes = (IsAdminUser | IsCompanyMemberPermission, )
return super(BuilderOrganizationViewSet, self).get_permissions()
```
Do put request
I also found similar issue on https://stackoverflow.com/a/55773420/1786016
## Expected behavior
`has_object_permission` must be called and return False in my case
## Actual behavior
`has_object_permission` not called
| 2020-09-05T18:20:46 |
|
encode/django-rest-framework | 7,557 | encode__django-rest-framework-7557 | [
"7554"
] | 68b23075a2d72935f1e6c428c664d49412a8af68 | diff --git a/rest_framework/authtoken/migrations/0003_tokenproxy.py b/rest_framework/authtoken/migrations/0003_tokenproxy.py
new file mode 100644
--- /dev/null
+++ b/rest_framework/authtoken/migrations/0003_tokenproxy.py
@@ -0,0 +1,25 @@
+# Generated by Django 3.1.1 on 2020-09-28 09:34
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('authtoken', '0002_auto_20160226_1747'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='TokenProxy',
+ fields=[
+ ],
+ options={
+ 'verbose_name': 'token',
+ 'proxy': True,
+ 'indexes': [],
+ 'constraints': [],
+ },
+ bases=('authtoken.token',),
+ ),
+ ]
| Missing migration for TokenProxy in 3.12 release
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
* Look at https://github.com/encode/django-rest-framework/tree/3.12.0/rest_framework/authtoken/migrations to see that there is no migration introducing the `TokenProxy` model.
* Alternatively (the way I found it): Have a django project which uses the rest-framework complain on startup that a migration is missing for the `TokenProxy` model.
## Expected behavior
An existing migration for the `TokenProxy` model.
## Actual behavior
No migration for the `TokenProxy` model.
| 2020-09-28T14:39:44 |
||
encode/django-rest-framework | 7,641 | encode__django-rest-framework-7641 | [
"7640"
] | 96993d817a6af9c037ece7253cfae49efc814f49 | diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py
--- a/rest_framework/renderers.py
+++ b/rest_framework/renderers.py
@@ -1063,7 +1063,8 @@ def ignore_aliases(self, data):
class JSONOpenAPIRenderer(BaseRenderer):
media_type = 'application/vnd.oai.openapi+json'
charset = None
+ encoder_class = encoders.JSONEncoder
format = 'openapi-json'
def render(self, data, media_type=None, renderer_context=None):
- return json.dumps(data, indent=2).encode('utf-8')
+ return json.dumps(data, cls=self.encoder_class, indent=2).encode('utf-8')
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -11,7 +11,8 @@
from rest_framework.compat import uritemplate
from rest_framework.parsers import JSONParser, MultiPartParser
from rest_framework.renderers import (
- BaseRenderer, BrowsableAPIRenderer, JSONRenderer, OpenAPIRenderer
+ BaseRenderer, BrowsableAPIRenderer, JSONOpenAPIRenderer, JSONRenderer,
+ OpenAPIRenderer
)
from rest_framework.request import Request
from rest_framework.schemas.openapi import AutoSchema, SchemaGenerator
@@ -992,6 +993,19 @@ def test_schema_construction(self):
assert 'openapi' in schema
assert 'paths' in schema
+ def test_schema_rendering_to_json(self):
+ patterns = [
+ path('example/', views.ExampleGenericAPIView.as_view()),
+ ]
+ generator = SchemaGenerator(patterns=patterns)
+
+ request = create_request('/')
+ schema = generator.get_schema(request=request)
+ ret = JSONOpenAPIRenderer().render(schema)
+
+ assert b'"openapi": "' in ret
+ assert b'"default": "0.0"' in ret
+
def test_schema_with_no_paths(self):
patterns = []
generator = SchemaGenerator(patterns=patterns)
diff --git a/tests/schemas/views.py b/tests/schemas/views.py
--- a/tests/schemas/views.py
+++ b/tests/schemas/views.py
@@ -1,4 +1,5 @@
import uuid
+from datetime import timedelta
from django.core.validators import (
DecimalValidator, MaxLengthValidator, MaxValueValidator,
@@ -59,6 +60,7 @@ def get(self, *args, **kwargs):
class ExampleSerializer(serializers.Serializer):
date = serializers.DateField()
datetime = serializers.DateTimeField()
+ duration = serializers.DurationField(default=timedelta())
hstore = serializers.HStoreField()
uuid_field = serializers.UUIDField(default=uuid.uuid4)
| OpenAPI Schema: rendering to json fails for timedelta
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [x] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
- Define a Serializer with a DurationField, use a timedelta as `default`, `min_value` or `max_value`. For example:
```
class ExampleSerializer(serializers.Serializer):
duration = serializers.DurationField(default=timedelta())
```
- Create an APIView using this Serializer
OpenAPI schema generation, rendered as json, will fail.
## Expected behavior
json rendering should not raise an error.
## Actual behavior
`TypeError: Object of type 'timedelta' is not JSON serializable` is raised
| 2020-11-18T10:31:37 |
|
encode/django-rest-framework | 7,708 | encode__django-rest-framework-7708 | [
"7691"
] | 431f7dfa3dc108d449044a6c9eef715416d53059 | diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py
--- a/rest_framework/pagination.py
+++ b/rest_framework/pagination.py
@@ -961,7 +961,7 @@ def get_schema_operation_parameters(self, view):
'in': 'query',
'description': force_str(self.cursor_query_description),
'schema': {
- 'type': 'integer',
+ 'type': 'string',
},
}
]
| Invalid `CursorPagination` schema type
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
1. Create custom cursor pagination class
`pagination.py`
```python
from rest_framework.pagination import CursorPagination
class AuthLogCursorPagination(CursorPagination):
page_size = 50
page_size_query_param = "page_size"
ordering = "-created_at"
```
2. Register `AuthLogCursorPagination` in APIView
`views.py`
```python
from rest_framework.generic import ListAPIView
from app.models import AuthLog
from app.api.pagination import AuthLogCursorPagination
from app.api.serializers import AuthLogSerializer
class AuthLogsAPIView(ListAPIView):
queryset = AuthLog.objects.all()
serializer_class = AuthLogSerializer
pagination_class = AuthLogCursorPagination
```
3. Register view
`urls.py`
```python
from rest_framework.schemas import get_schema_view
from app.api.views import AuthLogsAPIView
urlpatterns = [
path("authlog/", AuthLogsAPIView.as_view()),
path("openapi", get_schema_view(
title="Your Project",
description="API for all things …",
version="1.0.0"
), name="openapi-schema"),
]
```
4. Open /openapi and check /authlog/ endpoint generated spec
## Expected behavior
```yaml
/authlog/:
get:
operationId: listAuthLogs
description: ''
parameters:
- name: cursor
required: false
in: query
description: The pagination cursor value.
schema:
type: string
- name: page_size
required: false
in: query
description: Number of results to return per page.
schema:
type: integer
```
## Actual behavior
```yaml
/authlog/:
get:
operationId: listAuthLogs
description: ''
parameters:
- name: cursor
required: false
in: query
description: The pagination cursor value.
schema:
type: integer # <---- INVALID
- name: page_size
required: false
in: query
description: Number of results to return per page.
schema:
type: integer
```
`cursor` parameter schema type must be `string`, got `integer` instead.
| 2021-02-03T05:17:04 |
||
encode/django-rest-framework | 7,718 | encode__django-rest-framework-7718 | [
"7721"
] | 1ec0f86b585cd87e4b413aeaad1ecc947bacfef2 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1063,6 +1063,9 @@ def to_internal_value(self, data):
try:
value = decimal.Decimal(data)
except decimal.DecimalException:
+ if data == '' and self.allow_null:
+ return None
+
self.fail('invalid')
if value.is_nan():
@@ -1112,6 +1115,12 @@ def validate_precision(self, value):
def to_representation(self, value):
coerce_to_string = getattr(self, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING)
+ if value is None:
+ if coerce_to_string:
+ return ''
+ else:
+ return None
+
if not isinstance(value, decimal.Decimal):
value = decimal.Decimal(str(value).strip())
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -1090,6 +1090,9 @@ class TestDecimalField(FieldValues):
'2E+1': Decimal('20'),
}
invalid_inputs = (
+ (None, ["This field may not be null."]),
+ ('', ["A valid number is required."]),
+ (' ', ["A valid number is required."]),
('abc', ["A valid number is required."]),
(Decimal('Nan'), ["A valid number is required."]),
(Decimal('Snan'), ["A valid number is required."]),
@@ -1115,6 +1118,32 @@ class TestDecimalField(FieldValues):
field = serializers.DecimalField(max_digits=3, decimal_places=1)
+class TestAllowNullDecimalField(FieldValues):
+ valid_inputs = {
+ None: None,
+ '': None,
+ ' ': None,
+ }
+ invalid_inputs = {}
+ outputs = {
+ None: '',
+ }
+ field = serializers.DecimalField(max_digits=3, decimal_places=1, allow_null=True)
+
+
+class TestAllowNullNoStringCoercionDecimalField(FieldValues):
+ valid_inputs = {
+ None: None,
+ '': None,
+ ' ': None,
+ }
+ invalid_inputs = {}
+ outputs = {
+ None: None,
+ }
+ field = serializers.DecimalField(max_digits=3, decimal_places=1, allow_null=True, coerce_to_string=False)
+
+
class TestMinMaxDecimalField(FieldValues):
"""
Valid and invalid values for `DecimalField` with min and max limits.
| DecimalField errors on serialization of `None`, even when `allow_null=True`
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [x] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
Try to serialize `None` with a `DecimalField` where `allow_null = True`.
## Expected behavior
What to expect here is a bit subjective... I'm expecting `''` if `coerce_to_string=True`, otherwise `None`, but that's just my subjective opinion.
However, I think we can agree that the actual behavior isn't the expected behavior. :)
## Actual behavior
Throws `InvalidOperation: [<class 'decimal.ConversionSyntax'>]`
| 2021-02-16T23:40:26 |
|
encode/django-rest-framework | 7,724 | encode__django-rest-framework-7724 | [
"7706",
"7706"
] | 1ec0f86b585cd87e4b413aeaad1ecc947bacfef2 | diff --git a/rest_framework/utils/serializer_helpers.py b/rest_framework/utils/serializer_helpers.py
--- a/rest_framework/utils/serializer_helpers.py
+++ b/rest_framework/utils/serializer_helpers.py
@@ -1,5 +1,5 @@
from collections import OrderedDict
-from collections.abc import MutableMapping
+from collections.abc import Mapping, MutableMapping
from django.utils.encoding import force_str
@@ -101,7 +101,7 @@ class NestedBoundField(BoundField):
"""
def __init__(self, field, value, errors, prefix=''):
- if value is None or value == '':
+ if value is None or value == '' or not isinstance(value, Mapping):
value = {}
super().__init__(field, value, errors, prefix)
| diff --git a/tests/test_bound_fields.py b/tests/test_bound_fields.py
--- a/tests/test_bound_fields.py
+++ b/tests/test_bound_fields.py
@@ -163,6 +163,33 @@ class ExampleSerializer(serializers.Serializer):
rendered_packed = ''.join(rendered.split())
assert rendered_packed == expected_packed
+ def test_rendering_nested_fields_with_not_mappable_value(self):
+ from rest_framework.renderers import HTMLFormRenderer
+
+ class Nested(serializers.Serializer):
+ text_field = serializers.CharField()
+
+ class ExampleSerializer(serializers.Serializer):
+ nested = Nested()
+
+ serializer = ExampleSerializer(data={'nested': 1})
+ assert not serializer.is_valid()
+ renderer = HTMLFormRenderer()
+ for field in serializer:
+ rendered = renderer.render_field(field, {})
+ expected_packed = (
+ '<fieldset>'
+ '<legend>Nested</legend>'
+ '<divclass="form-group">'
+ '<label>Textfield</label>'
+ '<inputname="nested.text_field"class="form-control"type="text"value="">'
+ '</div>'
+ '</fieldset>'
+ )
+
+ rendered_packed = ''.join(rendered.split())
+ assert rendered_packed == expected_packed
+
class TestJSONBoundField:
def test_as_form_fields(self):
| Rendering of Nested Serializer fails if no dictionary is parsed
## Checklist
- [ ] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
1. Create a Serializer with a nested Serializer, e.g.:
```
class MySerializer(Serializer):
payload = PayloadSerializer(default={}, write_only=True)
class PayloadSerializer(Serializer):
some_field = CharField()
```
2. Post a malformed payload that is not a dictionary:
```
{
"payload": 1
}
```
## Expected behavior
Nested Serializer should fail and throw a ValidationError, Browsable API should render empty fields.
## Actual behavior
Server crashes in serializer_helpers.py at in as_form_field because integer is not iterable:
```python
def as_form_field(self):
values = {}
for key, value in self.value.items():
if isinstance(value, (list, dict)):
values[key] = value
else:
values[key] = '' if (value is None or value is False) else force_str(value)
return self.__class__(self._field, values, self.errors, self._prefix)
```
My workaround, modify Parent serializer:
```python
class PayloadNestedField(NestedBoundField):
def __init__(self, field, value, errors, prefix=''):
if value is not None and not isinstance(value, dict):
value = {}
super().__init__(field, value, errors, prefix)
class PayloadSerializer(Serializer):
some_field = CharField()
def __getitem__(self, key):
field = self.fields[key]
value = self.data.get(key)
error = self.errors.get(key) if hasattr(self, '_errors') else None
if key == 'payload':
return PayloadNestedField(field, value, error)
else:
return super().__getitem__(key)
```
I think the issue here is that NestedBoundField only defaults the value to {} if it is None or the empty string here:
```python
class NestedBoundField(BoundField):
"""
This `BoundField` additionally implements __iter__ and __getitem__
in order to support nested bound fields. This class is the type of
`BoundField` that is used for serializer fields.
"""
def __init__(self, field, value, errors, prefix=''):
if value is None or value == '':
value = {}
super().__init__(field, value, errors, prefix)
```
Rendering of Nested Serializer fails if no dictionary is parsed
## Checklist
- [ ] I have verified that that issue exists against the `master` branch of Django REST framework.
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.)
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
1. Create a Serializer with a nested Serializer, e.g.:
```
class MySerializer(Serializer):
payload = PayloadSerializer(default={}, write_only=True)
class PayloadSerializer(Serializer):
some_field = CharField()
```
2. Post a malformed payload that is not a dictionary:
```
{
"payload": 1
}
```
## Expected behavior
Nested Serializer should fail and throw a ValidationError, Browsable API should render empty fields.
## Actual behavior
Server crashes in serializer_helpers.py at in as_form_field because integer is not iterable:
```python
def as_form_field(self):
values = {}
for key, value in self.value.items():
if isinstance(value, (list, dict)):
values[key] = value
else:
values[key] = '' if (value is None or value is False) else force_str(value)
return self.__class__(self._field, values, self.errors, self._prefix)
```
My workaround, modify Parent serializer:
```python
class PayloadNestedField(NestedBoundField):
def __init__(self, field, value, errors, prefix=''):
if value is not None and not isinstance(value, dict):
value = {}
super().__init__(field, value, errors, prefix)
class PayloadSerializer(Serializer):
some_field = CharField()
def __getitem__(self, key):
field = self.fields[key]
value = self.data.get(key)
error = self.errors.get(key) if hasattr(self, '_errors') else None
if key == 'payload':
return PayloadNestedField(field, value, error)
else:
return super().__getitem__(key)
```
I think the issue here is that NestedBoundField only defaults the value to {} if it is None or the empty string here:
```python
class NestedBoundField(BoundField):
"""
This `BoundField` additionally implements __iter__ and __getitem__
in order to support nested bound fields. This class is the type of
`BoundField` that is used for serializer fields.
"""
def __init__(self, field, value, errors, prefix=''):
if value is None or value == '':
value = {}
super().__init__(field, value, errors, prefix)
```
| Hello @s4ke,
I was checking this issue and I tried to reproduce it with the following snippet:
``` python
from rest_framework import serializers
class PayloadSerializer(serializers.Serializer):
some_field = serializers.CharField()
class MySerializer(serializers.Serializer):
payload = PayloadSerializer(default={}, write_only=True)
data = {'payload': 1}
serializer = MySerializer(data=data)
serializer.is_valid(raise_exception=True)
```
The following Exception is raised:
```
ValidationError: {'payload': {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')]}}
```
I have tested this against the head of [master](https://github.com/encode/django-rest-framework/commit/1ec0f86b585cd87e4b413aeaad1ecc947bacfef2) and I have tested it against the version 3.12.2 that was already installed on my machine.
Do I miss anything in the snippet or in the reproduction steps?
This actually only happens in the browsable UI when rendering and is the reason we have not managed to reproduce it in our test suite. Re-reading the issue, I think I forgot to add this here.
I understand. Since it's also related with browsable UI, thus the endpoint, would it be possible to give more information regarding the views that can be used to reproduce this? Or does the issue happen with any Viewset extending APIView, GenericView, ModelViewSet, etc.?
This happens for GenericViewSet with the default html template.
I have created the following View that uses the serializers from the issue definition.
``` python
class NestedIssueView(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
serializer_class = MySerializer
queryset = Issue.objects.all()
def testing(self, request, format=None):
serializer = MySerializer(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(serializer.data, status=status.HTTP_201_CREATED)
```
I have added it to the `urls.py` as following:
``` python
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^issues/', NestedIssueView.as_view({'post': 'testing'}))
]
```
I sent the payload which can be seen in the following screenshot.

I am still receiving the validation error.

Could you maybe give more details to be able to reproduce the issue?
I will try to reproduce the error locally on our codebase and get back to you.
This is the error I get. I just checked with djangorestframework 3.12.2 and it also happens:

Let me try to extract more from our code.
Here is the stacktrace:
```
Traceback (most recent call last):
File "/base/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/base/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 202, in _get_response
response = response.render()
File "/base/venv/lib/python3.8/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/base/venv/lib/python3.8/site-packages/rest_framework/response.py", line 70, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/base/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 724, in render
context = self.get_context(data, accepted_media_type, renderer_context)
File "/base/<path-to-custom-renderer-that-only-overrides get_context>/renderers.py", line 25, in get_context
base_ctx = super().get_context(data, accepted_media_type, renderer_context)
File "/base/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 696, in get_context
'post_form': self.get_rendered_html_form(data, view, 'POST', request),
File "/base/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 493, in get_rendered_html_form
return self.render_form_for_serializer(existing_serializer)
File "/base/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 518, in render_form_for_serializer
return form_renderer.render(
File "/base/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 372, in render
return template.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 170, in render
return self._render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 211, in render
nodelist.append(node.render_annotated(context))
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 312, in render
return nodelist.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/library.py", line 192, in render
output = self.func(*resolved_args, **resolved_kwargs)
File "/base/venv/lib/python3.8/site-packages/rest_framework/templatetags/rest_framework.py", line 87, in render_field
return renderer.render_field(field, style)
File "/base/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 339, in render_field
field = field.as_form_field()
File "/base/venv/lib/python3.8/site-packages/rest_framework/utils/serializer_helpers.py", line 122, in as_form_field
for key, value in self.value.items():
AttributeError: 'int' object has no attribute 'items'
```
Here is the customized renderer we use (should not affect this, but nonetheless):
```
class CustomizableBrowsableAPIRenderer(BrowsableAPIRenderer):
def get_context(self, data: Any, accepted_media_type: str, renderer_context: Mapping[str, Any]) -> Dict[str, Any]:
base_ctx = super().get_context(data, accepted_media_type, renderer_context)
view = renderer_context['view']
if hasattr(view, 'get_description_string'):
try:
base_ctx['description'] = view.get_description_string()
except APIException:
pass
except Http404:
pass
if hasattr(view, 'get_name_string'):
try:
base_ctx['name'] = view.get_name_string()
except APIException:
# PermissionDenied, NotFound are really relevant here, but
# its better to not display anything than failing completely
pass
except Http404:
pass
return base_ctx
```
The PayloadSerializer class looks like this and is actually dynamically configured (see `get_fields`):
```
class PayloadSerializer(serializers.Serializer):
def create(self, validated_data: Any) -> Any:
# we dont use this
raise AssertionError()
def update(self, instance: Any, validated_data: Any) -> Any:
# we dont use this
raise AssertionError()
def to_internal_value(self, data: Dict[str, Any]) -> Dict[str, Any]:
# from the base class, we need to check this before
if not isinstance(data, Mapping):
message = self.error_messages['invalid'].format(
datatype=type(data).__name__
)
raise ValidationError({
api_settings.NON_FIELD_ERRORS_KEY: [message]
}, code='invalid')
own_keys = payload_serializers.keys()
extra_keys = set(data.keys()).difference(own_keys)
if len(extra_keys) > 0:
if data_series.allow_extra_fields:
for _extra_key in extra_keys:
if _extra_key in data:
# make sure downstream does not get the data
# if we ignore it
del data[_extra_key]
else:
raise ValidationError(
f'{str(extra_keys)} were set, but were not recognized'
)
return super().to_internal_value(data) # type: ignore
def get_fields(self) -> Dict[str, serializers.Field]:
return payload_serializers
```
I was able to reproduce the issue just now. I have tried with `CustomizableBrowsableAPIRenderer`. I was not able to reproduce it. The code was executed in a bit different direction than was in the stacktrace shared above. I was using the following parser class configuration:
```
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
],
```
I have changed it to the following:
```
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser',
],
```
Now, I was able to reproduce the issue. Then I have dropped `CustomizableBrowsableAPIRenderer` and used the regular `BrowsableAPIRenderer`. I am still able to reproduce the issue. Thank you for the detailed information. Now I will work on the issue.
Ah, something I also forgot. With this class it works for us:
```
class PayloadNestedField(NestedBoundField):
def __init__(self, field, value, errors, prefix=''): # type: ignore
if value is not None and not isinstance(value, Mapping):
value = {}
super().__init__(field, value, errors, prefix)
```
We monkey patch this into the parent serializer class like so:
```
def __getitem__(self, key): # type: ignore
# hack, return a PayloadNestedField to make rendering the browsable API not crash on non dict values
field = self.fields[key]
value = self.data.get(key)
error = self.errors.get(key) if hasattr(self, '_errors') else None
if key == 'payload':
return PayloadNestedField(field, value, error) # type: ignore
else:
return super().__getitem__(key)
```
Hello @s4ke,
I was checking this issue and I tried to reproduce it with the following snippet:
``` python
from rest_framework import serializers
class PayloadSerializer(serializers.Serializer):
some_field = serializers.CharField()
class MySerializer(serializers.Serializer):
payload = PayloadSerializer(default={}, write_only=True)
data = {'payload': 1}
serializer = MySerializer(data=data)
serializer.is_valid(raise_exception=True)
```
The following Exception is raised:
```
ValidationError: {'payload': {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')]}}
```
I have tested this against the head of [master](https://github.com/encode/django-rest-framework/commit/1ec0f86b585cd87e4b413aeaad1ecc947bacfef2) and I have tested it against the version 3.12.2 that was already installed on my machine.
Do I miss anything in the snippet or in the reproduction steps?
This actually only happens in the browsable UI when rendering and is the reason we have not managed to reproduce it in our test suite. Re-reading the issue, I think I forgot to add this here.
I understand. Since it's also related with browsable UI, thus the endpoint, would it be possible to give more information regarding the views that can be used to reproduce this? Or does the issue happen with any Viewset extending APIView, GenericView, ModelViewSet, etc.?
This happens for GenericViewSet with the default html template.
I have created the following View that uses the serializers from the issue definition.
``` python
class NestedIssueView(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
serializer_class = MySerializer
queryset = Issue.objects.all()
def testing(self, request, format=None):
serializer = MySerializer(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(serializer.data, status=status.HTTP_201_CREATED)
```
I have added it to the `urls.py` as following:
``` python
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^issues/', NestedIssueView.as_view({'post': 'testing'}))
]
```
I sent the payload which can be seen in the following screenshot.

I am still receiving the validation error.

Could you maybe give more details to be able to reproduce the issue?
I will try to reproduce the error locally on our codebase and get back to you.
This is the error I get. I just checked with djangorestframework 3.12.2 and it also happens:

Let me try to extract more from our code.
Here is the stacktrace:
```
Traceback (most recent call last):
File "/base/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/base/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 202, in _get_response
response = response.render()
File "/base/venv/lib/python3.8/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/base/venv/lib/python3.8/site-packages/rest_framework/response.py", line 70, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/base/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 724, in render
context = self.get_context(data, accepted_media_type, renderer_context)
File "/base/<path-to-custom-renderer-that-only-overrides get_context>/renderers.py", line 25, in get_context
base_ctx = super().get_context(data, accepted_media_type, renderer_context)
File "/base/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 696, in get_context
'post_form': self.get_rendered_html_form(data, view, 'POST', request),
File "/base/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 493, in get_rendered_html_form
return self.render_form_for_serializer(existing_serializer)
File "/base/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 518, in render_form_for_serializer
return form_renderer.render(
File "/base/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 372, in render
return template.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 170, in render
return self._render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 211, in render
nodelist.append(node.render_annotated(context))
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 312, in render
return nodelist.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/base/venv/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/base/venv/lib/python3.8/site-packages/django/template/library.py", line 192, in render
output = self.func(*resolved_args, **resolved_kwargs)
File "/base/venv/lib/python3.8/site-packages/rest_framework/templatetags/rest_framework.py", line 87, in render_field
return renderer.render_field(field, style)
File "/base/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 339, in render_field
field = field.as_form_field()
File "/base/venv/lib/python3.8/site-packages/rest_framework/utils/serializer_helpers.py", line 122, in as_form_field
for key, value in self.value.items():
AttributeError: 'int' object has no attribute 'items'
```
Here is the customized renderer we use (should not affect this, but nonetheless):
```
class CustomizableBrowsableAPIRenderer(BrowsableAPIRenderer):
def get_context(self, data: Any, accepted_media_type: str, renderer_context: Mapping[str, Any]) -> Dict[str, Any]:
base_ctx = super().get_context(data, accepted_media_type, renderer_context)
view = renderer_context['view']
if hasattr(view, 'get_description_string'):
try:
base_ctx['description'] = view.get_description_string()
except APIException:
pass
except Http404:
pass
if hasattr(view, 'get_name_string'):
try:
base_ctx['name'] = view.get_name_string()
except APIException:
# PermissionDenied, NotFound are really relevant here, but
# its better to not display anything than failing completely
pass
except Http404:
pass
return base_ctx
```
The PayloadSerializer class looks like this and is actually dynamically configured (see `get_fields`):
```
class PayloadSerializer(serializers.Serializer):
def create(self, validated_data: Any) -> Any:
# we dont use this
raise AssertionError()
def update(self, instance: Any, validated_data: Any) -> Any:
# we dont use this
raise AssertionError()
def to_internal_value(self, data: Dict[str, Any]) -> Dict[str, Any]:
# from the base class, we need to check this before
if not isinstance(data, Mapping):
message = self.error_messages['invalid'].format(
datatype=type(data).__name__
)
raise ValidationError({
api_settings.NON_FIELD_ERRORS_KEY: [message]
}, code='invalid')
own_keys = payload_serializers.keys()
extra_keys = set(data.keys()).difference(own_keys)
if len(extra_keys) > 0:
if data_series.allow_extra_fields:
for _extra_key in extra_keys:
if _extra_key in data:
# make sure downstream does not get the data
# if we ignore it
del data[_extra_key]
else:
raise ValidationError(
f'{str(extra_keys)} were set, but were not recognized'
)
return super().to_internal_value(data) # type: ignore
def get_fields(self) -> Dict[str, serializers.Field]:
return payload_serializers
```
I was able to reproduce the issue just now. I have tried with `CustomizableBrowsableAPIRenderer`. I was not able to reproduce it. The code was executed in a bit different direction than was in the stacktrace shared above. I was using the following parser class configuration:
```
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
],
```
I have changed it to the following:
```
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser',
],
```
Now, I was able to reproduce the issue. Then I have dropped `CustomizableBrowsableAPIRenderer` and used the regular `BrowsableAPIRenderer`. I am still able to reproduce the issue. Thank you for the detailed information. Now I will work on the issue.
Ah, something I also forgot. With this class it works for us:
```
class PayloadNestedField(NestedBoundField):
def __init__(self, field, value, errors, prefix=''): # type: ignore
if value is not None and not isinstance(value, Mapping):
value = {}
super().__init__(field, value, errors, prefix)
```
We monkey patch this into the parent serializer class like so:
```
def __getitem__(self, key): # type: ignore
# hack, return a PayloadNestedField to make rendering the browsable API not crash on non dict values
field = self.fields[key]
value = self.data.get(key)
error = self.errors.get(key) if hasattr(self, '_errors') else None
if key == 'payload':
return PayloadNestedField(field, value, error) # type: ignore
else:
return super().__getitem__(key)
``` | 2021-02-22T13:51:47 |
encode/django-rest-framework | 8,067 | encode__django-rest-framework-8067 | [
"8064"
] | d2977cff989f9b14f402ecf1e9235ee3d110977b | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1046,6 +1046,11 @@ def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=
'Invalid rounding option %s. Valid values for rounding are: %s' % (rounding, valid_roundings))
self.rounding = rounding
+ def validate_empty_values(self, data):
+ if smart_str(data).strip() == '' and self.allow_null:
+ return (True, None)
+ return super().validate_empty_values(data)
+
def to_internal_value(self, data):
"""
Validate that the input is a decimal number and return a Decimal
@@ -1063,9 +1068,6 @@ def to_internal_value(self, data):
try:
value = decimal.Decimal(data)
except decimal.DecimalException:
- if data == '' and self.allow_null:
- return None
-
self.fail('invalid')
if value.is_nan():
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -1163,6 +1163,30 @@ class TestMinMaxDecimalField(FieldValues):
)
+class TestAllowEmptyStrDecimalFieldWithValidators(FieldValues):
+ """
+ Check that empty string ('', ' ') is acceptable value for the DecimalField
+ if allow_null=True and there are max/min validators
+ """
+ valid_inputs = {
+ None: None,
+ '': None,
+ ' ': None,
+ ' ': None,
+ 5: Decimal('5'),
+ '0': Decimal('0'),
+ '10': Decimal('10'),
+ }
+ invalid_inputs = {
+ -1: ['Ensure this value is greater than or equal to 0.'],
+ 11: ['Ensure this value is less than or equal to 10.'],
+ }
+ outputs = {
+ None: '',
+ }
+ field = serializers.DecimalField(max_digits=3, decimal_places=1, allow_null=True, min_value=0, max_value=10)
+
+
class TestNoMaxDigitsDecimalField(FieldValues):
field = serializers.DecimalField(
max_value=100, min_value=0,
| Sending "" to a DecimalField with a min or a max value validator raises a TypeError
Example code:
```python
from rest_framework import serializers
from decimal import Decimal
class Foo(serializers.Serializer):
bar = serializers.DecimalField(max_digits=12, decimal_places=2, allow_null=True, min_value=Decimal('0.01'))
Foo(data={'bar': ''}).is_valid()
```
Result:
`TypeError: '<' not supported between instances of 'NoneType' and 'decimal.Decimal'`
This is due to the value being changed to None here after https://github.com/encode/django-rest-framework/pull/7718:
https://github.com/encode/django-rest-framework/blob/d2977cff989f9b14f402ecf1e9235ee3d110977b/rest_framework/fields.py#L1063-L1067
This doesn't happen with
```python
Foo(data={'bar': None}).is_valid()
```
I'm guessing in the latter case the min/max validation is skipped. I'm not sure if the same should happen here or if an empty string should not be accepted as a valid value.
| Good catch!
A good starting point here would be for someone to implement a pull request that adds a failing test for this particular case. Then we can get the test case resolved after that. Having a look at the tests added in #7718 would be helpful for anyone taking a go at this. | 2021-07-01T12:56:45 |
encode/django-rest-framework | 8,116 | encode__django-rest-framework-8116 | [
"8041",
"8041"
] | 98e56e0327596db352b35fa3b3dc8355dc9bd030 | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -1326,9 +1326,8 @@ def include_extra_kwargs(self, kwargs, extra_kwargs):
"""
if extra_kwargs.get('read_only', False):
for attr in [
- 'required', 'default', 'allow_blank', 'allow_null',
- 'min_length', 'max_length', 'min_value', 'max_value',
- 'validators', 'queryset'
+ 'required', 'default', 'allow_blank', 'min_length',
+ 'max_length', 'min_value', 'max_value', 'validators', 'queryset'
]:
kwargs.pop(attr, None)
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -2,6 +2,7 @@
import warnings
import pytest
+from django.db import models
from django.test import RequestFactory, TestCase, override_settings
from django.urls import path
from django.utils.translation import gettext_lazy as _
@@ -110,6 +111,24 @@ class Serializer(serializers.Serializer):
assert data['properties']['default_false']['default'] is False, "default must be false"
assert 'default' not in data['properties']['without_default'], "default must not be defined"
+ def test_nullable_fields(self):
+ class Model(models.Model):
+ rw_field = models.CharField(null=True)
+ ro_field = models.CharField(null=True)
+
+ class Serializer(serializers.ModelSerializer):
+ class Meta:
+ model = Model
+ fields = ["rw_field", "ro_field"]
+ read_only_fields = ["ro_field"]
+
+ inspector = AutoSchema()
+
+ data = inspector.map_serializer(Serializer())
+ assert data['properties']['rw_field']['nullable'], "rw_field nullable must be true"
+ assert data['properties']['ro_field']['nullable'], "ro_field nullable must be true"
+ assert data['properties']['ro_field']['readOnly'], "ro_field read_only must be true"
+
@pytest.mark.skipif(uritemplate is None, reason='uritemplate not installed.')
class TestOperationIntrospection(TestCase):
| null=True is not respected by AutoSchema when the field is on read_only_fields
Hello,
Take this ModelSerializer for example:
```python
class MyModel(models.Model):
my_field = models.DateTimeField(null=True, blank=True)
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ["my_field"]
read_only_fields = ["my_field"]
```
If you generate this serializer schema you will notice that the `null=True` was ignored by the generated schema
``` python
>>> inspector = AutoSchema()
>>> schema = inspector.map_serializer(MyModelSerializer())
>>> schema['properties']['my_field']
{'type': 'string', 'format': 'date-time', 'readOnly': True}
```
Removing the from the `read_only_fields` fixes the problem and the schema goes back to:
```python
{'type': 'string', 'format': 'date-time', 'nullable': True}
```
null=True is not respected by AutoSchema when the field is on read_only_fields
Hello,
Take this ModelSerializer for example:
```python
class MyModel(models.Model):
my_field = models.DateTimeField(null=True, blank=True)
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ["my_field"]
read_only_fields = ["my_field"]
```
If you generate this serializer schema you will notice that the `null=True` was ignored by the generated schema
``` python
>>> inspector = AutoSchema()
>>> schema = inspector.map_serializer(MyModelSerializer())
>>> schema['properties']['my_field']
{'type': 'string', 'format': 'date-time', 'readOnly': True}
```
Removing the from the `read_only_fields` fixes the problem and the schema goes back to:
```python
{'type': 'string', 'format': 'date-time', 'nullable': True}
```
| In theory, this should produce both `readOnly = True` and `nullable = True`, which is allowed per the OpenAPI spec.
This is not happening because `null=True` on the model is translated to `allow_null=True` on the serializer field which is stripped out when `read_only=True` is specified.
https://github.com/encode/django-rest-framework/blob/24a938abaadd98b5482bec33defd285625842342/rest_framework/serializers.py#L1327-L1333
It's not entirely clear at first glance why `allow_null` is removed since there doesn't appear to be any assertions explaining why these two wouldn't be allowed at the same time. My only guess is because normally this only applies to handling `null` in input data, but we do have code which also uses this for null coercion in outgoing data as well.
In theory, this should produce both `readOnly = True` and `nullable = True`, which is allowed per the OpenAPI spec.
This is not happening because `null=True` on the model is translated to `allow_null=True` on the serializer field which is stripped out when `read_only=True` is specified.
https://github.com/encode/django-rest-framework/blob/24a938abaadd98b5482bec33defd285625842342/rest_framework/serializers.py#L1327-L1333
It's not entirely clear at first glance why `allow_null` is removed since there doesn't appear to be any assertions explaining why these two wouldn't be allowed at the same time. My only guess is because normally this only applies to handling `null` in input data, but we do have code which also uses this for null coercion in outgoing data as well. | 2021-08-06T00:01:58 |
encode/django-rest-framework | 8,429 | encode__django-rest-framework-8429 | [
"8428"
] | 2506d0b4f2ac8bdbf35d33b3dd8a56f3e8d0da75 | diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py
--- a/rest_framework/renderers.py
+++ b/rest_framework/renderers.py
@@ -18,6 +18,7 @@
from django.template import engines, loader
from django.urls import NoReverseMatch
from django.utils.html import mark_safe
+from django.utils.safestring import SafeString
from rest_framework import VERSION, exceptions, serializers, status
from rest_framework.compat import (
@@ -1060,6 +1061,7 @@ def render(self, data, media_type=None, renderer_context=None):
class Dumper(yaml.Dumper):
def ignore_aliases(self, data):
return True
+ Dumper.add_representer(SafeString, Dumper.represent_str)
return yaml.dump(data, default_flow_style=False, sort_keys=False, Dumper=Dumper).encode('utf-8')
| diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py
--- a/tests/schemas/test_openapi.py
+++ b/tests/schemas/test_openapi.py
@@ -5,6 +5,7 @@
from django.db import models
from django.test import RequestFactory, TestCase, override_settings
from django.urls import path
+from django.utils.safestring import SafeString
from django.utils.translation import gettext_lazy as _
from rest_framework import filters, generics, pagination, routers, serializers
@@ -569,6 +570,11 @@ def test_openapi_yaml_rendering_without_aliases(self):
renderer.render(data) == b'o2:\n test: test\no1:\n test: test\n' # py <= 3.5
)
+ def test_openapi_yaml_safestring_render(self):
+ renderer = OpenAPIRenderer()
+ data = {'o1': SafeString('test')}
+ assert renderer.render(data) == b'o1: test\n'
+
def test_serializer_filefield(self):
path = '/{id}/'
method = 'POST'
| Unknown tag on redered schema when using Django's SafeString as help_text
### Discussed in https://github.com/encode/django-rest-framework/discussions/8402
Since:
- there's no response from the discussion thread,
- I think this is a valid issue, and
- I've found a possibly proper solution
I'll just put this as an issue and create a PR.
<div type='discussions-op-text'>
<sup>Originally posted by **hashlash** March 11, 2022</sup>
## The Issue
I have a model with SafeString as its help_text (inspired from [Django's password validation help text](https://github.com/django/django/blob/d90e34c61b27fba2527834806639eebbcfab9631/django/contrib/auth/password_validation.py#L84-L93)):
```py
from django.db import models
from django.utils.html import format_html, format_html_join
def list_help_text_html(help_texts):
help_items = format_html_join(
"", "<li>{}</li>", ((help_text,) for help_text in help_texts)
)
return format_html("<ul>{}</ul>", help_items) if help_items else ""
class ExampleModel(models.Model):
field = models.TextField(
help_text=list_help_text_html([
'info a',
'info b',
]),
)
```
I followed the DRF's doc about [Generating a dynamic schema with SchemaView](https://www.django-rest-framework.org/api-guide/schemas/#generating-a-dynamic-schema-with-schemaview) and [A minimal example with Swagger UI](https://www.django-rest-framework.org/topics/documenting-your-api/#a-minimal-example-with-swagger-ui), but the Swagger UI fails to render the generated schema.
```
Parser error on line 59
unknown tag !<tag:yaml.org,2002:python/object/new:django.utils.safestring.SafeString>
```
The generated schema ([full version](https://gist.github.com/hashlash/b7bc1b91b42625c6ac5ce7344299d8c7)):
```yaml
openapi: 3.0.2
info:
# redacted
paths:
# redacted
components:
schemas:
Example:
type: object
properties:
id:
# redacted
field:
type: string
description: !!python/object/new:django.utils.safestring.SafeString
- <ul><li>info a</li><li>info b</li></ul>
required:
- field
```
Here's [a repo](https://github.com/hashlash/django-demo/tree/drf/safestring-schema/bug) for demonstrating the bug. The Swagger UI can be accessed on `/swagger-ui/`.
Package versions:
```
django==3.2.12
djangorestframework==3.13.1
pyyaml==6.0
uritemplate==4.1.1
```
## Findings
I found that the schema generation for the help_text lies on:
https://github.com/encode/django-rest-framework/blob/a53e523f939332189b4ba8db7f99758b7d63e59b/rest_framework/schemas/openapi.py#L289-L290
and:
https://github.com/encode/django-rest-framework/blob/a53e523f939332189b4ba8db7f99758b7d63e59b/rest_framework/schemas/openapi.py#L537-L538
But since `SafeString` is a subclass of `str` and it override the `__str__()` method to return itself, those DRF's method will still return a `SafeString` object.
```py
class SafeString(str, SafeData):
...
def __str__(self):
return self
```
## Workaround
I've with 3 possible workarounds, and so far I think the third is the best:
- Adding the `SafeString` with an empty string ([implementation](https://github.com/hashlash/django-rest-framework/tree/str-add-fix), [demo](https://github.com/hashlash/django-demo/tree/drf/safestring-schema/str-add-fix))
```
>>> from django.utils.safestring import SafeString
>>> s = SafeString('abc')
>>> s + ''
'abc'
>>> type(s + '')
<class 'str'>
```
- Use `str.__str__()` ([implementation](https://github.com/hashlash/django-rest-framework/tree/str-str-fix), [demo](https://github.com/hashlash/django-demo/tree/drf/safestring-schema/str-str-fix))
```
>>> from django.utils.safestring import SafeString
>>> s = SafeString('abc')
>>> str.__str__(s)
'abc'
>>> type(str.__str__(s))
<class 'str'>
```
- Use `represent_str()` to represent `SafeString` as `str` ([implementation](https://github.com/hashlash/django-rest-framework/tree/yaml-representer-fix), [demo](https://github.com/hashlash/django-demo/tree/drf/safestring-schema/yaml-representation-fix))
```py
class OpenAPIRenderer(BaseRenderer):
...
def render(self, data, media_type=None, renderer_context=None):
class Dumper(yaml.Dumper):
...
Dumper.add_representer(SafeString, Dumper.represent_str)
return yaml.dump(data, default_flow_style=False, sort_keys=False, Dumper=Dumper).encode('utf-8')
```
PS: I also asked about the "string conversion" on [Django's forum](https://forum.djangoproject.com/t/convert-safestring-to-str/12549).</div>
| 2022-03-25T01:59:54 |
|
encode/django-rest-framework | 8,598 | encode__django-rest-framework-8598 | [
"8463"
] | 20d106d8a3f919d8fea2e7b9d1d26348a98c25cf | diff --git a/rest_framework/viewsets.py b/rest_framework/viewsets.py
--- a/rest_framework/viewsets.py
+++ b/rest_framework/viewsets.py
@@ -198,6 +198,10 @@ def get_extra_action_url_map(self):
for action in actions:
try:
url_name = '%s-%s' % (self.basename, action.url_name)
+ namespace = self.request.resolver_match.namespace
+ if namespace:
+ url_name = '%s:%s' % (namespace, url_name)
+
url = reverse(url_name, self.args, self.kwargs, request=self.request)
view = self.__class__(**action.kwargs)
action_urls[view.get_view_name()] = url
| Seems `Viewset`s `get_extra_action_url_map` method does not recognize namespaces
Seems `Viewset`s `get_extra_action_url_map` method does not recognize namespaces. I'm using different apps via Django URL namespaces ("<namespace>:<url name>") but the DRF action pull down menu will not provide it. My quick fix looks like:
```
def get_extra_action_url_map(self):
action_urls = OrderedDict()
# exit early if `detail` has not been provided
if self.detail is None:
return action_urls
# filter for the relevant extra actions
actions = [
action for action in self.get_extra_actions()
if action.detail == self.detail
]
for action in actions:
try:
url_name = '%s-%s' % (self.basename, action.url_name)
namespace = self.request.resolver_match.namespace
if namespace:
url_name = '%s:%s' % (namespace, url_name)
url = reverse(url_name, self.args, self.kwargs,
request=self.request)
view = self.__class__(**action.kwargs)
action_urls[view.get_view_name()] = url
except NoReverseMatch as exc:
pass # URL requires additional arguments, ignore
return action_urls
```
which basically add these two lines:
```
namespace = self.request.resolver_match.namespace
if namespace:
url_name = '%s:%s' % (namespace, url_name)
```
The fix works fine for me since years, but it seems that nobody else has been stumbled about it before.
Regards
Frank
_Originally posted by @backbohne in https://github.com/encode/django-rest-framework/discussions/7816_
Is there any specific reason why this fix is not merged?
| 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.
Tickets like this mostly get stuck because there's always associated risk that the change will break existing projects.
Personally I think that ViewSets and Routers are an overcomplicated abstraction that we introduced, and it's difficult to pick apart the impact of any changes around them.
If we *did* want to push forward with a change here, then the first step would be a pull request introducing this change, in order to determine if that breaks any existing tests. That'd at least give us *some* level of confidence in the change. | 2022-08-10T12:46:01 |
|
encode/django-rest-framework | 8,752 | encode__django-rest-framework-8752 | [
"8751"
] | cac89ae65defa1a89cb931106775314f0671bb46 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -104,6 +104,7 @@ def get_version(package):
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
+ 'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Internet :: WWW/HTTP',
],
| Add support to Python 3.11
## Checklist
- [ ] Raised initially as discussion #...
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [x] I have reduced the issue to the simplest possible case.
Add support to Python 3.11 in tests, docs and classifier.
| 2022-11-09T00:10:27 |
||
encode/django-rest-framework | 8,979 | encode__django-rest-framework-8979 | [
"8926"
] | d252d22343b9c9688db77b59aa72dabd540bd252 | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -609,6 +609,12 @@ def __init__(self, *args, **kwargs):
self.min_length = kwargs.pop('min_length', None)
assert self.child is not None, '`child` is a required argument.'
assert not inspect.isclass(self.child), '`child` has not been instantiated.'
+
+ instance = kwargs.get('instance', [])
+ data = kwargs.get('data', [])
+ if instance and data:
+ assert len(data) == len(instance), 'Data and instance should have same length'
+
super().__init__(*args, **kwargs)
self.child.bind(field_name='', parent=self)
@@ -683,7 +689,13 @@ def to_internal_value(self, data):
ret = []
errors = []
- for item in data:
+ for idx, item in enumerate(data):
+ if (
+ hasattr(self, 'instance')
+ and self.instance
+ and len(self.instance) > idx
+ ):
+ self.child.instance = self.instance[idx]
try:
validated = self.child.run_validation(item)
except ValidationError as exc:
| diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -2,6 +2,7 @@
import pickle
import re
import sys
+import unittest
from collections import ChainMap
from collections.abc import Mapping
@@ -783,3 +784,63 @@ def test_nested_key(self):
ret = {'a': 1}
self.s.set_value(ret, ['x', 'y'], 2)
assert ret == {'a': 1, 'x': {'y': 2}}
+
+
+class MyClass(models.Model):
+ name = models.CharField(max_length=100)
+ value = models.CharField(max_length=100, blank=True)
+
+ app_label = "test"
+
+ @property
+ def is_valid(self):
+ return self.name == 'valid'
+
+
+class MyClassSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = MyClass
+ fields = ('id', 'name', 'value')
+
+ def validate_value(self, value):
+ if value and not self.instance.is_valid:
+ raise serializers.ValidationError(
+ 'Status cannot be set for invalid instance')
+ return value
+
+
+class TestMultipleObjectsValidation(unittest.TestCase):
+ def setUp(self):
+ self.objs = [
+ MyClass(name='valid'),
+ MyClass(name='invalid'),
+ MyClass(name='other'),
+ ]
+
+ def test_multiple_objects_are_validated_separately(self):
+
+ serializer = MyClassSerializer(
+ data=[{'value': 'set', 'id': instance.id} for instance in
+ self.objs],
+ instance=self.objs,
+ many=True,
+ partial=True,
+ )
+
+ assert not serializer.is_valid()
+ assert serializer.errors == [
+ {},
+ {'value': ['Status cannot be set for invalid instance']},
+ {'value': ['Status cannot be set for invalid instance']}
+ ]
+
+ def test_exception_raised_when_data_and_instance_length_different(self):
+
+ with self.assertRaises(AssertionError):
+ MyClassSerializer(
+ data=[{'value': 'set', 'id': instance.id} for instance in
+ self.objs],
+ instance=self.objs[:-1],
+ many=True,
+ partial=True,
+ )
| Invalid `self.instance` when validating the serializer using `many=True`
Currently it is almost impossible to use the same serializer with and without `many=True` and the problem that sometimes serializer depending on the instance state or value during serialization and validation (usually it is PATCH method and `partial=True`
This is the simplest example to understand:
```python
from django.db import models
from rest_framework import serializers
class MyClass(models.Model):
name = models.CharField(max_length=100)
status = models.CharField(max_length=100, blank=True)
@property
def is_valid(self):
return self.name == 'valid'
class MyClassSerializer(serializers.ModelSerializer):
class Meta:
model = MyClass
fields = ('id', 'name', 'status')
def validate_status(self, value):
if value and not self.instance.is_valid:
raise serializers.ValidationError('Status cannot be set for invalid instance')
return value
objs = MyClass.objects.bulk_create(
objs=[
MyClass(name='valid'),
MyClass(name='invalid'),
MyClass(name='other'),
]
)
serializer = MyClassSerializer(
data=[{'status': 'set', 'id': instance.id} for instance in objs],
instance=objs,
many=True,
partial=True,
)
serializer.is_valid()
print(serializer.errors)
```
Please note that it is just an example and real serializers and models can be much more complex. The case is working when we pass the single instance to the serializer but not working when we are trying to validate `bulk` operation, like update in bulk (let's say)
The following exception raised:
```
AttributeError: 'list' object has no attribute 'is_valid'
```
When expected behavior would be to get this one (pretty-printed):
```
[
{},
{'status': [ErrorDetail(string='Status cannot be set for invalid instance', code='invalid')]},
{'status': [ErrorDetail(string='Status cannot be set for invalid instance', code='invalid')]},
]
```
P.S. I was able to manually patch the serializer to obtain the instance from the data provided, but I do not think that it should be done manually for every serializer. I assume that when we are validating the instance using PARTIAL, then the appropriate instance which is currently on validation, should be available inside the serializer. In this case we will be able to use the same serializer as single and multi entity-validation.
P.P.S. Also I think that if user require some logic for the list of objects, it should be placed inside the overridden `list_serializer_class`, no?
| I understand what you're trying to do here but I'm not sure how the values in the `data` list and the `objs` that you pass as the `instance` would correspond to each other. Would you assume that they are matched via indexes? Would you want to introduce a new keyword argument (e.g `instances`) just to make it clearer?
Also, from what I understand, `many` only works when you want serialize multiple objects into a list.
Interesting idea for a new feature, nonetheless. I know that Django does support [bulk updating](https://docs.djangoproject.com/en/4.2/ref/models/querysets/#bulk-update) so this should be possible to do. However, I'm not sure if the team behind DRF would want to add this to the core project at this point.
if anything is supported in django ORM core then that should be supported in DRF too.
My only concern is the mapping between the `data` and the `objs` in this example. Maybe instead of passing the `objs` it would be better to do something like this:
```python
serializer = MyClassSerializer(
data=[{'status': 'set', 'id': instance.id} for instance in objs],
key='id',
many=True,
partial=True,
)
```
This way the serializer can internally make a query to to fetch all objects based on the provided `key` (the argument doesn't have to have this name) and make a single query to fetch them. It could then do a bulk update as defined in the [Django Docs](https://docs.djangoproject.com/en/4.2/ref/models/querysets/)
So I did some more digging into it. The problem is caused by the following method:
```python
def validate_status(self, value):
if value and not self.instance.is_valid:
raise serializers.ValidationError('Status cannot be set for invalid instance')
return value
```
Specifically, it's caused by the `self.instance` is set to the value passed as `data`. Also, when you set `many` to `True`, the serializer that is declared is actually a `ListSerializer` instance. I'm not sure how we could make the `self.instance` variable point to the right `dict` object within the `data` list. From the looks of it, this would require significant reworking within the validation of the serializer classes. | 2023-05-10T20:31:02 |
encode/django-rest-framework | 9,030 | encode__django-rest-framework-9030 | [
"7469"
] | 8dd4250d0234ddf6c6a19a806639678ef7786468 | diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py
--- a/rest_framework/metadata.py
+++ b/rest_framework/metadata.py
@@ -11,6 +11,7 @@
from django.utils.encoding import force_str
from rest_framework import exceptions, serializers
+from rest_framework.fields import empty
from rest_framework.request import clone_request
from rest_framework.utils.field_mapping import ClassLookupDict
@@ -149,4 +150,7 @@ def get_field_info(self, field):
for choice_value, choice_name in field.choices.items()
]
+ if getattr(field, 'default', None) and field.default != empty and not callable(field.default):
+ field_info['default'] = field.default
+
return field_info
diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py
--- a/rest_framework/utils/field_mapping.py
+++ b/rest_framework/utils/field_mapping.py
@@ -9,6 +9,7 @@
from django.utils.text import capfirst
from rest_framework.compat import postgres_fields
+from rest_framework.fields import empty
from rest_framework.validators import UniqueValidator
NUMERIC_FIELD_TYPES = (
@@ -127,6 +128,9 @@ def get_field_kwargs(field_name, model_field):
kwargs['read_only'] = True
return kwargs
+ if model_field.default is not None and model_field.default != empty and not callable(model_field.default):
+ kwargs['default'] = model_field.default
+
if model_field.has_default() or model_field.blank or model_field.null:
kwargs['required'] = False
| diff --git a/tests/test_metadata.py b/tests/test_metadata.py
--- a/tests/test_metadata.py
+++ b/tests/test_metadata.py
@@ -184,6 +184,135 @@ def get_serializer(self):
assert response.status_code == status.HTTP_200_OK
assert response.data == expected
+ def test_actions_with_default(self):
+ """
+ On generic views OPTIONS should return an 'actions' key with metadata
+ on the fields with default that may be supplied to PUT and POST requests.
+ """
+ class NestedField(serializers.Serializer):
+ a = serializers.IntegerField(default=2)
+ b = serializers.IntegerField()
+
+ class ExampleSerializer(serializers.Serializer):
+ choice_field = serializers.ChoiceField(['red', 'green', 'blue'], default='red')
+ integer_field = serializers.IntegerField(
+ min_value=1, max_value=1000, default=1
+ )
+ char_field = serializers.CharField(
+ min_length=3, max_length=40, default="example"
+ )
+ list_field = serializers.ListField(
+ child=serializers.ListField(
+ child=serializers.IntegerField(default=1)
+ )
+ )
+ nested_field = NestedField()
+ uuid_field = serializers.UUIDField(label="UUID field")
+
+ class ExampleView(views.APIView):
+ """Example view."""
+ def post(self, request):
+ pass
+
+ def get_serializer(self):
+ return ExampleSerializer()
+
+ view = ExampleView.as_view()
+ response = view(request=request)
+ expected = {
+ 'name': 'Example',
+ 'description': 'Example view.',
+ 'renders': [
+ 'application/json',
+ 'text/html'
+ ],
+ 'parses': [
+ 'application/json',
+ 'application/x-www-form-urlencoded',
+ 'multipart/form-data'
+ ],
+ 'actions': {
+ 'POST': {
+ 'choice_field': {
+ 'type': 'choice',
+ 'required': False,
+ 'read_only': False,
+ 'label': 'Choice field',
+ "choices": [
+ {'value': 'red', 'display_name': 'red'},
+ {'value': 'green', 'display_name': 'green'},
+ {'value': 'blue', 'display_name': 'blue'}
+ ],
+ 'default': 'red'
+ },
+ 'integer_field': {
+ 'type': 'integer',
+ 'required': False,
+ 'read_only': False,
+ 'label': 'Integer field',
+ 'min_value': 1,
+ 'max_value': 1000,
+ 'default': 1
+ },
+ 'char_field': {
+ 'type': 'string',
+ 'required': False,
+ 'read_only': False,
+ 'label': 'Char field',
+ 'min_length': 3,
+ 'max_length': 40,
+ 'default': 'example'
+ },
+ 'list_field': {
+ 'type': 'list',
+ 'required': True,
+ 'read_only': False,
+ 'label': 'List field',
+ 'child': {
+ 'type': 'list',
+ 'required': True,
+ 'read_only': False,
+ 'child': {
+ 'type': 'integer',
+ 'required': False,
+ 'read_only': False,
+ 'default': 1
+ }
+ }
+ },
+ 'nested_field': {
+ 'type': 'nested object',
+ 'required': True,
+ 'read_only': False,
+ 'label': 'Nested field',
+ 'children': {
+ 'a': {
+ 'type': 'integer',
+ 'required': False,
+ 'read_only': False,
+ 'label': 'A',
+ 'default': 2
+ },
+ 'b': {
+ 'type': 'integer',
+ 'required': True,
+ 'read_only': False,
+ 'label': 'B'
+ }
+ }
+ },
+ 'uuid_field': {
+ 'type': 'string',
+ 'required': True,
+ 'read_only': False,
+ 'label': 'UUID field'
+ }
+ }
+ }
+ }
+ assert response.status_code == status.HTTP_200_OK
+ assert response.data == expected
+
def test_global_permissions(self):
"""
If a user does not have global permissions on an action, then any
diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py
--- a/tests/test_model_serializer.py
+++ b/tests/test_model_serializer.py
@@ -173,7 +173,7 @@ class Meta:
TestSerializer():
auto_field = IntegerField(read_only=True)
big_integer_field = IntegerField()
- boolean_field = BooleanField(required=False)
+ boolean_field = BooleanField(default=False, required=False)
char_field = CharField(max_length=100)
comma_separated_integer_field = CharField(max_length=100, validators=[<django.core.validators.RegexValidator object>])
date_field = DateField()
@@ -182,7 +182,7 @@ class Meta:
email_field = EmailField(max_length=100)
float_field = FloatField()
integer_field = IntegerField()
- null_boolean_field = BooleanField(allow_null=True, required=False)
+ null_boolean_field = BooleanField(allow_null=True, default=False, required=False)
positive_integer_field = IntegerField()
positive_small_integer_field = IntegerField()
slug_field = SlugField(allow_unicode=False, max_length=100)
@@ -210,7 +210,7 @@ class Meta:
length_limit_field = CharField(max_length=12, min_length=3)
blank_field = CharField(allow_blank=True, max_length=10, required=False)
null_field = IntegerField(allow_null=True, required=False)
- default_field = IntegerField(required=False)
+ default_field = IntegerField(default=0, required=False)
descriptive_field = IntegerField(help_text='Some help text', label='A label')
choices_field = ChoiceField(choices=(('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')))
text_choices_field = ChoiceField(choices=(('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')))
| ModelSerializer generate ChoicesField will discard default parameter
model
```python
class Brand(models.Model):
name = models.CharField(_("名称"), max_length=50, unique=True)
status = models.SmallIntegerField(
verbose_name=_("状态"),
choices=BrandStatus.choices,
default=BrandStatus.ENABLE.value,
help_text=make_markdown_table(BrandStatus.choices)
)
description = models.CharField(
_("描述"), max_length=300, null=True, blank=True
)
creator = models.ForeignKey(
"users.User", on_delete=models.CASCADE, verbose_name=_("拥有者")
)
created = models.DateTimeField(_("创建时间"), auto_now_add=True)
updated = models.DateTimeField(_("更新时间"), auto_now=True)
```
Serializer
```python
class BrandSerializer(serializers.ModelSerializer):
name = serializers.CharField(max_length=50, validators=[special_character])
created = serializers.DateTimeField(read_only=True)
updated = serializers.DateTimeField(read_only=True)
creator = serializers.ReadOnlyField(source="creator.username")
class Meta:
model = Brand
fields = "__all__"
```
swagger

So i find
> Serializers.ModelSerializer
```python
if 'choices' in field_kwargs:
# Fields with choices get coerced into `ChoiceField`
# instead of using their regular typed field.
field_class = self.serializer_choice_field
# Some model fields may introduce kwargs that would not be valid
# for the choice field. We need to strip these out.
# Eg. models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES)
valid_kwargs = {
'read_only', 'write_only',
'required', 'default', 'initial', 'source',
'label', 'help_text', 'style',
'error_messages', 'validators', 'allow_null', 'allow_blank',
'choices'
}
for key in list(field_kwargs):
if key not in valid_kwargs:
field_kwargs.pop(key)
```
default parameter not in valid_kwargs and will pop, but default in field_kwargs['field_kwargs']
I rewrite
```python
class ModelSerializer(serializers.ModelSerializer):
def build_standard_field(self, field_name, model_field):
field_kwargs = get_field_kwargs(field_name, model_field)
if 'choices' in field_kwargs:
# Fields with choices get coerced into `ChoiceField`
# instead of using their regular typed field.
field_class = self.serializer_choice_field
# Some model fields may introduce kwargs that would not be valid
# for the choice field. We need to strip these out.
# Eg. models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES)
valid_kwargs = {
'read_only', 'write_only',
'required', 'default', 'initial', 'source',
'label', 'help_text', 'style',
'error_messages', 'validators', 'allow_null', 'allow_blank',
'choices'
}
field_kwargs["default"] = field_kwargs["model_field"].default # add this
for key in list(field_kwargs):
if key not in valid_kwargs:
field_kwargs.pop(key)
else:
field_class, field_kwargs = super(ModelSerializer, self).build_standard_field(field_name, model_field)
return field_class, field_kwargs
```
swagger

| you can use the `extra_kwargs`, follow the link https://www.django-rest-framework.org/community/3.0-announcement/#the-extra_kwargs-option. Alternatively, specify the field explicitly on the serializer class. | 2023-07-01T11:09:02 |
encode/django-rest-framework | 9,208 | encode__django-rest-framework-9208 | [
"9206"
] | 0f39e0124d358b0098261f070175fa8e0359b739 | diff --git a/rest_framework/templatetags/rest_framework.py b/rest_framework/templatetags/rest_framework.py
--- a/rest_framework/templatetags/rest_framework.py
+++ b/rest_framework/templatetags/rest_framework.py
@@ -119,7 +119,7 @@ def optional_docs_login(request):
@register.simple_tag
-def optional_logout(request, user):
+def optional_logout(request, user, csrf_token):
"""
Include a logout snippet if REST framework's logout view is in the URLconf.
"""
@@ -135,11 +135,16 @@ def optional_logout(request, user):
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
- <li><a href='{href}?next={next}'>Log out</a></li>
+ <form id="logoutForm" method="post" action="{href}?next={next}">
+ <input type="hidden" name="csrfmiddlewaretoken" value="{csrf_token}">
+ </form>
+ <li>
+ <a href="#" onclick='document.getElementById("logoutForm").submit()'>Log out</a>
+ </li>
</ul>
</li>"""
- snippet = format_html(snippet, user=escape(user), href=logout_url, next=escape(request.path))
-
+ snippet = format_html(snippet, user=escape(user), href=logout_url,
+ next=escape(request.path), csrf_token=csrf_token)
return mark_safe(snippet)
| diff --git a/tests/browsable_api/test_browsable_api.py b/tests/browsable_api/test_browsable_api.py
--- a/tests/browsable_api/test_browsable_api.py
+++ b/tests/browsable_api/test_browsable_api.py
@@ -65,6 +65,12 @@ def test_login_shown_when_logged_out(self):
content = response.content.decode()
assert '>Log in<' in content
+ def test_dropdown_contains_logout_form(self):
+ self.client.login(username=self.username, password=self.password)
+ response = self.client.get('/')
+ content = response.content.decode()
+ assert '<form id="logoutForm" method="post" action="/auth/logout/?next=/">' in content
+
@override_settings(ROOT_URLCONF='tests.browsable_api.no_auth_urls')
class NoDropdownWithoutAuthTests(TestCase):
| rest_framework.urls doesn't work with LogoutView in Django 5.0
In Django 5.0, GET request for logout was removed (only POST supported now) and it seems like in DRF we still do GET request to the endpoint.
# https://docs.djangoproject.com/en/5.0/releases/5.0/
- Support for logging out via GET requests in the django.contrib.auth.views.LogoutView and django.contrib.auth.views.logout_then_login() is removed.
| can you share the traceback as well please? | 2024-01-03T20:08:19 |
encode/django-rest-framework | 9,278 | encode__django-rest-framework-9278 | [
"9274"
] | a2eabfc8673656493b76021b87d985f4ad647a02 | diff --git a/rest_framework/utils/representation.py b/rest_framework/utils/representation.py
--- a/rest_framework/utils/representation.py
+++ b/rest_framework/utils/representation.py
@@ -27,8 +27,8 @@ def smart_repr(value):
if isinstance(value, models.Manager):
return manager_repr(value)
- if isinstance(value, Promise) and value._delegate_text:
- value = force_str(value)
+ if isinstance(value, Promise):
+ value = force_str(value, strings_only=True)
value = repr(value)
| _delegate_text was removed in Django 5.
## Checklist
- [ ] Raised initially as discussion #...
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
- [ ] I have reduced the issue to the simplest possible case.
https://github.com/encode/django-rest-framework/blob/4c7c693f1555689cda88eb59a4353db69aa6f5b1/rest_framework/utils/representation.py#L30-L31
force_str has a built in parameter called `strings_only`. So the version number should be checked, and then if it is django 5, it should do the following instead of using delegate_text.
```python
value = force_str(value, strings_only=True)
```
| I'd make a pull request, if I had time, but you might get to this before I can, since it is relatively simple.
would be helpful If you could come with a PR | 2024-03-07T16:05:13 |
|
encode/django-rest-framework | 9,301 | encode__django-rest-framework-9301 | [
"9300"
] | 337ba211e82628c0a0bfc7340c45b22e725f8162 | diff --git a/rest_framework/authtoken/admin.py b/rest_framework/authtoken/admin.py
--- a/rest_framework/authtoken/admin.py
+++ b/rest_framework/authtoken/admin.py
@@ -28,7 +28,6 @@ class TokenAdmin(admin.ModelAdmin):
search_help_text = _('Username')
ordering = ('-created',)
actions = None # Actions not compatible with mapped IDs.
- autocomplete_fields = ("user",)
def get_changelist(self, request, **kwargs):
return TokenChangeList
| Error: An admin for model "User" has to be registered to be referenced by TokenAdmin.autocomplete_fields.
### Discussed in https://github.com/encode/django-rest-framework/discussions/9296
<div type='discussions-op-text'>
<sup>Originally posted by **kevinrenskers** March 18, 2024</sup>
After updating to DRF 3.15.0 I am now getting the following error when starting my Django server:
`<class 'rest_framework.authtoken.admin.TokenAdmin'>: (admin.E039) An admin for model "User" has to be registered to be referenced by TokenAdmin.autocomplete_fields.`
I am using a custom AdminSite instance where only the ModelAdmins that I specifically register to it are shown in my admin site. I have not registered TokenAdmin to my AdminSite, because it's not something we want to see in our admin site. I also have a custom User model, but its ModelAdmin is registered with my custom AdminSite.
It seems that DRF can't handle this situation. I guess that it only looks through the default AdminSite for what is registered there? How can I make DRF just ignore the TokenAdmin? I don't want it in our admin site, as we don't use tokens (only sessions).</div>
| I am also now seeing this error after bumping from 3.14.0 to 3.15.0. From Google, it appears this is coming from Django's command validation, not DRF specifically, but I believe it was introduced to DRF via [this pull request](https://github.com/encode/django-rest-framework/pull/8534/files), and it's unclear how to resolve the issue in DRF. The error suggests registering an admin model for "User", but [I already have been](https://github.com/HeliumEdu/platform/blob/1b5560eef0c90c29ae601804165266e113a54e09/helium/auth/admin.py#L123), and doing so before registering the `TokenAdmin`:
I do extend the AdminSite:
```python
class PlatformAdminSite(AdminSite):
"""
Creates a base AdminSite. Models and URLs should be attached to an instance of this class.
"""
site_header = settings.PROJECT_NAME + ' Administration'
site_title = site_header
index_title = settings.PROJECT_NAME
admin_site = PlatformAdminSite()
```
And register against that:
```python
from django.contrib.auth import admin, get_user_model
from rest_framework.authtoken import admin as drf_admin
from rest_framework.authtoken.models import Token
class UserAdmin(admin.UserAdmin, BaseModelAdmin):
# ... My extended UserAdmin code
class TokenAdmin(drf_admin.TokenAdmin):
# ... My extended TokenAdmin code
# Then register the models to the admin
admin_site.register(get_user_model(), UserAdmin)
admin_site.register(Token, TokenAdmin)
```
It fails with this error. If I register directly against `admin.site.register` instead of my extended `AdminSite`, it works again. So what has changed with this release, and what do we need to change? Do we need to register something elsewhere, or has the way we need to extend `AdminSite` changed?
I noticed that you have a custom `User` model, right? So I _think_ what happens is:
- Django register the default User model with the default admin
- DRF register the TokenProxy model with the default admin. But this model references your custom User model: https://github.com/encode/django-rest-framework/blob/337ba211e82628c0a0bfc7340c45b22e725f8162/rest_framework/authtoken/admin.py#L11
However, Django checks that the `autocomplete_fields` matches a model which is registered in the admin, but the user model registered in the default admin is the default one, not the custom one.
The simplest thing might be to revert the PR that caused it (I was waiting for this specific fix, but it doesn't work in all cases) and perhaps expand the documentation, [which already explains how to patch the `TokenAdmin`](https://www.django-rest-framework.org/api-guide/authentication/#with-django-admin). If folks want auto-complete fields, they can fix it in user land. | 2024-03-18T15:06:35 |
|
encode/django-rest-framework | 9,303 | encode__django-rest-framework-9303 | [
"9291"
] | 337ba211e82628c0a0bfc7340c45b22e725f8162 | diff --git a/rest_framework/compat.py b/rest_framework/compat.py
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -46,6 +46,12 @@ def unicode_http_header(value):
except ImportError:
yaml = None
+# inflection is optional
+try:
+ import inflection
+except ImportError:
+ inflection = None
+
# requests is optional
try:
diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py
--- a/rest_framework/schemas/openapi.py
+++ b/rest_framework/schemas/openapi.py
@@ -14,7 +14,7 @@
from rest_framework import (
RemovedInDRF315Warning, exceptions, renderers, serializers
)
-from rest_framework.compat import uritemplate
+from rest_framework.compat import inflection, uritemplate
from rest_framework.fields import _UnvalidatedField, empty
from rest_framework.settings import api_settings
@@ -247,9 +247,8 @@ def get_operation_id_base(self, path, method, action):
name = name[:-len(action)]
if action == 'list':
- from inflection import pluralize
-
- name = pluralize(name)
+ assert inflection, '`inflection` must be installed for OpenAPI schema support.'
+ name = inflection.pluralize(name)
return name
| 3.15 missing package inflection
New issue in the `3.15` release where if you use `generateschema` and have a list in your output you will get a `ModuleNotFound` error.
```
> [19/21] RUN poetry run python manage.py generateschema --file /code/templates/openapi-schema.yml:
2.585 Traceback (most recent call last):
2.586 File "/code/manage.py", line 22, in <module>
2.587 main()
2.588 File "/code/manage.py", line 18, in main
2.589 execute_from_command_line(sys.argv)
2.590 File "/root/.cache/pypoetry/virtualenvs/allfactors-django-MATOk_fk-py3.12/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
2.590 utility.execute()
2.591 File "/root/.cache/pypoetry/virtualenvs/allfactors-django-MATOk_fk-py3.12/lib/python3.12/site-packages/django/core/management/__init__.py", line 436, in execute
2.592 self.fetch_command(subcommand).run_from_argv(self.argv)
2.593 File "/root/.cache/pypoetry/virtualenvs/allfactors-django-MATOk_fk-py3.12/lib/python3.12/site-packages/django/core/management/base.py", line 412, in run_from_argv
2.593 self.execute(*args, **cmd_options)
2.594 File "/root/.cache/pypoetry/virtualenvs/allfactors-django-MATOk_fk-py3.12/lib/python3.12/site-packages/django/core/management/base.py", line 458, in execute
2.595 output = self.handle(*args, **options)
2.596 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2.600 File "/root/.cache/pypoetry/virtualenvs/allfactors-django-MATOk_fk-py3.12/lib/python3.12/site-packages/rest_framework/management/commands/generateschema.py", line 43, in handle
2.601 schema = generator.get_schema(request=None, public=True)
2.602 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2.606 File "/root/.cache/pypoetry/virtualenvs/allfactors-django-MATOk_fk-py3.12/lib/python3.12/site-packages/rest_framework/schemas/openapi.py", line 80, in get_schema
2.608 operation = view.schema.get_operation(path, method)
2.608 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2.608 File "/root/.cache/pypoetry/virtualenvs/allfactors-django-MATOk_fk-py3.12/lib/python3.12/site-packages/rest_framework/schemas/openapi.py", line 146, in get_operation
2.608 operation['operationId'] = self.get_operation_id(path, method)
2.608 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2.608 File "/root/.cache/pypoetry/virtualenvs/allfactors-django-MATOk_fk-py3.12/lib/python3.12/site-packages/rest_framework/schemas/openapi.py", line 268, in get_operation_id
2.608 name = self.get_operation_id_base(path, method, action)
2.608 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2.608 File "/root/.cache/pypoetry/virtualenvs/allfactors-django-MATOk_fk-py3.12/lib/python3.12/site-packages/rest_framework/schemas/openapi.py", line 250, in get_operation_id_base
2.608 from inflection import pluralize
2.608 ModuleNotFoundError: No module named 'inflection'
```
| Ah yep, needs resolving.
Introduced by PR https://github.com/encode/django-rest-framework/pull/8017.
Ooptions...
* Revert the PR. (Marginally incorrect naming is better than broken behavior)
* Add the dependency
I vote for including the dependency
One other idea:
```
try:
from inflection import pluralize
except ImportError:
def pluralize(input):
if not input.endswith('s'):
input += "s"
``` | 2024-03-18T19:04:23 |
|
encode/django-rest-framework | 9,326 | encode__django-rest-framework-9326 | [
"9317"
] | 56a5b354d0f82ea7e0df5cc4aa5187fe8450cbcb | diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py
--- a/rest_framework/exceptions.py
+++ b/rest_framework/exceptions.py
@@ -144,30 +144,17 @@ class ValidationError(APIException):
status_code = status.HTTP_400_BAD_REQUEST
default_detail = _('Invalid input.')
default_code = 'invalid'
- default_params = {}
- def __init__(self, detail=None, code=None, params=None):
+ def __init__(self, detail=None, code=None):
if detail is None:
detail = self.default_detail
if code is None:
code = self.default_code
- if params is None:
- params = self.default_params
# For validation failures, we may collect many errors together,
# so the details should always be coerced to a list if not already.
- if isinstance(detail, str):
- detail = [detail % params]
- elif isinstance(detail, ValidationError):
- detail = detail.detail
- elif isinstance(detail, (list, tuple)):
- final_detail = []
- for detail_item in detail:
- if isinstance(detail_item, ValidationError):
- final_detail += detail_item.detail
- else:
- final_detail += [detail_item % params if isinstance(detail_item, str) else detail_item]
- detail = final_detail
+ if isinstance(detail, tuple):
+ detail = list(detail)
elif not isinstance(detail, dict) and not isinstance(detail, list):
detail = [detail]
| diff --git a/tests/test_validation_error.py b/tests/test_validation_error.py
--- a/tests/test_validation_error.py
+++ b/tests/test_validation_error.py
@@ -109,89 +109,3 @@ def test_validation_error_details(self):
assert len(error.detail) == 2
assert str(error.detail[0]) == 'message1'
assert str(error.detail[1]) == 'message2'
-
-
-class TestValidationErrorWithDjangoStyle(TestCase):
- def test_validation_error_details(self):
- error = ValidationError('Invalid value: %(value)s', params={'value': '42'})
- assert str(error.detail[0]) == 'Invalid value: 42'
-
- def test_validation_error_details_tuple(self):
- error = ValidationError(
- detail=('Invalid value: %(value1)s', 'Invalid value: %(value2)s'),
- params={'value1': '42', 'value2': '43'},
- )
- assert isinstance(error.detail, list)
- assert len(error.detail) == 2
- assert str(error.detail[0]) == 'Invalid value: 42'
- assert str(error.detail[1]) == 'Invalid value: 43'
-
- def test_validation_error_details_list(self):
- error = ValidationError(
- detail=['Invalid value: %(value1)s', 'Invalid value: %(value2)s', ],
- params={'value1': '42', 'value2': '43'}
- )
- assert isinstance(error.detail, list)
- assert len(error.detail) == 2
- assert str(error.detail[0]) == 'Invalid value: 42'
- assert str(error.detail[1]) == 'Invalid value: 43'
-
- def test_validation_error_details_validation_errors(self):
- error = ValidationError(
- detail=ValidationError(
- detail='Invalid value: %(value1)s',
- params={'value1': '42'},
- ),
- )
- assert isinstance(error.detail, list)
- assert len(error.detail) == 1
- assert str(error.detail[0]) == 'Invalid value: 42'
-
- def test_validation_error_details_validation_errors_list(self):
- error = ValidationError(
- detail=[
- ValidationError(
- detail='Invalid value: %(value1)s',
- params={'value1': '42'},
- ),
- ValidationError(
- detail='Invalid value: %(value2)s',
- params={'value2': '43'},
- ),
- 'Invalid value: %(value3)s'
- ],
- params={'value3': '44'}
- )
- assert isinstance(error.detail, list)
- assert len(error.detail) == 3
- assert str(error.detail[0]) == 'Invalid value: 42'
- assert str(error.detail[1]) == 'Invalid value: 43'
- assert str(error.detail[2]) == 'Invalid value: 44'
-
- def test_validation_error_details_validation_errors_nested_list(self):
- error = ValidationError(
- detail=[
- ValidationError(
- detail='Invalid value: %(value1)s',
- params={'value1': '42'},
- ),
- ValidationError(
- detail=[
- 'Invalid value: %(value2)s',
- ValidationError(
- detail='Invalid value: %(value3)s',
- params={'value3': '44'},
- )
- ],
- params={'value2': '43'},
- ),
- 'Invalid value: %(value4)s'
- ],
- params={'value4': '45'}
- )
- assert isinstance(error.detail, list)
- assert len(error.detail) == 4
- assert str(error.detail[0]) == 'Invalid value: 42'
- assert str(error.detail[1]) == 'Invalid value: 43'
- assert str(error.detail[2]) == 'Invalid value: 44'
- assert str(error.detail[3]) == 'Invalid value: 45'
| 3.15 regression: ListSerializer ValidationErrors silently changed return type
- [`ListSerializer.errors` has type `ReturnList`](https://github.com/encode/django-rest-framework/blob/77ef27f18fc7c11e1d2e5fd4aaa8acc51cda6792/rest_framework/serializers.py#L808).
- When raising, #8863 [silently casts this into a list](https://github.com/encode/django-rest-framework/pull/8863/files#diff-2b352f708f44b59b1c568d234dafdfc405760d55eaee4fed1ee9fbd140d49886R163).
- As a result, the exceptions `.detail` attribute is no longer of type `ReturnList`.
- As a result, the `.detail.serializer` attribute is no longer available. [That attribute is the whole point of the existence of `ReturnList`.](https://github.com/encode/django-rest-framework/blob/77ef27f18fc7c11e1d2e5fd4aaa8acc51cda6792/rest_framework/utils/serializer_helpers.py#L49-L54)
This is a breaking change in a public API and should be reverted.
| 2024-03-21T15:56:12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.