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 | 4,285 | encode__django-rest-framework-4285 | [
"4265"
] | 6d4ada05ecd145714d9afaf3417f950389b57792 | diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -111,7 +111,6 @@ def get_api_endpoints(self, patterns, prefix=''):
for pattern in patterns:
path_regex = prefix + pattern.regex.pattern
-
if isinstance(pattern, RegexURLPattern):
path = self.get_path(path_regex)
callback = pattern.callback
@@ -253,6 +252,9 @@ def get_serializer_fields(self, path, method, callback, view):
fields = []
+ if not (hasattr(view, 'get_serializer_class') and callable(getattr(view, 'get_serializer_class'))):
+ return []
+
serializer_class = view.get_serializer_class()
serializer = serializer_class()
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -5,8 +5,11 @@
from rest_framework import filters, pagination, permissions, serializers
from rest_framework.compat import coreapi
+from rest_framework.response import Response
from rest_framework.routers import DefaultRouter
+from rest_framework.schemas import SchemaGenerator
from rest_framework.test import APIClient
+from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
@@ -31,11 +34,24 @@ class ExampleViewSet(ModelViewSet):
serializer_class = ExampleSerializer
+class ExampleView(APIView):
+ permission_classes = [permissions.IsAuthenticatedOrReadOnly]
+
+ def get(self, request, *args, **kwargs):
+ return Response()
+
+ def post(self, request, *args, **kwargs):
+ return Response()
+
+
router = DefaultRouter(schema_title='Example API' if coreapi else None)
router.register('example', ExampleViewSet, base_name='example')
urlpatterns = [
url(r'^', include(router.urls))
]
+urlpatterns2 = [
+ url(r'^example-view/$', ExampleView.as_view(), name='example-view')
+]
@unittest.skipUnless(coreapi, 'coreapi is not installed')
@@ -135,3 +151,29 @@ def test_authenticated_request(self):
}
)
self.assertEqual(response.data, expected)
+
+
[email protected](coreapi, 'coreapi is not installed')
+class TestSchemaGenerator(TestCase):
+ def test_view(self):
+ schema_generator = SchemaGenerator(title='Test View', patterns=urlpatterns2)
+ schema = schema_generator.get_schema()
+ expected = coreapi.Document(
+ url='',
+ title='Test View',
+ content={
+ 'example-view': {
+ 'create': coreapi.Link(
+ url='/example-view/',
+ action='post',
+ fields=[]
+ ),
+ 'read': coreapi.Link(
+ url='/example-view/',
+ action='get',
+ fields=[]
+ )
+ }
+ }
+ )
+ self.assertEquals(schema, expected)
| SchemaGenerator fails with message "object has no attribute 'get_serializer_class'"
Hi,
I just upgraded to 3.4.0 of django-rest-framework. In my application i have a API view which doesn't have a GET method implemented only POST is there.
Now i am trying to auto generate the schema using the tutorial given. Here is my code for the schema view.
```
from rest_framework.decorators import api_view, renderer_classes
from rest_framework import renderers, schemas
@api_view()
@renderer_classes([renderers.CoreJSONRenderer, ])
def schema_view(request):
generator = schemas.SchemaGenerator(title='Bookings API')
return generator.get_schema()
```
Now when i try to view this schema i am getting this error.
```
Traceback (most recent call last):
File "/home/ashish/Env/backend/lib/python3.4/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/ashish/Env/backend/lib/python3.4/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ashish/Env/backend/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/ashish/Env/backend/lib/python3.4/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/ashish/Env/backend/lib/python3.4/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/home/ashish/Env/backend/lib/python3.4/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/home/ashish/Env/backend/lib/python3.4/site-packages/rest_framework/decorators.py", line 52, in handler
return func(*args, **kwargs)
File "/home/ashish/Projects/backend/oyster/config/swagger.py", line 7, in schema_view
generator = schemas.SchemaGenerator(title='Bookings API')
File "/home/ashish/Env/backend/lib/python3.4/site-packages/rest_framework/schemas.py", line 74, in __init__
self.endpoints = self.get_api_endpoints(patterns)
File "/home/ashish/Env/backend/lib/python3.4/site-packages/rest_framework/schemas.py", line 128, in get_api_endpoints
prefix=path_regex
File "/home/ashish/Env/backend/lib/python3.4/site-packages/rest_framework/schemas.py", line 121, in get_api_endpoints
link = self.get_link(path, method, callback)
File "/home/ashish/Env/backend/lib/python3.4/site-packages/rest_framework/schemas.py", line 196, in get_link
fields += self.get_serializer_fields(path, method, callback, view)
File "/home/ashish/Env/backend/lib/python3.4/site-packages/rest_framework/schemas.py", line 256, in get_serializer_fields
serializer_class = view.get_serializer_class()
AttributeError: 'LogoutView' object has no attribute 'get_serializer_class'
```
Here is my LogoutView class..
```
class LogoutView(APIView):
permission_classes = (AllowAny,)
def post(self, request):
return self.logout(request)
def logout(self, request):
try:
request.user.auth_token.delete()
except (AttributeError, ObjectDoesNotExist):
pass
logout(request)
log.info('Logout Successful | %s' % request.user)
content = {'success': settings.USERS_LOGOUT_MSG}
return Response(content, status=status.HTTP_200_OK)
```
Am i missing something? What needs to be done to auto generate the schema?
| I am also seeing a similar error. Except, that the call to `view.get_serializer_class` from my `ModelViewSet` gets into the `get_serializer_class` method and fails when it doesn't have the `request` attribute.
Is there any update on this one? I will try to write a failing test case ...
@geekashu
Have you defined a serializer for this view? You should either have a `serializer_class = X` or override `get_serializer_class()` ?
The OP mentions an `APIView` and I'm not sure `SchemaGenerator` do work with them which is why I removed the bug status.
@lwm test case would definitively help get this fixed faster.
@lwm No i haven't defined a serializer for this view.
@xordoquy SchemaGenerator should work with all APIView as per this [comment](https://github.com/tomchristie/django-rest-framework/pull/4179#discussion_r69324115)
I am getting the same error on my function based views. My view looks sort of like this
<pre>
@api_view(['GET', 'POST'])
@authentication_classes((CustomAuthentication, ))
@permission_classes((CustomPermission, ))
def get_all(request):
return Response(CustomSerializer(CustomModel.objects.all(), many=True).data)
</pre>
Before you ask, I have to support both GET and POST for legacy reasons.
Issue is easy to re-recreate - basically when SchemaGenerator iterates through API views and any of them derived from `APIView`, simply because it does not have this method.
| 2016-07-19T10:55:08 |
encode/django-rest-framework | 4,313 | encode__django-rest-framework-4313 | [
"4281"
] | f9df0dc9657e5d765d924e3b1887cf59bbb5a680 | diff --git a/rest_framework/response.py b/rest_framework/response.py
--- a/rest_framework/response.py
+++ b/rest_framework/response.py
@@ -51,9 +51,11 @@ def __init__(self, data=None, status=None,
@property
def rendered_content(self):
renderer = getattr(self, 'accepted_renderer', None)
+ accepted_media_type = getattr(self, 'accepted_media_type', None)
context = getattr(self, 'renderer_context', None)
assert renderer, ".accepted_renderer not set on Response"
+ assert accepted_media_type, ".accepted_media_type not set on Response"
assert context, ".renderer_context not set on Response"
context['response'] = self
@@ -67,7 +69,7 @@ def rendered_content(self):
content_type = media_type
self['Content-Type'] = content_type
- ret = renderer.render(self.data, media_type, context)
+ ret = renderer.render(self.data, accepted_media_type, context)
if isinstance(ret, six.text_type):
assert charset, (
'renderer returned unicode, and did not specify '
diff --git a/rest_framework/routers.py b/rest_framework/routers.py
--- a/rest_framework/routers.py
+++ b/rest_framework/routers.py
@@ -276,6 +276,8 @@ class DefaultRouter(SimpleRouter):
default_schema_renderers = [renderers.CoreJSONRenderer]
def __init__(self, *args, **kwargs):
+ if 'schema_renderers' in kwargs:
+ assert 'schema_title' in kwargs, 'Missing "schema_title" argument.'
self.schema_title = kwargs.pop('schema_title', None)
self.schema_renderers = kwargs.pop('schema_renderers', self.default_schema_renderers)
super(DefaultRouter, self).__init__(*args, **kwargs)
| diff --git a/tests/test_negotiation.py b/tests/test_negotiation.py
--- a/tests/test_negotiation.py
+++ b/tests/test_negotiation.py
@@ -10,6 +10,11 @@
factory = APIRequestFactory()
+class MockOpenAPIRenderer(BaseRenderer):
+ media_type = 'application/openapi+json;version=2.0'
+ format = 'swagger'
+
+
class MockJSONRenderer(BaseRenderer):
media_type = 'application/json'
@@ -24,7 +29,7 @@ class NoCharsetSpecifiedRenderer(BaseRenderer):
class TestAcceptedMediaType(TestCase):
def setUp(self):
- self.renderers = [MockJSONRenderer(), MockHTMLRenderer()]
+ self.renderers = [MockJSONRenderer(), MockHTMLRenderer(), MockOpenAPIRenderer()]
self.negotiator = DefaultContentNegotiation()
def select_renderer(self, request):
@@ -44,3 +49,9 @@ def test_client_overspecifies_accept_use_client(self):
request = Request(factory.get('/', HTTP_ACCEPT='application/json; indent=8'))
accepted_renderer, accepted_media_type = self.select_renderer(request)
self.assertEqual(accepted_media_type, 'application/json; indent=8')
+
+ def test_client_specifies_parameter(self):
+ request = Request(factory.get('/', HTTP_ACCEPT='application/openapi+json;version=2.0'))
+ accepted_renderer, accepted_media_type = self.select_renderer(request)
+ self.assertEqual(accepted_media_type, 'application/openapi+json;version=2.0')
+ self.assertEqual(accepted_renderer.format, 'swagger')
| JSON indent parameter in Accept header ignored
Refactoring between 3.3.3 and 3.4.0 changed how `Response.render` passes `media_type` to its `renderer`.
[Response](https://github.com/tomchristie/django-rest-framework/blob/e476c222f98c4a455bf806fa05c5d70a9e0f37da/rest_framework/response.py#L60) sets it as `media_type = renderer.media_type` compared to `self.accepted_media_type` (set via `APIView.finalize_response` [here](https://github.com/tomchristie/django-rest-framework/blob/e476c222f98c4a455bf806fa05c5d70a9e0f37da/rest_framework/views.py#L405)).
Since `renderer.media_type` looses the indent parameter (i.e. `application/json; indent=4` becomes `application/json`), the resulting JSON rendering is not indented.
A 'simple' fix is to restore the 3.3.3 code where `media_type = getattr(self, 'accepted_media_type', None)` but I haven't made a PR yet because I'm not clear as to whether there was a specific reason for changing to `renderer.media_type` (which might have overlooked that it doesn't include `indent`).
| I can confirm, the media_type value that get_ident receives is stripped of params.
| 2016-07-27T10:32:21 |
encode/django-rest-framework | 4,314 | encode__django-rest-framework-4314 | [
"4289"
] | 351e0a4a99a6505b01718aa8926b6e466e43dcb0 | diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -278,7 +278,7 @@ def get_pagination_fields(self, path, method, callback, view):
if hasattr(callback, 'actions') and ('list' not in callback.actions.values()):
return []
- if not hasattr(view, 'pagination_class'):
+ if not getattr(view, 'pagination_class', None):
return []
paginator = view.pagination_class()
| Schemas Generator produces error for views with no pagination 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](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 TaskList(generics.ListCreateAPIView):
queryset = TaskModel.objects.all()
serializer_class = TaskSerializer
pagination_class = None
class ApiDocView(APIView):
def get(self, request, format=None):
generator = schemas.SchemaGenerator(title='API')
return Response(generator.get_schema(request=request))
```
## Expected behavior
Schema generator should consider views with pagination_class = None.
This issue is similar to #4265
## Actual behavior
Schema generator gives error
File "/path/to/env/local/lib/python2.7/site-packages/rest_framework/schemas.py", line 284, in get_pagination_fields
paginator = view.pagination_class()
TypeError: 'NoneType' object is not callable
| 2016-07-27T11:52:51 |
||
encode/django-rest-framework | 4,315 | encode__django-rest-framework-4315 | [
"4293"
] | 8ebf81b1502bee067fe842fa23442aa4bc176473 | diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -84,6 +84,7 @@ def get_schema(self, request=None):
method = link.action.upper()
view = callback.cls()
view.request = clone_request(request, method)
+ view.format_kwarg = None
try:
view.check_permissions(view.request)
except exceptions.APIException:
| SchemaGenerator: 'FooViewSet' object has no attribute 'format_kwarg'
## 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
Using the new schema generation via `DefaultRouter`, hook a `ViewSet` into it.
## Expected behavior
A schema is generated for the `ViewSet`.
## Actual behavior
`AttributeError: 'AddressViewSet' object has no attribute 'format_kwarg'`
| I managed to avoid #4265 and #4278 but then ran into this.
| 2016-07-27T12:03:19 |
|
encode/django-rest-framework | 4,316 | encode__django-rest-framework-4316 | [
"4294"
] | 3586c8a61ae0dd3424c49b50f22a7699e999bae7 | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -1396,9 +1396,8 @@ def get_unique_together_validators(self):
# cannot map to a field, and must be a traversal, so we're not
# including those.
field_names = {
- field.source for field in self.fields.values()
+ field.source for field in self._writable_fields
if (field.source != '*') and ('.' not in field.source)
- and not field.read_only
}
# Note that we make sure to check `unique_together` both on the
| default=CurrentUserDefault and read_only=True in DRF 3.4.0 broken if unique_together is being used in a Model for a ModelSerializer
## 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
``` python
import django
django.setup()
from django.contrib.auth import get_user_model
from django.db import models
from django.conf import settings
from rest_framework import serializers, test
class Item(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
item_number = models.IntegerField()
class Meta:
unique_together = (('user', 'item_number'),)
class ItemSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(read_only=True,
default=serializers.CurrentUserDefault())
class Meta:
model = Item
fields = ('id', 'item_number', 'user')
User = get_user_model()
user = User.objects.create_user(username='asdf')
request = test.APIRequestFactory().post('/')
request.user = user
item = Item.objects.create(user=user, item_number=3)
data = {'item_number': item.item_number}
context = {'request': request}
serializer = ItemSerializer(data=data, context=context)
assert not serializer.is_valid(), 'Should be False!'
```
## Expected behavior
The serializer should not be valid. This is the case using djangorestframework == 3.3.0
## Actual behavior
The serializer is valid. This is the case using djangorestframework == 3.4.0
I've tracked the root of the issue and it seems to be pull request #4192, where a new condition is added to `get_unique_together_validators()`: "`and not field.read_only`"
| 2016-07-27T14:17:00 |
||
encode/django-rest-framework | 4,321 | encode__django-rest-framework-4321 | [
"4305"
] | 6a7d34ec3452d4e8534f5c9bd238405548485a7a | diff --git a/rest_framework/compat.py b/rest_framework/compat.py
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -23,6 +23,12 @@
from django.utils import importlib # Will be removed in Django 1.9
+try:
+ import urlparse # Python 2.x
+except ImportError:
+ import urllib.parse as urlparse
+
+
def unicode_repr(instance):
# Get the repr of an instance, but ensure it is a unicode string
# on both python 3 (already the case) and 2 (not the case).
diff --git a/rest_framework/routers.py b/rest_framework/routers.py
--- a/rest_framework/routers.py
+++ b/rest_framework/routers.py
@@ -278,11 +278,14 @@ class DefaultRouter(SimpleRouter):
def __init__(self, *args, **kwargs):
if 'schema_renderers' in kwargs:
assert 'schema_title' in kwargs, 'Missing "schema_title" argument.'
+ if 'schema_url' in kwargs:
+ assert 'schema_title' in kwargs, 'Missing "schema_title" argument.'
self.schema_title = kwargs.pop('schema_title', None)
+ self.schema_url = kwargs.pop('schema_url', None)
self.schema_renderers = kwargs.pop('schema_renderers', self.default_schema_renderers)
super(DefaultRouter, self).__init__(*args, **kwargs)
- def get_api_root_view(self, schema_urls=None):
+ def get_api_root_view(self, api_urls=None):
"""
Return a view to use as the API root.
"""
@@ -294,11 +297,12 @@ def get_api_root_view(self, schema_urls=None):
view_renderers = list(api_settings.DEFAULT_RENDERER_CLASSES)
schema_media_types = []
- if schema_urls and self.schema_title:
+ if api_urls and self.schema_title:
view_renderers += list(self.schema_renderers)
schema_generator = SchemaGenerator(
title=self.schema_title,
- patterns=schema_urls
+ url=self.schema_url,
+ patterns=api_urls
)
schema_media_types = [
renderer.media_type
@@ -347,7 +351,7 @@ def get_urls(self):
urls = super(DefaultRouter, self).get_urls()
if self.include_root_view:
- view = self.get_api_root_view(schema_urls=urls)
+ view = self.get_api_root_view(api_urls=urls)
root_url = url(r'^$', view, name=self.root_view_name)
urls.append(root_url)
diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -6,7 +6,7 @@
from django.utils import six
from rest_framework import exceptions, serializers
-from rest_framework.compat import coreapi, uritemplate
+from rest_framework.compat import coreapi, uritemplate, urlparse
from rest_framework.request import clone_request
from rest_framework.views import APIView
@@ -57,7 +57,7 @@ class SchemaGenerator(object):
'delete': 'destroy',
}
- def __init__(self, title=None, patterns=None, urlconf=None):
+ def __init__(self, title=None, url=None, patterns=None, urlconf=None):
assert coreapi, '`coreapi` must be installed for schema support.'
if patterns is None and urlconf is not None:
@@ -70,7 +70,11 @@ def __init__(self, title=None, patterns=None, urlconf=None):
urls = import_module(settings.ROOT_URLCONF)
patterns = urls.urlpatterns
+ if url and not url.endswith('/'):
+ url += '/'
+
self.title = title
+ self.url = url
self.endpoints = self.get_api_endpoints(patterns)
def get_schema(self, request=None):
@@ -102,7 +106,7 @@ def get_schema(self, request=None):
insert_into(content, key, link)
# Return the schema document.
- return coreapi.Document(title=self.title, content=content)
+ return coreapi.Document(title=self.title, content=content, url=self.url)
def get_api_endpoints(self, patterns, prefix=''):
"""
@@ -203,7 +207,7 @@ def get_link(self, path, method, callback):
encoding = None
return coreapi.Link(
- url=path,
+ url=urlparse.urljoin(self.url, path),
action=method.lower(),
encoding=encoding,
fields=fields
| SchemaGenerator is not using the SCRIPT_NAME in the url
## 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
Deploy your django project on a subpath with a proxy and make sure to set the SCRIPT_NAME header.
## Expected behavior
Urls in the schema to be using the URLs with the SCRIPT_NAME prepended.
## Actual behavior
URLs without the SCRIPT_NAME making the Django REST Swagger UI unusable, since its calling to the wrong URLs.
Also see this ticket at the Django REST Swagger repo: https://github.com/marcgibbons/django-rest-swagger/issues/494#issuecomment-234598025
| 2016-07-28T10:57:26 |
||
encode/django-rest-framework | 4,323 | encode__django-rest-framework-4323 | [
"4268"
] | 061e0ed0841274da930f61838c60af1324ea04bc | diff --git a/rest_framework/routers.py b/rest_framework/routers.py
--- a/rest_framework/routers.py
+++ b/rest_framework/routers.py
@@ -283,6 +283,10 @@ def __init__(self, *args, **kwargs):
self.schema_title = kwargs.pop('schema_title', None)
self.schema_url = kwargs.pop('schema_url', None)
self.schema_renderers = kwargs.pop('schema_renderers', self.default_schema_renderers)
+ if 'root_renderers' in kwargs:
+ self.root_renderers = kwargs.pop('root_renderers')
+ else:
+ self.root_renderers = list(api_settings.DEFAULT_RENDERER_CLASSES)
super(DefaultRouter, self).__init__(*args, **kwargs)
def get_api_root_view(self, api_urls=None):
@@ -294,7 +298,7 @@ def get_api_root_view(self, api_urls=None):
for prefix, viewset, basename in self.registry:
api_root_dict[prefix] = list_name.format(basename=basename)
- view_renderers = list(api_settings.DEFAULT_RENDERER_CLASSES)
+ view_renderers = list(self.root_renderers)
schema_media_types = []
if api_urls and self.schema_title:
| Allow configuration of DefaultRouter's root view renderer classes
Currently, we can set the schema_renderer classes as kwargs on the DefaultRouter, but can't override the renderer classes used on the root view which comes from the settings.
https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/routers.py#L292
It would be desirable to replace BrowsableAPI renderer with the SwaggerUI html renderer in Django REST Swagger.
Referencing issue:
https://github.com/marcgibbons/django-rest-swagger/issues/479#issuecomment-232998716
| Thanks Marc. Getting back onto the project after DjangoCon - apologies for the delay.
| 2016-07-28T11:18:10 |
|
encode/django-rest-framework | 4,338 | encode__django-rest-framework-4338 | [
"4335"
] | e997713313c36808ac7052a218b253087622e179 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -804,7 +804,10 @@ def __init__(self, protocol='both', **kwargs):
self.validators.extend(validators)
def to_internal_value(self, data):
- if data and ':' in data:
+ if not isinstance(data, six.string_types):
+ self.fail('invalid', value=data)
+
+ if ':' in data:
try:
if self.protocol in ('both', 'ipv6'):
return clean_ipv6_address(data, self.unpack_ipv4)
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -663,6 +663,7 @@ class TestIPAddressField(FieldValues):
'127.122.111.2231': ['Enter a valid IPv4 or IPv6 address.'],
'2001:::9652': ['Enter a valid IPv4 or IPv6 address.'],
'2001:0db8:85a3:0042:1000:8a2e:0370:73341': ['Enter a valid IPv4 or IPv6 address.'],
+ 1000: ['Enter a valid IPv4 or IPv6 address.'],
}
outputs = {}
field = serializers.IPAddressField()
| Possible exception during validation of IPAddressField
I faced with not expected behaviour of IPAddress field during validation certain types of input.
## 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
1. Create a serializer with IPAddressField
2. Pass not iterable object as input for the serializer. E.g. integer.
## Expected behavior
Validation error with usual text:
`['Enter a valid IPv4 or IPv6 address.']`
## Actual behavior
Exception:
```
rest_framework/fields.py:701: in run_validation
return super(CharField, self).run_validation(data)
rest_framework/fields.py:487: in run_validation
value = self.to_internal_value(data)
rest_framework/fields.py:807: in to_internal_value
if data and ':' in data:
E TypeError: argument of type 'int' is not iterable
```
| Yup, looks valid, given your test case.
| 2016-08-01T15:13:56 |
encode/django-rest-framework | 4,339 | encode__django-rest-framework-4339 | [
"4318"
] | aa349fe76729dbea1b8becf1846ce58c70871f35 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -955,7 +955,7 @@ def to_internal_value(self, data):
if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')):
self.fail('invalid')
- return self.validate_precision(value)
+ return self.quantize(self.validate_precision(value))
def validate_precision(self, value):
"""
@@ -1018,7 +1018,8 @@ def quantize(self, value):
context.prec = self.max_digits
return value.quantize(
decimal.Decimal('.1') ** self.decimal_places,
- context=context)
+ context=context
+ )
# Date & time fields...
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -912,6 +912,26 @@ def test_localize_forces_coerce_to_string(self):
self.assertTrue(isinstance(field.to_representation(Decimal('1.1')), six.string_types))
+class TestQuantizedValueForDecimal(TestCase):
+ def test_int_quantized_value_for_decimal(self):
+ field = serializers.DecimalField(max_digits=4, decimal_places=2)
+ value = field.to_internal_value(12).as_tuple()
+ expected_digit_tuple = (0, (1, 2, 0, 0), -2)
+ self.assertEqual(value, expected_digit_tuple)
+
+ def test_string_quantized_value_for_decimal(self):
+ field = serializers.DecimalField(max_digits=4, decimal_places=2)
+ value = field.to_internal_value('12').as_tuple()
+ expected_digit_tuple = (0, (1, 2, 0, 0), -2)
+ self.assertEqual(value, expected_digit_tuple)
+
+ def test_part_precision_string_quantized_value_for_decimal(self):
+ field = serializers.DecimalField(max_digits=4, decimal_places=2)
+ value = field.to_internal_value('12.0').as_tuple()
+ expected_digit_tuple = (0, (1, 2, 0, 0), -2)
+ self.assertEqual(value, expected_digit_tuple)
+
+
class TestNoDecimalPlaces(FieldValues):
valid_inputs = {
'0.12345': Decimal('0.12345'),
| Invalid data type assigned into model while update
I'm not really sure if it's DRF of Django issue. It seems that input should (?) be modified for DecimalField before it ends up at `.validated_data`. Otherwise one can pass an `int` and retured object from `.save()` would be a incorrect.
Code:
``` python
class Product(models.Model):
title = models.CharField(max_length=100)
price = models.DecimalField(
max_digits=8,
decimal_places=2,
default=Decimal('0.00'),
validators=[MinValueValidator(Decimal(0))],)
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('title', 'price')
# create product instance
s = ProductSerializer(data={'title': 'Test', price: 100})
s.is_valid()
obj = s.save()
```
`obj.price` would be `(Decimal) 100` and not `(Decimal) 100.00`, however `serializer.data['price']` would be correctly formatted: `(Decimal) 100.00`; It's confusing and forces users to do `obj.refresh_from_db()` if one wants to use returned object and not `serializer.data` in their code.
| Ok, thanks for raising this
Milestoning to review further.
| 2016-08-01T16:15:24 |
encode/django-rest-framework | 4,340 | encode__django-rest-framework-4340 | [
"4296"
] | 46a44e52aa8a0eae82cc9c1e290a83ecf156f81a | diff --git a/rest_framework/parsers.py b/rest_framework/parsers.py
--- a/rest_framework/parsers.py
+++ b/rest_framework/parsers.py
@@ -118,6 +118,10 @@ class FileUploadParser(BaseParser):
Parser for file upload data.
"""
media_type = '*/*'
+ errors = {
+ 'unhandled': 'FileUpload parse error - none of upload handlers can handle the stream',
+ 'no_filename': 'Missing filename. Request should include a Content-Disposition header with a filename parameter.',
+ }
def parse(self, stream, media_type=None, parser_context=None):
"""
@@ -134,6 +138,9 @@ def parse(self, stream, media_type=None, parser_context=None):
upload_handlers = request.upload_handlers
filename = self.get_filename(stream, media_type, parser_context)
+ if not filename:
+ raise ParseError(self.errors['no_filename'])
+
# Note that this code is extracted from Django's handling of
# file uploads in MultiPartParser.
content_type = meta.get('HTTP_CONTENT_TYPE',
@@ -146,7 +153,7 @@ def parse(self, stream, media_type=None, parser_context=None):
# See if the handler will want to take care of the parsing.
for handler in upload_handlers:
- result = handler.handle_raw_input(None,
+ result = handler.handle_raw_input(stream,
meta,
content_length,
None,
@@ -178,10 +185,10 @@ def parse(self, stream, media_type=None, parser_context=None):
for index, handler in enumerate(upload_handlers):
file_obj = handler.file_complete(counters[index])
- if file_obj:
+ if file_obj is not None:
return DataAndFiles({}, {'file': file_obj})
- raise ParseError("FileUpload parse error - "
- "none of upload handlers can handle the stream")
+
+ raise ParseError(self.errors['unhandled'])
def get_filename(self, stream, media_type, parser_context):
"""
| diff --git a/tests/test_parsers.py b/tests/test_parsers.py
--- a/tests/test_parsers.py
+++ b/tests/test_parsers.py
@@ -2,8 +2,11 @@
from __future__ import unicode_literals
+import pytest
from django import forms
-from django.core.files.uploadhandler import MemoryFileUploadHandler
+from django.core.files.uploadhandler import (
+ MemoryFileUploadHandler, TemporaryFileUploadHandler
+)
from django.test import TestCase
from django.utils.six.moves import StringIO
@@ -63,8 +66,9 @@ def test_parse_missing_filename(self):
parser = FileUploadParser()
self.stream.seek(0)
self.parser_context['request'].META['HTTP_CONTENT_DISPOSITION'] = ''
- with self.assertRaises(ParseError):
+ with pytest.raises(ParseError) as excinfo:
parser.parse(self.stream, None, self.parser_context)
+ assert str(excinfo.value) == 'Missing filename. Request should include a Content-Disposition header with a filename parameter.'
def test_parse_missing_filename_multiple_upload_handlers(self):
"""
@@ -78,8 +82,23 @@ def test_parse_missing_filename_multiple_upload_handlers(self):
MemoryFileUploadHandler()
)
self.parser_context['request'].META['HTTP_CONTENT_DISPOSITION'] = ''
- with self.assertRaises(ParseError):
+ with pytest.raises(ParseError) as excinfo:
parser.parse(self.stream, None, self.parser_context)
+ assert str(excinfo.value) == 'Missing filename. Request should include a Content-Disposition header with a filename parameter.'
+
+ def test_parse_missing_filename_large_file(self):
+ """
+ Parse raw file upload when filename is missing with TemporaryFileUploadHandler.
+ """
+ parser = FileUploadParser()
+ self.stream.seek(0)
+ self.parser_context['request'].upload_handlers = (
+ TemporaryFileUploadHandler(),
+ )
+ self.parser_context['request'].META['HTTP_CONTENT_DISPOSITION'] = ''
+ with pytest.raises(ParseError) as excinfo:
+ parser.parse(self.stream, None, self.parser_context)
+ assert str(excinfo.value) == 'Missing filename. Request should include a Content-Disposition header with a filename parameter.'
def test_get_filename(self):
parser = FileUploadParser()
| Test large files
I filled #3374 time ago and it was closed. Probably it wasn't very well explained, but it showed a non consistent behaviour.
Today I wrote this test that shows that large files and small files don't have the same behaviour. I couldn't fix it. My knowledge of DRF is limitated. This test, probably, will help to fix the error.
I think that fixing this test would fix #3374 and probably it would help with #3610.
| 2016-08-01T17:14:03 |
|
encode/django-rest-framework | 4,346 | encode__django-rest-framework-4346 | [
"3565"
] | 296e47a9f8f5303d7862b68db7277aa87886e8a9 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -435,7 +435,8 @@ def get_default(self):
return `empty`, indicating that no value should be set in the
validated data for this field.
"""
- if self.default is empty:
+ if self.default is empty or getattr(self.root, 'partial', False):
+ # No default, or this is a partial update.
raise SkipField()
if callable(self.default):
if hasattr(self.default, 'set_context'):
| diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -309,3 +309,31 @@ class ExampleSerializer(serializers.Serializer):
pickled = pickle.dumps(serializer.data)
data = pickle.loads(pickled)
assert data == {'field1': 'a', 'field2': 'b'}
+
+
+class TestDefaultInclusions:
+ def setup(self):
+ class ExampleSerializer(serializers.Serializer):
+ char = serializers.CharField(read_only=True, default='abc')
+ integer = serializers.IntegerField()
+ self.Serializer = ExampleSerializer
+
+ def test_default_should_included_on_create(self):
+ serializer = self.Serializer(data={'integer': 456})
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'char': 'abc', 'integer': 456}
+ assert serializer.errors == {}
+
+ def test_default_should_be_included_on_update(self):
+ instance = MockObject(char='def', integer=123)
+ serializer = self.Serializer(instance, data={'integer': 456})
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'char': 'abc', 'integer': 456}
+ assert serializer.errors == {}
+
+ def test_default_should_not_be_included_on_partial_update(self):
+ instance = MockObject(char='def', integer=123)
+ serializer = self.Serializer(instance, data={'integer': 456}, partial=True)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'integer': 456}
+ assert serializer.errors == {}
| Partial updates always change fields that are not in data, read only, and have a default
This is kind of an edge case, maybe? Maybe not. I ran into it because I have a field which is readonly on update but has a default for the create case.
See [Serializer._writable_fields](https://github.com/tomchristie/django-rest-framework/blob/322bda8/rest_framework/serializers.py#L344). I'm trying to do a partial update on one field, but I have another field that's readonly on update. BUT instead of being left alone, since it has a default, it always gets set TO THAT DEFAULT.
From my reading of writable_fields, it looks like this would happen with _any_ field that has a default and isn't included in a partial update, but for it to happen on a read_only field seems particularly egregious to me. :-p
| (My expectation would be that a partial update would only affect the fields that have data being sent their way.)
Is this still occurring against the latest release?
I tried upgrading to the latest stable release (3.3.1) and still had the issue, and I didn't see any changes between that and master in the relevant parts of the code.
This is still present. The documentation ([3.0 announcement](http://www.django-rest-framework.org/topics/3.0-announcement/#the-required-allow_null-allow_blank-and-default-arguments), which is the only place I could find a reference to this) is also wrong: it doesn't mention that it'll only be used for read_only fields.
Milestoning to confirm against latest version.
| 2016-08-02T11:49:25 |
encode/django-rest-framework | 4,347 | encode__django-rest-framework-4347 | [
"4345"
] | e37619f7410bcfc472db56635aa573b33f83e92a | diff --git a/rest_framework/utils/formatting.py b/rest_framework/utils/formatting.py
--- a/rest_framework/utils/formatting.py
+++ b/rest_framework/utils/formatting.py
@@ -32,13 +32,22 @@ def dedent(content):
unindented text on the initial line.
"""
content = force_text(content)
- whitespace_counts = [len(line) - len(line.lstrip(' '))
- for line in content.splitlines()[1:] if line.lstrip()]
+ whitespace_counts = [
+ len(line) - len(line.lstrip(' '))
+ for line in content.splitlines()[1:] if line.lstrip()
+ ]
+ tab_counts = [
+ len(line) - len(line.lstrip('\t'))
+ for line in content.splitlines()[1:] if line.lstrip()
+ ]
# unindent the content if needed
if whitespace_counts:
whitespace_pattern = '^' + (' ' * min(whitespace_counts))
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content)
+ elif tab_counts:
+ whitespace_pattern = '^' + ('\t' * min(whitespace_counts))
+ content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content)
return content.strip()
| diff --git a/tests/test_description.py b/tests/test_description.py
--- a/tests/test_description.py
+++ b/tests/test_description.py
@@ -6,6 +6,7 @@
from django.utils.encoding import python_2_unicode_compatible
from rest_framework.compat import apply_markdown
+from rest_framework.utils.formatting import dedent
from rest_framework.views import APIView
@@ -120,3 +121,7 @@ def test_markdown(self):
gte_21_match = apply_markdown(DESCRIPTION) == MARKED_DOWN_gte_21
lt_21_match = apply_markdown(DESCRIPTION) == MARKED_DOWN_lt_21
self.assertTrue(gte_21_match or lt_21_match)
+
+
+def test_dedent_tabs():
+ assert dedent("\tfirst string\n\n\tsecond string") == 'first string\n\n\tsecond string'
| Browsable API markdown description broken if tabs are used in code indentation.
get_view_description(html=True) with markdown installed is broken if the project uses tabs instead of spaces. Everything after the first line is rendered as a `<pre>` block.
The problem is in the [utils.formatting.dedent()](https://github.com/tomchristie/django-rest-framework/blob/4e5da16/rest_framework/utils/formatting.py#L25) function which only dedents spaces, not tabs.
## 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
``` python
from rest_framework.utils.formatting import dedent
dedent("\tfirst string\n\n\tsecond string")
```
## Expected behavior
It returns:
```
u'first string\n\n\tsecond string'
```
## Actual behavior
It should return:
```
u'first string\n\nsecond string'
```
| 2016-08-02T12:05:44 |
|
encode/django-rest-framework | 4,349 | encode__django-rest-framework-4349 | [
"4198"
] | 5500b265bceb1d964725d3fd13f60429b834dbf4 | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -1324,9 +1324,8 @@ def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs
# Update `extra_kwargs` with any new options.
for key, value in uniqueness_extra_kwargs.items():
if key in extra_kwargs:
- extra_kwargs[key].update(value)
- else:
- extra_kwargs[key] = value
+ value.update(extra_kwargs[key])
+ extra_kwargs[key] = value
return extra_kwargs, hidden_fields
| 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
@@ -976,3 +976,22 @@ class Meta:
source = OneToOneSourceTestModel(target=target)
serializer = ExampleSerializer(source)
self.assertEqual(serializer.data, {'target': 1})
+
+
+class TestUniquenessOverride(TestCase):
+ def test_required_not_overwritten(self):
+ class TestModel(models.Model):
+ field_1 = models.IntegerField(null=True)
+ field_2 = models.IntegerField()
+
+ class Meta:
+ unique_together = (('field_1', 'field_2'),)
+
+ class TestSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = TestModel
+ extra_kwargs = {'field_1': {'required': False}}
+
+ fields = TestSerializer().fields
+ self.assertFalse(fields['field_1'].required)
+ self.assertTrue(fields['field_2'].required)
| Always defer to explicit overrides.
Some of these may already be covered, but we should make sure that all the following are satisfied:
- If a user declares a field explicitly, but also includes it in `extra_kwargs` then warn/error.
- If a user declares a field explicitly, but also includes it in `read_only_fields` then warn/error.
- Don't allow `get_uniqueness_extra_kwargs` to override a declared field.
- Don't allow `get_uniqueness_extra_kwargs` to override a flag that has been set in `extra_kwargs`.
- If a serializer field has a `default`, then ensure that uniqueness validators use that for empty, rather than forcing `required=True`
| > - Don't allow get_uniqueness_extra_kwargs to override a declared field.
This already happens, a declared field will not be re-declared with new args.
> - If a serializer field has a default, then ensure that uniqueness validators use that for empty, rather than forcing required=True
A default of None on a declared field will work for uniqueness validation.
Thanks for those confirmations @gcbirzan!
| 2016-08-02T13:29:32 |
encode/django-rest-framework | 4,359 | encode__django-rest-framework-4359 | [
"4330"
] | 11a2468379496a4e9ed29d84d135825a927a5595 | diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -195,6 +195,8 @@ def get_link(self, path, method, callback):
Return a `coreapi.Link` instance for the given endpoint.
"""
view = callback.cls()
+ for attr, val in getattr(callback, 'initkwargs', {}).items():
+ setattr(view, attr, val)
fields = self.get_path_fields(path, method, callback, view)
fields += self.get_serializer_fields(path, method, callback, view)
diff --git a/rest_framework/viewsets.py b/rest_framework/viewsets.py
--- a/rest_framework/viewsets.py
+++ b/rest_framework/viewsets.py
@@ -97,6 +97,7 @@ def view(request, *args, **kwargs):
# generation can pick out these bits of information from a
# resolved URL.
view.cls = cls
+ view.initkwargs = initkwargs
view.suffix = initkwargs.get('suffix', None)
view.actions = actions
return csrf_exempt(view)
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -5,6 +5,7 @@
from rest_framework import filters, pagination, permissions, serializers
from rest_framework.compat import coreapi
+from rest_framework.decorators import detail_route
from rest_framework.response import Response
from rest_framework.routers import DefaultRouter
from rest_framework.schemas import SchemaGenerator
@@ -27,12 +28,21 @@ class ExampleSerializer(serializers.Serializer):
b = serializers.CharField(required=False)
+class AnotherSerializer(serializers.Serializer):
+ c = serializers.CharField(required=True)
+ d = serializers.CharField(required=False)
+
+
class ExampleViewSet(ModelViewSet):
pagination_class = ExamplePagination
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
filter_backends = [filters.OrderingFilter]
serializer_class = ExampleSerializer
+ @detail_route(methods=['post'], serializer_class=AnotherSerializer)
+ def custom_action(self, request, pk):
+ return super(ExampleSerializer, self).retrieve(self, request)
+
class ExampleView(APIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
@@ -120,6 +130,16 @@ def test_authenticated_request(self):
coreapi.Field('pk', required=True, location='path')
]
),
+ 'custom_action': coreapi.Link(
+ url='/example/{pk}/custom_action/',
+ action='post',
+ encoding='application/json',
+ fields=[
+ coreapi.Field('pk', required=True, location='path'),
+ coreapi.Field('c', required=True, location='form'),
+ coreapi.Field('d', required=False, location='form'),
+ ]
+ ),
'update': coreapi.Link(
url='/example/{pk}/',
action='put',
| Schema generator ignores detail_route and list_route overrides of serializer_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](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
``` python
class ExampleSerializer(serializers.Serializer):
a = serializers.CharField(required=True)
b = serializers.CharField(required=False)
class AnotherSerializer(serializers.Serializer):
c = serializers.CharField(required=True)
d = serializers.CharField(required=False)
class ExampleViewSet(ModelViewSet):
serializer_class = ExampleSerializer
@detail_route(methods=['post'], serializer_class=AnotherSerializer)
def custom_action(self, request, pk):
return super(ExampleSerializer, self).retrieve(self, request)
```
## Expected behavior
Fields `c` and `d` from `AnotherSerializer` in generated schema.
## Actual behavior
Fields `a` and `b` from `ExampleSerializer` - serializer of viewset itself.
| 2016-08-05T10:06:49 |
|
encode/django-rest-framework | 4,374 | encode__django-rest-framework-4374 | [
"4137"
] | 0781182646e4b292e88ec46b74cc5b709c190753 | 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
@@ -89,6 +89,21 @@ def add_query_param(request, key, val):
return escape(replace_query_param(uri, key, val))
[email protected]
+def as_string(value):
+ if value is None:
+ return ''
+ return '%s' % value
+
+
[email protected]
+def as_list_of_strings(value):
+ return [
+ '' if (item is None) else ('%s' % item)
+ for item in value
+ ]
+
+
@register.filter
def add_class(value, css_class):
"""
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
@@ -78,7 +78,7 @@ def __repr__(self):
))
def as_form_field(self):
- value = '' if (self.value is None or self.value is False) else force_text(self.value)
+ value = '' if (self.value is None or self.value is False) else self.value
return self.__class__(self._field, value, self.errors, self._prefix)
| diff --git a/tests/test_renderers.py b/tests/test_renderers.py
--- a/tests/test_renderers.py
+++ b/tests/test_renderers.py
@@ -481,3 +481,90 @@ def test_render_with_provided_args(self):
result = renderer.render(self.serializer.data, None, {})
self.assertIsInstance(result, SafeText)
+
+
+class TestChoiceFieldHTMLFormRenderer(TestCase):
+ """
+ Test rendering ChoiceField with HTMLFormRenderer.
+ """
+
+ def setUp(self):
+ choices = ((1, 'Option1'), (2, 'Option2'), (12, 'Option12'))
+
+ class TestSerializer(serializers.Serializer):
+ test_field = serializers.ChoiceField(choices=choices,
+ initial=2)
+
+ self.TestSerializer = TestSerializer
+ self.renderer = HTMLFormRenderer()
+
+ def test_render_initial_option(self):
+ serializer = self.TestSerializer()
+ result = self.renderer.render(serializer.data)
+
+ self.assertIsInstance(result, SafeText)
+
+ self.assertInHTML('<option value="2" selected>Option2</option>',
+ result)
+ self.assertInHTML('<option value="1">Option1</option>', result)
+ self.assertInHTML('<option value="12">Option12</option>', result)
+
+ def test_render_selected_option(self):
+ serializer = self.TestSerializer(data={'test_field': '12'})
+
+ serializer.is_valid()
+ result = self.renderer.render(serializer.data)
+
+ self.assertIsInstance(result, SafeText)
+
+ self.assertInHTML('<option value="12" selected>Option12</option>',
+ result)
+ self.assertInHTML('<option value="1">Option1</option>', result)
+ self.assertInHTML('<option value="2">Option2</option>', result)
+
+
+class TestMultipleChoiceFieldHTMLFormRenderer(TestCase):
+ """
+ Test rendering MultipleChoiceField with HTMLFormRenderer.
+ """
+
+ def setUp(self):
+ self.renderer = HTMLFormRenderer()
+
+ def test_render_selected_option_with_string_option_ids(self):
+ choices = (('1', 'Option1'), ('2', 'Option2'), ('12', 'Option12'),
+ ('}', 'OptionBrace'))
+
+ class TestSerializer(serializers.Serializer):
+ test_field = serializers.MultipleChoiceField(choices=choices)
+
+ serializer = TestSerializer(data={'test_field': ['12']})
+ serializer.is_valid()
+
+ result = self.renderer.render(serializer.data)
+
+ self.assertIsInstance(result, SafeText)
+
+ self.assertInHTML('<option value="12" selected>Option12</option>',
+ result)
+ self.assertInHTML('<option value="1">Option1</option>', result)
+ self.assertInHTML('<option value="2">Option2</option>', result)
+ self.assertInHTML('<option value="}">OptionBrace</option>', result)
+
+ def test_render_selected_option_with_integer_option_ids(self):
+ choices = ((1, 'Option1'), (2, 'Option2'), (12, 'Option12'))
+
+ class TestSerializer(serializers.Serializer):
+ test_field = serializers.MultipleChoiceField(choices=choices)
+
+ serializer = TestSerializer(data={'test_field': ['12']})
+ serializer.is_valid()
+
+ result = self.renderer.render(serializer.data)
+
+ self.assertIsInstance(result, SafeText)
+
+ self.assertInHTML('<option value="12" selected>Option12</option>',
+ result)
+ self.assertInHTML('<option value="1">Option1</option>', result)
+ self.assertInHTML('<option value="2">Option2</option>', result)
| Improve HTML form rendering of choice fields
Another take on fixing choice field HTML rendering issues (#4120 and #4121) - this is a smaller impact patch, as suggested in #4122.
| 2016-08-10T10:33:29 |
|
encode/django-rest-framework | 4,375 | encode__django-rest-framework-4375 | [
"3877"
] | 8105a4ac5abc9760ac5dea8e567f333feb6f8e2a | diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -156,14 +156,16 @@ def get_attribute(self, instance):
# Standard case, return the object instance.
return get_attribute(instance, self.source_attrs)
- @property
- def choices(self):
+ def get_choices(self, cutoff=None):
queryset = self.get_queryset()
if queryset is None:
# Ensure that field.choices returns something sensible
# even when accessed with a read-only field.
return {}
+ if cutoff is not None:
+ queryset = queryset[:cutoff]
+
return OrderedDict([
(
six.text_type(self.to_representation(item)),
@@ -172,13 +174,17 @@ def choices(self):
for item in queryset
])
+ @property
+ def choices(self):
+ return self.get_choices()
+
@property
def grouped_choices(self):
return self.choices
def iter_options(self):
return iter_options(
- self.grouped_choices,
+ self.get_choices(cutoff=self.html_cutoff),
cutoff=self.html_cutoff,
cutoff_text=self.html_cutoff_text
)
@@ -487,9 +493,12 @@ def to_representation(self, iterable):
for value in iterable
]
+ def get_choices(self, cutoff=None):
+ return self.child_relation.get_choices(cutoff)
+
@property
def choices(self):
- return self.child_relation.choices
+ return self.get_choices()
@property
def grouped_choices(self):
@@ -497,7 +506,7 @@ def grouped_choices(self):
def iter_options(self):
return iter_options(
- self.grouped_choices,
+ self.get_choices(cutoff=self.html_cutoff),
cutoff=self.html_cutoff,
cutoff_text=self.html_cutoff_text
)
| Improve relation choices limiting (using html_cutoff)
When we're showing the HTML form field for related objects and we're trying to generate the choices for the select field, it doesn't seem to make sense to grab every single record in a table, only to display `html_cutoff` (default: 1000) of them and completely ignore the rest.
Instead, we should limit the number of objects we want from the database to the number of objects we're planning on displaying. This changeset makes the semantics of retrieving related objects the same as for displaying related objects. In other words, we limit the queryset to the first `html_cutoff` objects. That way we aren't pulling back more objects than necessary, because this can kill performance for tables with "lots" of records (~500k in my case, [~400k for others](https://github.com/tomchristie/django-rest-framework/issues/3329#issue-103045398)).
Closes #3329.
| 2016-08-10T11:11:47 |
||
encode/django-rest-framework | 4,377 | encode__django-rest-framework-4377 | [
"4372"
] | 2d43b17f9a854f53688752c764e86f21fe982cf2 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1016,7 +1016,8 @@ def quantize(self, value):
return value
context = decimal.getcontext().copy()
- context.prec = self.max_digits
+ if self.max_digits is not None:
+ context.prec = self.max_digits
return value.quantize(
decimal.Decimal('.1') ** self.decimal_places,
context=context
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -876,6 +876,18 @@ class TestMinMaxDecimalField(FieldValues):
)
+class TestNoMaxDigitsDecimalField(FieldValues):
+ field = serializers.DecimalField(
+ max_value=100, min_value=0,
+ decimal_places=2, max_digits=None
+ )
+ valid_inputs = {
+ '10': Decimal('10.00')
+ }
+ invalid_inputs = {}
+ outputs = {}
+
+
class TestNoStringCoercionDecimalField(FieldValues):
"""
Output values for `DecimalField` with `coerce_to_string=False`.
| DecimalField fails when `max_digits=None`
## Steps to reproduce
1) Create a DecimalField inside a serializer with max_value, min_value, and decimal_places set, but set max_digits = None. EG: serializers.DecimalField(max_value=100, min_value=0, decimal_places=10, max_digits=None)
2) call serializer.is_valid()
3) observe traceback similar to the following :
Traceback (most recent call last):
File "~/api/views.py", line 263, in monitor
serializer.is_valid()
File "~/env/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 213, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "~/env/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 407, in run_validation
value = self.to_internal_value(data)
File "~/env/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 437, in to_internal_value
validated_value = field.run_validation(primitive_value)
File "~/env/local/lib/python2.7/site-packages/rest_framework/fields.py", line 488, in run_validation
value = self.to_internal_value(data)
File "~/env/local/lib/python2.7/site-packages/rest_framework/fields.py", line 959, in to_internal_value
return self.quantize(self.validate_precision(value))
File "~/env/local/lib/python2.7/site-packages/rest_framework/fields.py", line 1022, in quantize
context=context
File "/usr/lib/python2.7/decimal.py", line 2455, in quantize
if not (context.Etiny() <= exp._exp <= context.Emax):
File "/usr/lib/python2.7/decimal.py", line 3898, in Etiny
return int(self.Emin - self.prec + 1)
TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'
## Expected behavior
is_valid returns true if the value is between min and max, without concerning itself with the number of digits / precision of the number, OR do not accept None as a valid value for max_digits.
## Actual behavior
an exception is raised, which is difficult to track down and counter intuitive.
| > is_valid returns true if the value is between min and max, without concerning itself with the number of digits / precision of the number, OR do not accept None as a valid value for max_digits.
Nop. `max_digits` is a required argument. It shouldn't be `None` or ignored. I'd assume you'll get a faster traceback if you simply ignore it.
What I'd be willing to do here would be:
- to add an explicit mention in the doc about the required fields.
- to add an assert about `max_digits` not being None.
Closing this issue meanwhile as we're not making `max_digit` optional.
That makes sense, yeah assert when max_digits is None would be great.
Definitely easier for people to debug.
On Aug 9, 2016 11:53 PM, "Xavier Ordoquy" [email protected] wrote:
> Closed #4372
> https://github.com/tomchristie/django-rest-framework/issues/4372.
>
> —
> You are receiving this because you authored the thread.
> Reply to this email directly, view it on GitHub
> https://github.com/tomchristie/django-rest-framework/issues/4372#event-750879863,
> or mute the thread
> https://github.com/notifications/unsubscribe-auth/AE4PcV0S1msjrxb6c-2dJxbv8Gx6aFplks5qeXVtgaJpZM4Jgk4N
> .
Taking a look through the code it's not clear if `max_digits` is intended to be optional or not. We _do_ switch on `if self.max_digits is None`, and a `DecimalField` _without_ digit restrictions is a reasonable enough use case. Worth putting on to the queue to have a second think over.
@tomchristie `max_digits` is not a keyword argument in `__init__` therefore it's supposed to be required. Same applies to `decimal_field`. This is likely inherited from Django's own `DecimalField`.
If it becomes an optional argument, we'll need to cover the case where it's over the Django's Model boundaries.
| 2016-08-10T13:27:25 |
encode/django-rest-framework | 4,379 | encode__django-rest-framework-4379 | [
"3365"
] | fa4ce50be7dc0d429d6455e02a5da67a7d0fcb92 | diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -168,7 +168,7 @@ def get_choices(self, cutoff=None):
return OrderedDict([
(
- six.text_type(self.to_representation(item)),
+ self.to_representation(item),
self.display_value(item)
)
for item in 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
@@ -614,7 +614,7 @@ class Meta:
fields = '__all__'
serializer = TestSerializer()
- expected = OrderedDict([('1', 'Red Color'), ('2', 'Yellow Color'), ('3', 'Green Color')])
+ expected = OrderedDict([(1, 'Red Color'), (2, 'Yellow Color'), (3, 'Green Color')])
self.assertEqual(serializer.fields['color'].choices, expected)
def test_custom_display_value(self):
@@ -630,7 +630,7 @@ class Meta:
fields = '__all__'
serializer = TestSerializer()
- expected = OrderedDict([('1', 'My Red Color'), ('2', 'My Yellow Color'), ('3', 'My Green Color')])
+ expected = OrderedDict([(1, 'My Red Color'), (2, 'My Yellow Color'), (3, 'My Green Color')])
self.assertEqual(serializer.fields['color'].choices, expected)
| @choices representation of RelatedField
can we change
https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/relations.py#L154
from
```
return OrderedDict([
(
six.text_type(self.to_representation(item)),
self.display_value(item)
)
for item in queryset
```
to
```
return OrderedDict([
(
force_text(self.to_representation(item), strings_only=True),
self.display_value(item)
)
for item in queryset
```
????
When i make OPTION request, i've got metada for related field choices of action:
1st case:
{display_name: "Acura", value: "184"} (this is wrong)
2nd case:
{display_name: "Acura", value: 184} (it's ok)
Here we got field.choices:
https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/metadata.py#L142
```
field_info['choices'] = [
{
'value': choice_value,
'display_name': force_text(choice_name, strings_only=True)
}
for choice_value, choice_name in field.choices.items()
```
value is always string now.
| Yup, that seems like a valid request to me.
We no longer display relational choices in `OPTIONS` by default, but the underlying change here is still reasonable & correct.
| 2016-08-10T15:03:23 |
encode/django-rest-framework | 4,380 | encode__django-rest-framework-4380 | [
"3394"
] | f1a2eeb818366b11c44c86d2ccfa1d6822d216b9 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -672,6 +672,7 @@ def to_representation(self, value):
class CharField(Field):
default_error_messages = {
+ 'invalid': _('Not a valid string.'),
'blank': _('This field may not be blank.'),
'max_length': _('Ensure this field has no more than {max_length} characters.'),
'min_length': _('Ensure this field has at least {min_length} characters.')
@@ -702,6 +703,11 @@ def run_validation(self, data=empty):
return super(CharField, self).run_validation(data)
def to_internal_value(self, data):
+ # We're lenient with allowing basic numerics to be coerced into strings,
+ # but other types should fail. Eg. unclear if booleans should represent as `true` or `True`,
+ # and composites such as lists are likely user error.
+ if isinstance(data, bool) or not isinstance(data, six.string_types + six.integer_types + (float,)):
+ self.fail('invalid')
value = six.text_type(data)
return value.strip() if self.trim_whitespace else value
diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -168,7 +168,7 @@ def get_choices(self, cutoff=None):
return OrderedDict([
(
- six.text_type(self.to_representation(item)),
+ self.to_representation(item),
self.display_value(item)
)
for item in queryset
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -535,6 +535,8 @@ class TestCharField(FieldValues):
'abc': 'abc'
}
invalid_inputs = {
+ (): ['Not a valid string.'],
+ True: ['Not a valid string.'],
'': ['This field may not be blank.']
}
outputs = {
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
@@ -614,7 +614,7 @@ class Meta:
fields = '__all__'
serializer = TestSerializer()
- expected = OrderedDict([('1', 'Red Color'), ('2', 'Yellow Color'), ('3', 'Green Color')])
+ expected = OrderedDict([(1, 'Red Color'), (2, 'Yellow Color'), (3, 'Green Color')])
self.assertEqual(serializer.fields['color'].choices, expected)
def test_custom_display_value(self):
@@ -630,7 +630,7 @@ class Meta:
fields = '__all__'
serializer = TestSerializer()
- expected = OrderedDict([('1', 'My Red Color'), ('2', 'My Yellow Color'), ('3', 'My Green Color')])
+ expected = OrderedDict([(1, 'My Red Color'), (2, 'My Yellow Color'), (3, 'My Green Color')])
self.assertEqual(serializer.fields['color'].choices, expected)
| CharField should not accept collections as valid input
This issue came up on the marshmallow issue tracker (https://github.com/marshmallow-code/marshmallow/issues/231), so I thought I'd pass it along here.
It seems incorrect for `CharField` to take numbers and collections as valid input.
### Code to reproduce
``` python
from django.conf import settings
settings.configure(INSTALLED_APPS=['rest_framework'])
import django
django.setup()
from rest_framework import serializers as ser
from rest_framework.exceptions import ValidationError
field = ser.CharField()
inputs = (
42,
42.0,
{},
[]
)
for val in inputs:
try:
field.run_validation(val)
except ValidationError as err:
print(err.detail[0])
```
### Expected
Validation fails with messages like `"{} is not a valid string."`.
### Actual
Numbers and collections pass validation.
| I'm not quite sure why the py3x-django18 builds are failing; I can look into it further if you decide this change is a good idea.
I don't think I mind us coercing numbers to string representations. Collection types should prob fail tho.
I second @tomchristie
What is the rationale for allowing numbers? Any time a client passes a number to a string field, it is most likely due to user or client error and should be treated as such. The client should be responsible for "stringifying" any numerical input.
^ Same goes for booleans passed to a string field.
I agree with triggering an error when a collection is passed in as a string.
> What is the rationale for allowing numbers?
I'm -0 on not allowing numbers _mostly_ because that's expected functionality at the moment and changing this would break backwards compatibility. We even had a test to ensure that numbers were coerced properly.
It's also useful to note that there may be renders out there which try their best to coerce string input to the right type, so numbers would become a numeric type (decimal, probably) instead of staying as strings. We allow for the reverse case (numbers passed in as strings to number-type fields), so I don't understand why we would want to disallow this.
> We allow for the reverse case (numbers passed in as strings to number-type fields), so I don't understand why we would want to disallow this.
Indeed, most of simple fields accept strings as input. The fields' deserialization logic, however, is responsible for deciding which string inputs are valid (e.g. `Boolean` accepts `"true"` but not `"glue"`). That logic is also responsible for deciding which Python types are valid (e.g. `Dict` only accepts `dict`; `Boolean` doesn't accept `dict`).
I lean slightly toward disallowing numbers as inputs to `String`. That said, I don't feel that strongly about it, and it's probably not worth breaking backwards compat for this change. Let me know how to proceed.
At least they should be treated as individually. The case for one pull request is unambiguous, the case for the other less so.
I'd like to see this be configurable at least. I would imagine passing anything other than a string to a CharField is usually indicative of user error.
> I would imagine passing anything other than a string to a CharField is usually indicative of user error.
Possibly, tho "Generous on input, strict on output" could also be a valid rule of thumb for us to use here.
Adding an option to coerce input to string sounds valid to me. I don't think we should coerce collections though.
| 2016-08-10T16:08:58 |
encode/django-rest-framework | 4,383 | encode__django-rest-framework-4383 | [
"4382"
] | 3698d9ea2ef95a6823b1bc98863ba7b49e2b6937 | diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -65,44 +65,52 @@ def __init__(self, title=None, url=None, patterns=None, urlconf=None):
urls = import_module(urlconf)
else:
urls = urlconf
- patterns = urls.urlpatterns
+ self.patterns = urls.urlpatterns
elif patterns is None and urlconf is None:
urls = import_module(settings.ROOT_URLCONF)
- patterns = urls.urlpatterns
+ self.patterns = urls.urlpatterns
+ else:
+ self.patterns = patterns
if url and not url.endswith('/'):
url += '/'
self.title = title
self.url = url
- self.endpoints = self.get_api_endpoints(patterns)
+ self.endpoints = None
def get_schema(self, request=None):
- if request is None:
- endpoints = self.endpoints
- else:
- # Filter the list of endpoints to only include those that
- # the user has permission on.
- endpoints = []
- for key, link, callback in self.endpoints:
- method = link.action.upper()
- view = callback.cls()
+ if self.endpoints is None:
+ self.endpoints = self.get_api_endpoints(self.patterns)
+
+ links = []
+ for key, path, method, callback in self.endpoints:
+ view = callback.cls()
+ for attr, val in getattr(callback, 'initkwargs', {}).items():
+ setattr(view, attr, val)
+ view.args = ()
+ view.kwargs = {}
+ view.format_kwarg = None
+
+ if request is not None:
view.request = clone_request(request, method)
- view.format_kwarg = None
try:
view.check_permissions(view.request)
except exceptions.APIException:
- pass
- else:
- endpoints.append((key, link, callback))
+ continue
+ else:
+ view.request = None
+
+ link = self.get_link(path, method, callback, view)
+ links.append((key, link))
- if not endpoints:
+ if not link:
return None
# Generate the schema content structure, from the endpoints.
# ('users', 'list'), Link -> {'users': {'list': Link()}}
content = {}
- for key, link, callback in endpoints:
+ for key, link in links:
insert_into(content, key, link)
# Return the schema document.
@@ -122,8 +130,7 @@ def get_api_endpoints(self, patterns, prefix=''):
if self.should_include_endpoint(path, callback):
for method in self.get_allowed_methods(callback):
key = self.get_key(path, method, callback)
- link = self.get_link(path, method, callback)
- endpoint = (key, link, callback)
+ endpoint = (key, path, method, callback)
api_endpoints.append(endpoint)
elif isinstance(pattern, RegexURLResolver):
@@ -190,14 +197,10 @@ def get_key(self, path, method, callback):
# Methods for generating each individual `Link` instance...
- def get_link(self, path, method, callback):
+ def get_link(self, path, method, callback, view):
"""
Return a `coreapi.Link` instance for the given endpoint.
"""
- view = callback.cls()
- for attr, val in getattr(callback, 'initkwargs', {}).items():
- setattr(view, attr, val)
-
fields = self.get_path_fields(path, method, callback, view)
fields += self.get_serializer_fields(path, method, callback, view)
fields += self.get_pagination_fields(path, method, callback, view)
@@ -260,20 +263,18 @@ def get_serializer_fields(self, path, method, callback, view):
if method not in ('PUT', 'PATCH', 'POST'):
return []
- if not hasattr(view, 'get_serializer_class'):
+ if not hasattr(view, 'get_serializer'):
return []
- fields = []
-
- serializer_class = view.get_serializer_class()
- serializer = serializer_class()
+ serializer = view.get_serializer()
if isinstance(serializer, serializers.ListSerializer):
- return coreapi.Field(name='data', location='body', required=True)
+ return [coreapi.Field(name='data', location='body', required=True)]
if not isinstance(serializer, serializers.Serializer):
return []
+ fields = []
for field in serializer.fields.values():
if field.read_only:
continue
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -43,6 +43,10 @@ class ExampleViewSet(ModelViewSet):
def custom_action(self, request, pk):
return super(ExampleSerializer, self).retrieve(self, request)
+ def get_serializer(self, *args, **kwargs):
+ assert self.request
+ return super(ExampleViewSet, self).get_serializer(*args, **kwargs)
+
class ExampleView(APIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
| SchemaGenerator does not pass in serializer context
## Steps to reproduce
Create a simple serializer which references the incoming serializer context. As an example, we're going to reference the incoming request, which should be passed in as `request`, so we can get the user who is making the request to the serializer.
``` python
class MySimpleSerializer(Serializer):
# I have no fields because I'm a useless serializer
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print(self.context['request'].user)
```
And attach it to a view which is pulled in for schema generation. It can be any view, as long as the schema generation is able to introspect it and generate a schema from it.
## Expected behavior
The schema is able to be generated from the view. It should reference no fields (none are being defined) but it should still be able to generate an empty schema.
## Actual behavior
During schema generation, an error is triggered because `request` is not defined in `self.context`. The serializer context is empty.
## Possible solution
One possible solution to this issue is to generate the serializer context, which can be done using `view.get_serializer_context` and pass it into the serializer that is being used for introspection. You can combine the steps for getting the serializer class, getting the context, and creating the serializer by using `view.get_serializer` to create it.
### The problem with that...
Right now that solution would run into another issue, which is that `view.request` is not defined. This is required by `view.get_serializer_context`, and the issue related to it is being tracked at https://github.com/tomchristie/django-rest-framework/issues/4278.
| 2016-08-11T10:07:58 |
|
encode/django-rest-framework | 4,386 | encode__django-rest-framework-4386 | [
"4376"
] | b50d8950eeeac03843b9da1cb96ba52b5b98c8bc | diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -30,24 +30,6 @@ def is_api_view(callback):
return (cls is not None) and issubclass(cls, APIView)
-def insert_into(target, keys, item):
- """
- Insert `item` into the nested dictionary `target`.
-
- For example:
-
- target = {}
- insert_into(target, ('users', 'list'), Link(...))
- insert_into(target, ('users', 'detail'), Link(...))
- assert target == {'users': {'list': Link(...), 'detail': Link(...)}}
- """
- for key in keys[:1]:
- if key not in target:
- target[key] = {}
- target = target[key]
- target[keys[-1]] = item
-
-
class SchemaGenerator(object):
default_mapping = {
'get': 'read',
@@ -84,7 +66,7 @@ def get_schema(self, request=None):
self.endpoints = self.get_api_endpoints(self.patterns)
links = []
- for key, path, method, callback in self.endpoints:
+ for path, method, category, action, callback in self.endpoints:
view = callback.cls()
for attr, val in getattr(callback, 'initkwargs', {}).items():
setattr(view, attr, val)
@@ -102,16 +84,21 @@ def get_schema(self, request=None):
view.request = None
link = self.get_link(path, method, callback, view)
- links.append((key, link))
+ links.append((category, action, link))
- if not link:
+ if not links:
return None
- # Generate the schema content structure, from the endpoints.
- # ('users', 'list'), Link -> {'users': {'list': Link()}}
+ # Generate the schema content structure, eg:
+ # {'users': {'list': Link()}}
content = {}
- for key, link in links:
- insert_into(content, key, link)
+ for category, action, link in links:
+ if category is None:
+ content[action] = link
+ elif category in content:
+ content[category][action] = link
+ else:
+ content[category] = {action: link}
# Return the schema document.
return coreapi.Document(title=self.title, content=content, url=self.url)
@@ -129,8 +116,8 @@ def get_api_endpoints(self, patterns, prefix=''):
callback = pattern.callback
if self.should_include_endpoint(path, callback):
for method in self.get_allowed_methods(callback):
- key = self.get_key(path, method, callback)
- endpoint = (key, path, method, callback)
+ action = self.get_action(path, method, callback)
+ endpoint = (path, method, action, callback)
api_endpoints.append(endpoint)
elif isinstance(pattern, RegexURLResolver):
@@ -140,7 +127,21 @@ def get_api_endpoints(self, patterns, prefix=''):
)
api_endpoints.extend(nested_endpoints)
- return api_endpoints
+ return self.add_categories(api_endpoints)
+
+ def add_categories(self, api_endpoints):
+ """
+ (path, method, action, callback) -> (path, method, category, action, callback)
+ """
+ # Determine the top level categories for the schema content,
+ # based on the URLs of the endpoints. Eg `set(['users', 'organisations'])`
+ paths = [endpoint[0] for endpoint in api_endpoints]
+ categories = self.get_categories(paths)
+
+ return [
+ (path, method, self.get_category(categories, path), action, callback)
+ for (path, method, action, callback) in api_endpoints
+ ]
def get_path(self, path_regex):
"""
@@ -177,23 +178,38 @@ def get_allowed_methods(self, callback):
callback.cls().allowed_methods if method not in ('OPTIONS', 'HEAD')
]
- def get_key(self, path, method, callback):
+ def get_action(self, path, method, callback):
"""
- Return a tuple of strings, indicating the identity to use for a
- given endpoint. eg. ('users', 'list').
+ Return a description action string for the endpoint, eg. 'list'.
"""
- category = None
- for item in path.strip('/').split('/'):
- if '{' in item:
- break
- category = item
-
actions = getattr(callback, 'actions', self.default_mapping)
- action = actions[method.lower()]
-
- if category:
- return (category, action)
- return (action,)
+ return actions[method.lower()]
+
+ def get_categories(self, paths):
+ categories = set()
+ split_paths = set([
+ tuple(path.split("{")[0].strip('/').split('/'))
+ for path in paths
+ ])
+
+ while split_paths:
+ for split_path in list(split_paths):
+ if len(split_path) == 0:
+ split_paths.remove(split_path)
+ elif len(split_path) == 1:
+ categories.add(split_path[0])
+ split_paths.remove(split_path)
+ elif split_path[0] in categories:
+ split_paths.remove(split_path)
+
+ return categories
+
+ def get_category(self, categories, path):
+ path_components = path.split("{")[0].strip('/').split('/')
+ for path_component in path_components:
+ if path_component in categories:
+ return path_component
+ return None
# Methods for generating each individual `Link` instance...
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -5,7 +5,7 @@
from rest_framework import filters, pagination, permissions, serializers
from rest_framework.compat import coreapi
-from rest_framework.decorators import detail_route
+from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
from rest_framework.routers import DefaultRouter
from rest_framework.schemas import SchemaGenerator
@@ -43,6 +43,10 @@ class ExampleViewSet(ModelViewSet):
def custom_action(self, request, pk):
return super(ExampleSerializer, self).retrieve(self, request)
+ @list_route()
+ def custom_list_action(self, request):
+ return super(ExampleViewSet, self).list(self, request)
+
def get_serializer(self, *args, **kwargs):
assert self.request
return super(ExampleViewSet, self).get_serializer(*args, **kwargs)
@@ -88,6 +92,10 @@ def test_anonymous_request(self):
coreapi.Field('ordering', required=False, location='query')
]
),
+ 'custom_list_action': coreapi.Link(
+ url='/example/custom_list_action/',
+ action='get'
+ ),
'retrieve': coreapi.Link(
url='/example/{pk}/',
action='get',
@@ -144,6 +152,10 @@ def test_authenticated_request(self):
coreapi.Field('d', required=False, location='form'),
]
),
+ 'custom_list_action': coreapi.Link(
+ url='/example/custom_list_action/',
+ action='get'
+ ),
'update': coreapi.Link(
url='/example/{pk}/',
action='put',
| Consider including list routes under associated categories when generating CoreAPI schema
Consider adding `@list_route()` actions under their associated categories when generated `CoreAPI` schema. Currently they are added as top level entries.
| Absolutely would want this behavior, yup. Thanks for raising this!
| 2016-08-11T12:55:00 |
encode/django-rest-framework | 4,388 | encode__django-rest-framework-4388 | [
"4201"
] | 116917dbed76ab37ab2d07f7b938d13f2c6e3efd | diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py
--- a/rest_framework/pagination.py
+++ b/rest_framework/pagination.py
@@ -312,6 +312,9 @@ def paginate_queryset(self, queryset, request, view=None):
self.request = request
if self.count > self.limit and self.template is not None:
self.display_page_controls = True
+
+ if self.count == 0 or self.offset > self.count:
+ return []
return list(queryset[self.offset:self.offset + self.limit])
def get_paginated_response(self, data):
| Paginators always repeat the query even if the count is 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.)
- [ ] 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.) - This can be done with a third party library, but I feel that it's a sensible improvement.
- [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.) - I haven't, since I'm not sure this is considered a bug/desired feature.
## Steps to reproduce
- Add a paginated view for an empty model (Only applies to LimitOffsetPagination)
- Make a GET request.
## Expected behavior
- If the count query returns 0, the actual query shouldn't be re-run
## Actual behavior
- The query is re-run.
This isn't a problem in the case I described, but in some cases the query can get quite complex and slow. Even if the view isn't wrapped in a transaction and it is possible to get rows on the second run, the results will be inconsistent, but the maybe expensive query is re-run.
| Do you have an analysis in regard to where the queryset is re-evaluated ?
It depends on the paginator, but, for LimitOffsetPagination it's [rest_framework/pagination.py:307](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/pagination.py#L307) (first one is line 303->53). For CursorPagination, this isn't an issue, since it doesn't do the count. For PageNumberPagination, this is done by [DjangoPaginator](https://github.com/django/django/blob/master/django/core/paginator.py#L61) (first one is 59->78).
While Django behaves the same, that's a separate issue and I will probably put in a ticket there as well. My main concern is whether this is a behaviour that seems sensible (it does to me).
> For PageNumberPagination, this is done by DjangoPaginator (first one is 59->78).
I've actually went and tested that, and it's not true. Django has an extra bit which [caps](https://github.com/django/django/blob/master/django/core/paginator.py#L59) the upper limit to the count and in qs.query.set_limits, if low and high are equal, it returns an empty QS, without going to the database.
So, I guess that answers my question whether this is intended behaviour or not, I'll make a PR tonight when I get home to unify the behaviour.
| 2016-08-11T15:41:15 |
|
encode/django-rest-framework | 4,394 | encode__django-rest-framework-4394 | [
"4329"
] | 1d26b398adab6df3727a86c1e1747e66d17706d6 | diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -39,6 +39,10 @@ class SchemaGenerator(object):
'patch': 'partial_update',
'delete': 'destroy',
}
+ known_actions = (
+ 'create', 'read', 'retrieve', 'list',
+ 'update', 'partial_update', 'destroy'
+ )
def __init__(self, title=None, url=None, patterns=None, urlconf=None):
assert coreapi, '`coreapi` must be installed for schema support.'
@@ -118,7 +122,8 @@ def get_api_endpoints(self, patterns, prefix=''):
if self.should_include_endpoint(path, callback):
for method in self.get_allowed_methods(callback):
action = self.get_action(path, method, callback)
- endpoint = (path, method, action, callback)
+ category = self.get_category(path, method, callback, action)
+ endpoint = (path, method, category, action, callback)
api_endpoints.append(endpoint)
elif isinstance(pattern, RegexURLResolver):
@@ -128,21 +133,7 @@ def get_api_endpoints(self, patterns, prefix=''):
)
api_endpoints.extend(nested_endpoints)
- return self.add_categories(api_endpoints)
-
- def add_categories(self, api_endpoints):
- """
- (path, method, action, callback) -> (path, method, category, action, callback)
- """
- # Determine the top level categories for the schema content,
- # based on the URLs of the endpoints. Eg `set(['users', 'organisations'])`
- paths = [endpoint[0] for endpoint in api_endpoints]
- categories = self.get_categories(paths)
-
- return [
- (path, method, self.get_category(categories, path), action, callback)
- for (path, method, action, callback) in api_endpoints
- ]
+ return api_endpoints
def get_path(self, path_regex):
"""
@@ -181,36 +172,41 @@ def get_allowed_methods(self, callback):
def get_action(self, path, method, callback):
"""
- Return a description action string for the endpoint, eg. 'list'.
+ Return a descriptive action string for the endpoint, eg. 'list'.
"""
actions = getattr(callback, 'actions', self.default_mapping)
return actions[method.lower()]
- def get_categories(self, paths):
- categories = set()
- split_paths = set([
- tuple(path.split("{")[0].strip('/').split('/'))
- for path in paths
- ])
-
- while split_paths:
- for split_path in list(split_paths):
- if len(split_path) == 0:
- split_paths.remove(split_path)
- elif len(split_path) == 1:
- categories.add(split_path[0])
- split_paths.remove(split_path)
- elif split_path[0] in categories:
- split_paths.remove(split_path)
-
- return categories
-
- def get_category(self, categories, path):
- path_components = path.split("{")[0].strip('/').split('/')
- for path_component in path_components:
- if path_component in categories:
- return path_component
- return None
+ def get_category(self, path, method, callback, action):
+ """
+ Return a descriptive category string for the endpoint, eg. 'users'.
+
+ Examples of category/action pairs that should be generated for various
+ endpoints:
+
+ /users/ [users][list], [users][create]
+ /users/{pk}/ [users][read], [users][update], [users][destroy]
+ /users/enabled/ [users][enabled] (custom action)
+ /users/{pk}/star/ [users][star] (custom action)
+ /users/{pk}/groups/ [groups][list], [groups][create]
+ /users/{pk}/groups/{pk}/ [groups][read], [groups][update], [groups][destroy]
+ """
+ path_components = path.strip('/').split('/')
+ path_components = [
+ component for component in path_components
+ if '{' not in component
+ ]
+ if action in self.known_actions:
+ # Default action, eg "/users/", "/users/{pk}/"
+ idx = -1
+ else:
+ # Custom action, eg "/users/{pk}/activate/", "/users/active/"
+ idx = -2
+
+ try:
+ return path_components[idx]
+ except IndexError:
+ return None
# Methods for generating each individual `Link` instance...
| Schema autogeneration
# Schema Autogeneration
This pull request addresses Schema autogeneration from the API views.
1. it resolves a bug where the higher namespace urls (/account/{account_id}/books/{pk}/) are hidden by lower namespace (/account/{pk}/).
2. It uses the docstring of the method that will handle the request (either get, post, put, etc for the APIView or list, retrieve, update for the viewset) as the description of the coreapi.Link.
3. It uses the help_text of the serializers fields as the description of the coreapi.Field.
4. It capitalize the names of the Link.
| Great stuff in here, thanks!
Will review shortly.
Okay, so there's a number of different aspects here, some we want, some we probably don't, some may need further thought.
1. Yes, we should resolve that, although not 100% clear to me exactly what we should use for the key generation. Needs further thought.
2. Useful, although note that this would _also_ pull in unhelpful docstrings from the default mixin implementations, so not sure how we should best handle that.
3. Yes.
4. Not totally convinced if we should be using `Humanized` or `programatic` formatting for the keys.
The `path_descriptions` API you've added is also perfectly reasonable, tho again, I'm not 100% sure if it's exactly what we want or not.
1. Sounds like an issue, but I can't think of a clean way to resolve them properly. Someone else who has more experience reverse-engineering url patterns can probably chip in here.
2. I'm a fan of this, because I personally have a tendency to write method-specific documentation when I'm overriding them. With that said, I do see the issue that Tom mentioned with the default mixins having developer-oriented documentation instead of user-oriented documentation. I'd personally prefer developer-oriented documentation there, so I don't have a solution.
3. Handled in https://github.com/tomchristie/django-rest-framework/pull/4387.
4. Imo, this is better handled client-side. The keys appear to match the url path for links right now, and this change can be done on the client if needed.
On second thoughts I noted that the `.get` etc... methods that we provide in REST framework _don't_ have default docstrings, so we _could_ use them. Although some users will be using base classes and/or mixins where the docstrings may not be correct/relevant, so point still applies, but less so than it would otherwise.
- Some remaining work on (1) prior to the 3.4.4 release - still not handling that quite right.
- For (2) I'm happy to reassess that as part of 3.5.0 - happy to see an individual issue opened for it. We're adding in the form field descriptions now. We could also look at addressing path field and query field descriptions.
- 3. Now resolved.
- 4. Going to stay with lowercase for now. We'll firm up the generator API methods and document them as public API, so that folks can introduce third party packages with overrides if wanted.
| 2016-08-12T09:37:08 |
|
encode/django-rest-framework | 4,408 | encode__django-rest-framework-4408 | [
"4398"
] | 101fd29039dc17df3ad317580cf4bcf5ba1c1c03 | diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -79,6 +79,13 @@ def get_schema(self, request=None):
view.kwargs = {}
view.format_kwarg = None
+ actions = getattr(callback, 'actions', None)
+ if actions is not None:
+ if method == 'OPTIONS':
+ view.action = 'metadata'
+ else:
+ view.action = actions.get(method.lower())
+
if request is not None:
view.request = clone_request(request, method)
try:
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -49,6 +49,7 @@ def custom_list_action(self, request):
def get_serializer(self, *args, **kwargs):
assert self.request
+ assert self.action
return super(ExampleViewSet, self).get_serializer(*args, **kwargs)
| 'ViewSet' object has no attribute 'action' during Schema generation
## Steps to reproduce
Create a `ModelViewSet` that uses `get_serializer_class()`:
``` python
class MyViewSet(viewsets.ModelViewSet):
queryset = Person.objects.all()
def get_serializer_class(self):
if self.action == 'list':
return serializers.SerializerB
return serializers.SerializerA
```
## Expected behavior
Schema should be generated in a view that uses the `CoreJSONRenderer`.
## Actual behavior
An `AttributeError` is thrown: `'MyViewSet' object has no attribute 'action'`.
This is related to #4373 and #4278. If this isn't a bug, I may be missing something...the docs do have this method as the suggested way to dynamically change serializers.
Using djangorestframework==3.4.4 and python2.7.
| Yup, makes sense. Thanks for raising this.
| 2016-08-15T16:00:49 |
encode/django-rest-framework | 4,415 | encode__django-rest-framework-4415 | [
"4410"
] | 966330a85a404b2967883c5366548cad4e3586d0 | diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py
--- a/rest_framework/renderers.py
+++ b/rest_framework/renderers.py
@@ -645,6 +645,12 @@ def get_context(self, data, accepted_media_type, renderer_context):
else:
paginator = None
+ csrf_cookie_name = settings.CSRF_COOKIE_NAME
+ csrf_header_name = getattr(settings, 'CSRF_HEADER_NAME', 'HTTP_X_CSRFToken') # Fallback for Django 1.8
+ if csrf_header_name.startswith('HTTP_'):
+ csrf_header_name = csrf_header_name[5:]
+ csrf_header_name = csrf_header_name.replace('_', '-')
+
context = {
'content': self.get_content(renderer, data, accepted_media_type, renderer_context),
'view': view,
@@ -675,7 +681,8 @@ def get_context(self, data, accepted_media_type, renderer_context):
'display_edit_forms': bool(response.status_code != 403),
'api_settings': api_settings,
- 'csrf_cookie_name': settings.CSRF_COOKIE_NAME,
+ 'csrf_cookie_name': csrf_cookie_name,
+ 'csrf_header_name': csrf_header_name
}
return context
| rest_framework api view not working when CSRF_HEADER_NAME param is not 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](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
Set custom CSRF header name in settings.py eg.
setting.py:
``` python
CSRF_HEADER_NAME = "HTTP_X_XSRF_TOKEN"
```
1. Go to api view
2. Login to account with permission to modificate any data
3. make request with unsafe method - for example modify data
## Expected behavior
Request should work and data should be modified.
## Actual behavior
Systems gives error CSRF Failed: CSRF token missing or incorrect.
## Patch
**rest_framework/static/rest_framework/js/csrf.js** change line 49 to:
``` javascript
xhr.setRequestHeader(window.drf.csrfHeaderName, csrftoken);
```
**rest_framework/templates/rest_framework/base.html** add new line between lines 265-266 from:
``` javascript
window.drf = {
csrfCookieName: "{{ csrf_cookie_name|default:'csrftoken' }}"
};
```
to
``` javascript
window.drf = {
csrfHeaderName: "{{ csrf_header_name|default:'X-CSRFToken' }}",
csrfCookieName: "{{ csrf_cookie_name|default:'csrftoken' }}"
};
```
same story in file **rest_framework/templates/rest_framework/admin.html** but modification should be done between lines 234 and 235
``` javascript
window.drf = {
csrfCookieName: "{{ csrf_cookie_name|default:'csrftoken' }}"
};
```
to
``` javascript
window.drf = {
csrfHeaderName: "{{ csrf_header_name|default:'X-CSRFToken' }}",
csrfCookieName: "{{ csrf_cookie_name|default:'csrftoken' }}"
};
```
**rest_framework/renderers.py** add new line between 678 and 679 before:
``` javascript
'csrf_cookie_name': settings.CSRF_COOKIE_NAME,
}
```
after
``` javascript
'csrf_cookie_name': settings.CSRF_COOKIE_NAME,
'csrf_header_name': (settings.CSRF_HEADER_NAME[5:].replace("_","-") if settings.CSRF_HEADER_NAME.startswith('HTTP_') else settings.CSRF_HEADER_NAME.replace("_","-")),
}
```
and that is all. Last modification have those replaces call because Django documentation say:
```
As with other HTTP headers in request.META, the header name received from the server is normalized by converting all characters to uppercase, replacing any hyphens with underscores, and adding an 'HTTP_' prefix to the name. For example, if your client sends a 'X-XSRF-TOKEN' header, the setting should be 'HTTP_X_XSRF_TOKEN'.
```
ps. great job guys! Nice module.
| Great, thanks for the comprehensive report!
| 2016-08-18T09:48:53 |
|
encode/django-rest-framework | 4,416 | encode__django-rest-framework-4416 | [
"4409"
] | b76984d222281e58e3105df0128141567b9a7697 | diff --git a/rest_framework/request.py b/rest_framework/request.py
--- a/rest_framework/request.py
+++ b/rest_framework/request.py
@@ -391,3 +391,8 @@ def QUERY_PARAMS(self):
'`request.QUERY_PARAMS` has been deprecated in favor of `request.query_params` '
'since version 3.0, and has been fully removed as of version 3.2.'
)
+
+ def force_plaintext_errors(self, value):
+ # Hack to allow our exception handler to force choice of
+ # plaintext or html error responses.
+ self._request.is_ajax = lambda: value
diff --git a/rest_framework/views.py b/rest_framework/views.py
--- a/rest_framework/views.py
+++ b/rest_framework/views.py
@@ -3,17 +3,14 @@
"""
from __future__ import unicode_literals
-import sys
-
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db import models
from django.http import Http404
-from django.http.response import HttpResponse, HttpResponseBase
+from django.http.response import HttpResponseBase
from django.utils import six
from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
-from django.views import debug
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
@@ -95,11 +92,6 @@ def exception_handler(exc, context):
set_rollback()
return Response(data, status=status.HTTP_403_FORBIDDEN)
- # throw django's error page if debug is True
- if settings.DEBUG:
- exception_reporter = debug.ExceptionReporter(context.get('request'), *sys.exc_info())
- return HttpResponse(exception_reporter.get_traceback_html(), status=500)
-
return None
@@ -439,11 +431,19 @@ def handle_exception(self, exc):
response = exception_handler(exc, context)
if response is None:
- raise
+ self.raise_uncaught_exception(exc)
response.exception = True
return response
+ def raise_uncaught_exception(self, exc):
+ if settings.DEBUG:
+ request = self.request
+ renderer_format = getattr(request.accepted_renderer, 'format')
+ use_plaintext_traceback = renderer_format not in ('html', 'api', 'admin')
+ request.force_plaintext_errors(use_plaintext_traceback)
+ raise
+
# Note: Views are made CSRF exempt from within `as_view` as to prevent
# accidental removal of this exemption in cases where `dispatch` needs to
# be overridden.
| Tracebacks not printed on console v 3.4.4 | Logger
With 3.4.4 Tracebacks are not being printed on console. For version 3.3.3 - 3.4.3, Tracebacks were/are printed fine on console. But in version 3.4.4 it prints only in the browser.
This may be the reason for the issue [#4172](https://github.com/tomchristie/django-rest-framework/pull/4172)
Using - Django v1.9.9
Here is my logger config...
```
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '[%(levelname)s] %(asctime)s | %(module)s %(funcName)s %(lineno)d | PID - %(process)d, Thread - %(thread)d | %(message)s'
},
},
'handlers': {
'general': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': '/var/log/app/general.log',
'maxBytes': 1024*1024*10,
'backupCount': 10,
'formatter': 'verbose',
},
'request': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': '/var/log/app/request.log',
'maxBytes': 1024*1024*10,
'backupCount': 10,
'formatter': 'verbose',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
}
},
'loggers': {
'': {
'handlers': ['console', 'general'],
'level': 'DEBUG',
},
'django.request': {
'handlers': ['console', 'request'],
'level': 'DEBUG',
'propagate': False,
}
}
}
```
| 2016-08-18T13:03:07 |
||
encode/django-rest-framework | 4,423 | encode__django-rest-framework-4423 | [
"4419"
] | 63342e81db53260ca4a0defc2b7ed00ed9be3698 | diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -10,7 +10,7 @@
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.utils import six
-from django.utils.encoding import smart_text
+from django.utils.encoding import python_2_unicode_compatible, smart_text
from django.utils.six.moves.urllib import parse as urlparse
from django.utils.translation import ugettext_lazy as _
@@ -47,6 +47,7 @@ def __getnewargs__(self):
is_hyperlink = True
+@python_2_unicode_compatible
class PKOnlyObject(object):
"""
This is a mock object, used for when we only need the pk of the object
@@ -56,6 +57,9 @@ class PKOnlyObject(object):
def __init__(self, pk):
self.pk = pk
+ def __str__(self):
+ return "%s" % self.pk
+
# We assume that 'validators' are intended for the child serializer,
# rather than the parent serializer.
| PKOnlyObject doesn't have __str__/__unicode__ methods
## 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
Select admin renderer. View a model that has a ForeignKey like `origin = models.ForeignKey(Address, related_name='+')` See gibberish output like `<rest_framework.relations.PKOnlyObject object at 0x7f943b762950>`
## Expected behavior
my-pretty-pk-uuid-string
## Actual behavior
`<rest_framework.relations.PKOnlyObject object at 0x7f9a6903d510>`
Should be fairly simple to add **str**/**unicode** methods so the link text is the pk value instead of something like `<rest_framework.relations.PKOnlyObject object at 0x7f9a6903d510>.`
This simple monkey patch fixes the issue so I assume adding the method won't cause any problems
```
from rest_framework.relations import PKOnlyObject
PKOnlyObject.__str__ = lambda obj: str(obj.pk)
```
| Could you add a screenshot so we get the big picture ?
```
PKOnlyObject.__str__ = lambda obj: str(obj.pk)
PKOnlyObject.__unicode__ = lambda obj: text_type(obj.pk)
```
no monkeypatch:
<img width="959" alt="drf-issue-4419-no-monkeypatch" src="https://cloud.githubusercontent.com/assets/77731/17809717/989067d6-65e6-11e6-91b7-0b56a2c38db6.png">
has monkeypatch:
<img width="960" alt="drf-issue-4419-has-monkeypatch" src="https://cloud.githubusercontent.com/assets/77731/17809731/a4bcd74c-65e6-11e6-803c-03b5f63b976e.png">
| 2016-08-19T13:05:45 |
|
encode/django-rest-framework | 4,429 | encode__django-rest-framework-4429 | [
"4425"
] | d540f0262b4b0a5f8ce628334d1a812179556002 | diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -296,8 +296,9 @@ def get_serializer_fields(self, path, method, callback, view):
fields = []
for field in serializer.fields.values():
- if field.read_only:
+ if field.read_only or isinstance(field, serializers.HiddenField):
continue
+
required = field.required and method != 'PATCH'
description = force_text(field.help_text) if field.help_text else ''
field = coreapi.Field(
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -26,6 +26,8 @@ class ExamplePagination(pagination.PageNumberPagination):
class ExampleSerializer(serializers.Serializer):
a = serializers.CharField(required=True, help_text='A field description')
b = serializers.CharField(required=False)
+ read_only = serializers.CharField(read_only=True)
+ hidden = serializers.HiddenField(default='hello')
class AnotherSerializer(serializers.Serializer):
| SchemaGenerator add Serializer HiddenFields to parameters
When SchemaGenerator return `.get_schema()` data, HiddenFields included to views parameters:
### Serializer
``` python
class CommonDriverVehiclePOSTSerializer(serializers.ModelSerializer):
class Meta:
model = vehicle_mdl.Vehicle
exclude = ['deleted', ]
read_only_fields = ['full_name', 'company']
driver = serializers.HiddenField(default=CurrentDriverProfileDefault())
```
### Generator response
```
post: {
description: "",
parameters: [
{type: "string", name: "driver", required: false, description: "", in: "formData"},
],
}
```
| Thanks for the report!
Giant thanks for you. DRF is amazing.
Actually, what you think about `channels` project? I try implement it in my last project now. Is it good idea to include support of it to DRF? It may be a first in the world REST framework via Websockets.
| 2016-08-21T15:28:06 |
encode/django-rest-framework | 4,490 | encode__django-rest-framework-4490 | [
"2617"
] | a68b37d8bc432fae37ef5880aec500002b59f565 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -252,6 +252,8 @@ class SkipField(Exception):
pass
+REGEX_TYPE = type(re.compile(''))
+
NOT_READ_ONLY_WRITE_ONLY = 'May not set both `read_only` and `write_only`'
NOT_READ_ONLY_REQUIRED = 'May not set both `read_only` and `required`'
NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`'
@@ -581,16 +583,17 @@ def __deepcopy__(self, memo):
When cloning fields we instantiate using the arguments it was
originally created with, rather than copying the complete state.
"""
- args = copy.deepcopy(self._args)
- kwargs = dict(self._kwargs)
- # Bit ugly, but we need to special case 'validators' as Django's
- # RegexValidator does not support deepcopy.
- # We treat validator callables as immutable objects.
+ # Treat regexes and validators as immutable.
# See https://github.com/tomchristie/django-rest-framework/issues/1954
- validators = kwargs.pop('validators', None)
- kwargs = copy.deepcopy(kwargs)
- if validators is not None:
- kwargs['validators'] = validators
+ # and https://github.com/tomchristie/django-rest-framework/pull/4489
+ args = [
+ copy.deepcopy(item) if not isinstance(item, REGEX_TYPE) else item
+ for item in self._args
+ ]
+ kwargs = {
+ key: (copy.deepcopy(value) if (key not in ('validators', 'regex')) else value)
+ for key, value in self._kwargs.items()
+ }
return self.__class__(*args, **kwargs)
def __repr__(self):
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -1,5 +1,6 @@
import datetime
import os
+import re
import uuid
from decimal import Decimal
@@ -590,6 +591,20 @@ class TestRegexField(FieldValues):
field = serializers.RegexField(regex='[a-z][0-9]')
+class TestiCompiledRegexField(FieldValues):
+ """
+ Valid and invalid values for `RegexField`.
+ """
+ valid_inputs = {
+ 'a9': 'a9',
+ }
+ invalid_inputs = {
+ 'A9': ["This value does not match the required pattern."]
+ }
+ outputs = {}
+ field = serializers.RegexField(regex=re.compile('[a-z][0-9]'))
+
+
class TestSlugField(FieldValues):
"""
Valid and invalid values for `SlugField`.
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 @@
from __future__ import unicode_literals
import pickle
+import re
import pytest
@@ -337,3 +338,16 @@ def test_default_should_not_be_included_on_partial_update(self):
assert serializer.is_valid()
assert serializer.validated_data == {'integer': 456}
assert serializer.errors == {}
+
+
+class TestSerializerValidationWithCompiledRegexField:
+ def setup(self):
+ class ExampleSerializer(serializers.Serializer):
+ name = serializers.RegexField(re.compile(r'\d'), required=True)
+ self.Serializer = ExampleSerializer
+
+ def test_validation_success(self):
+ serializer = self.Serializer(data={'name': '2'})
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'name': '2'}
+ assert serializer.errors == {}
| Overriding Field.__deepcopy__ for RegexField
Problem:
`Serializers` are deepcopying a declared `RegexField`[[source]](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L324), but it'll error out with the message. `TypeError: cannot deepcopy this pattern object`.



| I think this needs a test in order to verify that now the RegexField can be deep copied with compiled regex patterns.
Something like:
``` python
# ...
serializer = TestSerializer(data={'regex_field': 'abc'})
try:
serializer.get_fields()
except TypeError as e:
if e.msg == 'cannot deepcopy this pattern object' and isinstance(e, TypeError):
assert False, 'Compiled regex patterns cannot be deep copied.'
else:
traceback.print_traceback()
raise e
```
Hi there,
Wondering if there's been a decision made on this? I'm running into the same deepcopy issue with RegexFields.
Having `regex` [taken out of kwargs](https://github.com/tomchristie/django-rest-framework/blob/3.4.6/rest_framework/fields.py#L734)
```
def __init__(self, regex, **kwargs):
super(RegexField, self).__init__(**kwargs)
<..snip..>
```
doesn't seem to avoid them [being in `self._kwargs`](https://github.com/tomchristie/django-rest-framework/blob/3.4.6/rest_framework/fields.py#L576)
```
def __new__(cls, *args, **kwargs):
"""
When a field is instantiated, we store the arguments that were used,
so that we can present a helpful representation of the object.
"""
<..snip..>
instance._kwargs = kwargs
return instance
```
and it's `self._kwargs` that actually ends up being `deepcopy()`ed in `__deepcopy__`
```
def __deepcopy__(self, memo):
"""
When cloning fields we instantiate using the arguments it was
originally created with, rather than copying the complete state.
"""
args = copy.deepcopy(self._args)
kwargs = dict(self._kwargs)
<..snip..>
kwargs = copy.deepcopy(kwargs)
<..snip..>
```
Bumping up the priority to ensure this gets reviewed sometime over the coming weeks.
To add on, this happens only when I'm using a compiled regex object as the `regex` argument (either as a positional parameter, or as a keyword argument).
Using a pattern string works fine
eg.
```
import re
USERNAME_RE = re.compile(r"[a-z0-9]+")
username = serializers.RegexField(regex=USERNAME_RE) # This eventually fails
username = seriazliers.RegexField(regex=USERNAME_RE.pattern) # This works
```
Noted. Thanks!
| 2016-09-15T10:58:17 |
encode/django-rest-framework | 4,500 | encode__django-rest-framework-4500 | [
"3951"
] | e82ee9107827329508b716bb0add707a338219ef | diff --git a/rest_framework/request.py b/rest_framework/request.py
--- a/rest_framework/request.py
+++ b/rest_framework/request.py
@@ -15,6 +15,7 @@
from django.conf import settings
from django.http import QueryDict
from django.http.multipartparser import parse_header
+from django.http.request import RawPostDataException
from django.utils import six
from django.utils.datastructures import MultiValueDict
@@ -263,10 +264,20 @@ def _load_stream(self):
if content_length == 0:
self._stream = None
- elif hasattr(self._request, 'read'):
+ elif not self._request._read_started:
self._stream = self._request
else:
- self._stream = six.BytesIO(self.raw_post_data)
+ self._stream = six.BytesIO(self.body)
+
+ def _supports_form_parsing(self):
+ """
+ Return True if this requests supports parsing form data.
+ """
+ form_media = (
+ 'application/x-www-form-urlencoded',
+ 'multipart/form-data'
+ )
+ return any([parser.media_type in form_media for parser in self.parsers])
def _parse(self):
"""
@@ -274,8 +285,18 @@ def _parse(self):
May raise an `UnsupportedMediaType`, or `ParseError` exception.
"""
- stream = self.stream
media_type = self.content_type
+ try:
+ stream = self.stream
+ except RawPostDataException:
+ if not hasattr(self._request, '_post'):
+ raise
+ # If request.POST has been accessed in middleware, and a method='POST'
+ # request was made with 'multipart/form-data', then the request stream
+ # will already have been exhausted.
+ if self._supports_form_parsing():
+ return (self._request.POST, self._request.FILES)
+ stream = None
if stream is None or media_type is None:
empty_data = QueryDict('', encoding=self._request._encoding)
| diff --git a/tests/test_parsers.py b/tests/test_parsers.py
--- a/tests/test_parsers.py
+++ b/tests/test_parsers.py
@@ -7,11 +7,16 @@
from django.core.files.uploadhandler import (
MemoryFileUploadHandler, TemporaryFileUploadHandler
)
+from django.http.request import RawPostDataException
from django.test import TestCase
from django.utils.six.moves import StringIO
from rest_framework.exceptions import ParseError
-from rest_framework.parsers import FileUploadParser, FormParser
+from rest_framework.parsers import (
+ FileUploadParser, FormParser, JSONParser, MultiPartParser
+)
+from rest_framework.request import Request
+from rest_framework.test import APIRequestFactory
class Form(forms.Form):
@@ -122,3 +127,39 @@ def test_get_encoded_filename(self):
def __replace_content_disposition(self, disposition):
self.parser_context['request'].META['HTTP_CONTENT_DISPOSITION'] = disposition
+
+
+class TestPOSTAccessed(TestCase):
+ def setUp(self):
+ self.factory = APIRequestFactory()
+
+ def test_post_accessed_in_post_method(self):
+ django_request = self.factory.post('/', {'foo': 'bar'})
+ request = Request(django_request, parsers=[FormParser(), MultiPartParser()])
+ django_request.POST
+ assert request.POST == {'foo': ['bar']}
+ assert request.data == {'foo': ['bar']}
+
+ def test_post_accessed_in_post_method_with_json_parser(self):
+ django_request = self.factory.post('/', {'foo': 'bar'})
+ request = Request(django_request, parsers=[JSONParser()])
+ django_request.POST
+ assert request.POST == {}
+ assert request.data == {}
+
+ def test_post_accessed_in_put_method(self):
+ django_request = self.factory.put('/', {'foo': 'bar'})
+ request = Request(django_request, parsers=[FormParser(), MultiPartParser()])
+ django_request.POST
+ assert request.POST == {'foo': ['bar']}
+ assert request.data == {'foo': ['bar']}
+
+ def test_request_read_before_parsing(self):
+ django_request = self.factory.put('/', {'foo': 'bar'})
+ request = Request(django_request, parsers=[FormParser(), MultiPartParser()])
+ django_request.read()
+ with pytest.raises(RawPostDataException):
+ request.POST
+ with pytest.raises(RawPostDataException):
+ request.POST
+ request.data
| Request.data empty when multipart/form-data POSTed
Django==1.9.2
djangorestframework==3.3.2
This is essentially a repost of #3814. There is already some research and discussion attached to that issue that I will not rehash, but the author closed out the item once a workaround was found.
Is that workaround the long term solution? Is the answer to never touch the Django Request before DRF has a chance to do its thing? This can be difficult to control in projects with third party middleware.
The issue seems to be that, when POSTing data, Django is exhausting the underlying request stream if the WSGIRequest is accessed prior to initialize_request in the DRF View dispatcher. PUTs seem to be unaffected.
A totally contrived example that demonstrates the issue. First example, presuming no middleware Request meddling...
``` python
class TestView(APIView):
def post(self, request, *args, **kwargs):
# request.data, .FILES, and .POST are populated
# request._request.FILES and .POST are empty
return Response()
def put(self, request, *args, **kwargs):
# request.data, .FILES, and .POST are populated
# request._request.FILES and .POST are empty
return Response()
```
Second example, forcibly evaluating the Django request before dispatching.
``` python
class TestView(APIView):
def dispatch(self, request, *args, **kwargs):
p = request.POST # Force evaluation of the Django request
return super().dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
# request.data, .FILES, and .POST are empty
# request._request.FILES and .POST are populated
return Response()
def put(self, request, *args, **kwargs):
# request.data, .FILES, and .POST are populated
# request._request.FILES and .POST are empty
return Response()
```
Cheers!
| +1 here. The workaround for the previously closed issue is not a solution for the issue at hand. The truth is that there very well is a use case for accessing the Django POST QueryDict in middleware before DRF can consume it.
As there is for streaming content too which breaks the use of middleware introspecting the request content.
Moreover, if a middleware do look at the request content, it means it'll bypasses at least partially the content negotiation. At this point, it's probably a good option not to use DRF views and explicitly feed the serializer if required.
I'd also be interested in learning a bit more in your solution about this issue - in particular how to preserve the compatibility with the current behavior.
The closest I've come to a "solution" is to add an additional check in the `_parse` method of the DRF `Request`:
``` python
...
try:
parsed = parser.parse(stream, media_type, self.parser_context)
# If Django got to the POST/FILES data before we did, just use theirs.
if (len(parsed.data) + len(parsed.files)) < 1:
parsed.data = self._request.POST
parsed.files = self._request.FILES
except:
# If we get an exception during parsing, fill in empty data and
...
```
I'm not sure how dangerous it is to use Django's POST data directly like this (rather than making a copy). They seem to be essentially read only once parsed.
While this retains the current Django WSGIRequest behavior, it leaves it in an inconsistent state insofar as POSTs may or may not have POST/FILE data depending on whether or not the request was touched prior to DRF Request parsing.
Just hit this on production today...
As workaround, I've put a check in our base GenericAPIView instead of custom middleware
(for compatibility must keep both override methods)
``` python
def initialize_request(self, request, *args, **kwargs):
request = super().initialize_request(request, *args, **kwargs)
if request.path.startswith("/api/3/") and request.method == "POST":
request.method = request.META.get("HTTP_X_HTTP_METHOD_OVERRIDE", request.POST.get("_method", request.method)).upper()
return request
```
Also running into this problem. It appears to have been introduced in `3.2` (was not experiencing it while using `3.1.1`).
Does anyone know if there is a way to reset the `request` object to its original state after examination or possibly duplicate the object without exhausting the POST data stream?
It feels like DRF should be capable of using an already-examined `WSGIRequest`.
+1
I have run into a similar issue. I created a new `nested_route` decorator that acts a lot like `list_route` and `detail_route`. I usually redirect to another viewset to handle the nested path. The issue was that the stream was being read too early (by the parent viewset `dispatch`), so I needed to ensure that the `initialize_request` function was only called once for a given request.
Working off of @rsalmaso's comment above, I overrode the `initialize_request` method in the children viewsets with the following.
```
def initialize_request(self, request, *args, **kwargs):
if not isinstance(request, Request):
request = super().initialize_request(request, *args, **kwargs)
return request
```
This works fine, but I think having some sort of attribute for either ignoring the `initialize_request` function within `dispatch` or having a global check to only run `initialize_request` iff `isinstance(request, rest_framework.request.Request) == False`. I'm happy to prepare the PR with tests if that could be acceptable.
I have the same issue. For now I have reverted to drf 3.2
I've spent almost 3 hours searching about why my data wouldn't be parsed correctly. I first thought the issue was on my Angular App code. And I finally found this issue. Damn, almost banged my head on my desk.
The only work around working for me is getting back to 3.2.5. I'm surprised this issue has no real fix ?
This shows what [open source really is](http://www.commitstrip.com/en/2014/05/07/the-truth-behind-open-source-apps/).
To get this fixed, the first step is to have someone take time and have a deep analysis of when / why and how the behavior change has been introduced. An initial analysis was performed on #3814 though it requires confirmation that the mentioned change did affect the behavior and then identify how the behavior change has been introduced.
Before that, I won't be able to consider the various workarounds as a solution.
Here's what I've managed to track down.
The change definitely occurred in commit 566812a as part of removing method and content overriding. Prior to that change, in [request.py](https://github.com/tomchristie/django-rest-framework/blob/721efa28176507434a2f4b006f2f31b9a33ca2aa/rest_framework/request.py), the [_load_data_and_files](https://github.com/tomchristie/django-rest-framework/blob/721efa28176507434a2f4b006f2f31b9a33ca2aa/rest_framework/request.py#L264) method called [_load_method_and_content_type](https://github.com/tomchristie/django-rest-framework/blob/721efa28176507434a2f4b006f2f31b9a33ca2aa/rest_framework/request.py#L279) which called [_perform_form_overloading](https://github.com/tomchristie/django-rest-framework/blob/721efa28176507434a2f4b006f2f31b9a33ca2aa/rest_framework/request.py#L316). Within [_perform_form_overloading](https://github.com/tomchristie/django-rest-framework/blob/721efa28176507434a2f4b006f2f31b9a33ca2aa/rest_framework/request.py#L316) was a [bit of code](https://github.com/tomchristie/django-rest-framework/blob/721efa28176507434a2f4b006f2f31b9a33ca2aa/rest_framework/request.py#L336) that seeded the DRF Request._data attribute with Request._request.POST (which is the Django WSGIRequest POST).
``` python
# At this point we're committed to parsing the request as form data.
self._data = self._request.POST
self._files = self._request.FILES
self._full_data = self._data.copy()
self._full_data.update(self._files)
```
This means that, back in [_load_data_and_files](https://github.com/tomchristie/django-rest-framework/blob/721efa28176507434a2f4b006f2f31b9a33ca2aa/rest_framework/request.py#L264), [_parse](https://github.com/tomchristie/django-rest-framework/blob/721efa28176507434a2f4b006f2f31b9a33ca2aa/rest_framework/request.py#L360) was probably never called for multipart POSTs (at least not in the default configuration) and thus DRF did not attempt to re-read the request stream.
In more recent versions of DRF, [_load_data_and_files](https://github.com/tomchristie/django-rest-framework/blob/0c42c742290400e3ee742e77268681b6911604ed/rest_framework/request.py#L238) no longer calls _load_method_and_content_type as that method no longer exists, so now execution is falling through to the call to [_parse](https://github.com/tomchristie/django-rest-framework/blob/0c42c742290400e3ee742e77268681b6911604ed/rest_framework/request.py#L269). Herein lies the problem.
For multipart POSTs, [_parse](https://github.com/tomchristie/django-rest-framework/blob/0c42c742290400e3ee742e77268681b6911604ed/rest_framework/request.py#L269) is using a [DRF MultiPartParser](https://github.com/tomchristie/django-rest-framework/blob/0c42c742290400e3ee742e77268681b6911604ed/rest_framework/parsers.py#L90) which is using a [Django MultiPartParser](https://github.com/django/django/blob/dafddb6b8c0eb778072bec1ccd536bafad0eb936/django/http/multipartparser.py#L45) which is attempting to re-read the request stream which has previously been exhausted.
So, another potential solution would be to just allow Django to handle the parsing of multipart forms. This could be achieved by replacing the [MultiPartParser.parse](https://github.com/tomchristie/django-rest-framework/blob/0c42c742290400e3ee742e77268681b6911604ed/rest_framework/parsers.py#L97) method with something more along the lines of:
``` python
def parse(self, stream, media_type=None, parser_context=None):
"""
Parses the incoming bytestream as a multipart encoded form,
and returns a DataAndFiles object.
`.data` will be a `QueryDict` containing all the form parameters.
`.files` will be a `QueryDict` containing all the form files.
"""
parser_context = parser_context or {}
request = parser_context['request']
_request = request._request
if _request.method == 'POST':
return DataAndFiles(_request.POST, _request.FILES)
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
meta = request.META.copy()
meta['CONTENT_TYPE'] = media_type
upload_handlers = request.upload_handlers
try:
parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding)
data, files = parser.parse()
return DataAndFiles(data, files)
except MultiPartParserError as exc:
raise ParseError('Multipart form parse error - %s' % six.text_type(exc))
```
This essentially grabs the WSGIRequest that underlies the DRF Request and allows it to perform the request parsing. What I don't know is, are there any conditions under which Django would use another parser when DRF is expecting a MultiPartParser?
Edit: Updated "fix" code. Forgot that Django really only parses POSTs for multipart forms. Also wanted to note that I'm working on tests and eventually a pull request.
I'm depending on this fix. Are there already plans on when to release it?
I experience the same in 3.3.3. Had to roll back to 3.2.4 on Django 1.8.13. A patch for this issue is highly anticipated.
I met the same issue today. Doing PUT instead of POST is really the solution for now.
I'll put it on the list, but no promises if it'll make the 3.4.0 cut or not. We'll see.
I did some digging on this too as I ran into it as well.
(This is django 1.8)
The DjangoMultiPartParser loops through the upload_handlers and called handle_raw_input which should return something, but none of them do.
The MemoryFileUploadHandler just set's activated to True and the TemporaryFileUploadHandler doesn't even implement it.
So maybe the handlers being passed are the wrong one, or rest framework is using the DjangoMultiPartParser wrong.
+1 Answering @alukach, I have the same issue but only when updating to `3.3.0`. With `3.2.0` works fine (I had to downgrade)
Ran in to this issue as well :-( Had to drop back to version 3.2
Anything I (we as a company) can do to help with this?
This is preventing us from upgrading to drf >= 3.3 and thus is also blocking our django upgrade.
Well, it's on the list, and being re-raised by folks, so I'd expect to deal with it prior to 3.5, hopefully towards the end of this month.
> Anything I (we as a company) can do to help with this?
This, this, this...
https://fund.django-rest-framework.org/topics/funding/
(We're just a few % short of what we need for baseline sustainability right now, getting over the mark will mean I can focus exclusively on the project itself)
So, we're (Zupr) now funding you to work on DRF 🎉
This issue has the label Needs information and there is a pull request #4026 with a label needs further review.
Now the pull request by @CaffeineFueled currently does not merge cleanly (but only conflicts in the test file) and was created against 3.3.2 (which was the version that had the issue show up for the first time).
I used the pull request version with our code and ran the test suite (1024 tests, ~84% coverage) and all the test passed.
| 2016-09-21T10:38:48 |
encode/django-rest-framework | 4,553 | encode__django-rest-framework-4553 | [
"2442"
] | a3802504a0a26f1d03d2cf6f851030314b7372fd | diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py
--- a/rest_framework/mixins.py
+++ b/rest_framework/mixins.py
@@ -68,6 +68,13 @@ def update(self, request, *args, **kwargs):
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
+
+ if getattr(instance, '_prefetched_objects_cache', None):
+ # If 'prefetch_related' has been applied to a queryset, we need to
+ # refresh the instance from the database.
+ instance = self.get_object()
+ serializer = self.get_serializer(instance)
+
return Response(serializer.data)
def perform_update(self, serializer):
| diff --git a/tests/test_prefetch_related.py b/tests/test_prefetch_related.py
new file mode 100644
--- /dev/null
+++ b/tests/test_prefetch_related.py
@@ -0,0 +1,41 @@
+from django.contrib.auth.models import Group, User
+from django.test import TestCase
+
+from rest_framework import generics, serializers
+from rest_framework.test import APIRequestFactory
+
+factory = APIRequestFactory()
+
+
+class UserSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = User
+ fields = ('id', 'username', 'email', 'groups')
+
+
+class UserUpdate(generics.UpdateAPIView):
+ queryset = User.objects.all().prefetch_related('groups')
+ serializer_class = UserSerializer
+
+
+class TestPrefetchRelatedUpdates(TestCase):
+ def setUp(self):
+ self.user = User.objects.create(username='tom', email='[email protected]')
+ self.groups = [Group.objects.create(name='a'), Group.objects.create(name='b')]
+ self.user.groups = self.groups
+ self.user.save()
+
+ def test_prefetch_related_updates(self):
+ view = UserUpdate.as_view()
+ pk = self.user.pk
+ groups_pk = self.groups[0].pk
+ request = factory.put('/', {'username': 'new', 'groups': [groups_pk]}, format='json')
+ response = view(request, pk=pk)
+ assert User.objects.get(pk=pk).groups.count() == 1
+ expected = {
+ 'id': pk,
+ 'username': 'new',
+ 'groups': [1],
+ 'email': '[email protected]'
+ }
+ assert response.data == expected
| Serializers many to many field not reflecting edits made in PUT/PATCH if prefetch_related used
If you use a viewset with a queryset using prefetch_related, any update to those prefetched many to many fields is not reflected in the response to the client, although the changes have been saved to the database.
See below code for very simple example:
``` python
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets, routers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'groups')
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all().prefetch_related('groups')
serializer_class = UserSerializer
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
```
With the above code, assume there is an existing user with 2 groups assigned:
``` json
{
"id": 1,
"username": "chris",
"email": "[email protected]",
"groups": [
1,
2
]
}
```
Submitting a PUT to /users/1/ changing groups to `[1]`, the response will still show groups as `[1, 2]`, but if you then did a GET request for /users/1/ you would see the reflected changes.
You can see this behaviour using the browseable api also.
Removing prefetch_related from the queryset restores normal behaviour and edits are again reflected in the response.
This example is very trivial, but if people are using prefetch_related to try and optimise their database queries they may encounter this issue.
| Interesting - nice work tracking that down.
Sounds like it might be pretty gnarly to deal with.
There's a [closed Django ticket](https://code.djangoproject.com/ticket/21584) that looks relevant.
> This is not a bug, I'm afraid. The results of DB queries that have already been run are never updated automatically by the Django ORM, and that is by design. ...
>
> Changing this would really require an identity mapper, and a very fundamental change to the way the Django ORM works.
Nice find @carltongibson - I guess we _may_ still want to consider if there's anything more graceful we can do here. This _may_ just fall into documentation, as we're unlikely to want to do try to automagically determine when we hit this case, but I'm open to other proposals that can be demonstrated as feasible and not overly complex.
At first guess I'd suspect it'd hard to do better than "implement `get_queryset` and check `request.method` before using `prefetch_related`"
Good call, yup. Of course this is only an issue on writable nested serializers, so something of an edge case.
Documenting this would solve a lot of potential head scratching for others. The users can avoid this problem by just re-fetching the instance from the database. In the update method in the Serializer as long as they have something like below they will be fine.
``` python
def update(self, instance, validated_attrs):
...
instance.save()
instance = self.Meta.model.objects.get(id=instance.id)
return instance
```
Indeed - tho unclear if the extra query there would defeat the point of the prefetch related or not.
True, for my case I was only using prefetch_related to speed up GET on large collections, with some nested serialization, an update on a single resource can do without it, at least in my case.
my solution was to to override BaseSerializer (We are still on 2.x.x branch):
``` python
def save(self, **kwargs):
"""
Due to DRF bug with M2M fields we refresh object state from database
directly if object is models.Model type and it contains m2m fields
See: https://github.com/tomchristie/django-rest-framework/issues/1556
"""
self.object = super(BaseSerializer, self).save(**kwargs)
if isinstance(self, serializers.ModelSerializer):
model = self.Meta.model
if model._meta.model._meta.local_many_to_many and self.object.pk:
self.object = model.objects.get(pk=self.object.pk)
return self.object
```
So it only hits database if model had m2m keys. Ideally it should be more complex check, but I was fine with this one due to aggresive caching.
See also #2704, #2727 (and the closed #3028.)
Haven't assessed if both of those should be closed as duplicates of this or not.
Thoughts/review anyone?
It looks like they're all duplicates, except #2704 which seems a slightly different issue. Your suggestion in #3028 of overriding `get_queryset` to do prefetch only on GET requests, would have worked for my case.
On reflection I _think_ that #2704 and #2727 are duplicates of each other (queryset reevaluation on list field / many=True fields) , but are not the same as this issue. (Output representation does not properly support updates if prefetch_replace has been used.)
This bug just bit us soooo hard! We've had two engineers on it for a week thinking it was a bug in the application not the endpoint.
Example solution:
```
class InspectionItemViewSet(viewsets.ModelViewSet):
queryset = InspectionItem.objects.all()
def get_queryset(self):
qs = super(InspectionItemViewSet, self).get_queryset()
if self.action == 'retrieve' or self.action == 'list':
qs = qs.prefetch_related('tags', 'failures')
if self.get_depth() >= 1:
qs = qs.prefetch_related('contractor', 'type')
return qs
```
@aidanlister :-/ Prioritizing this as a result. Right now I suppose that the sensible thing to do is just to try to highlight select_related and prefetch_related in the documentation with a suitable warning.
Of course we'll still end up having folks getting hit with this (can't expect that everyone will always have read every last bit of the documentation always, all the time), but at least if we have it documented then it's more likely to be resolved more quickly.
Yeah, given it's not a DRF issue I think a warning in the documentation is probably the best you can do. Keep up the good work Tom!
@tomchristie This is the issue we discussed on Tuesday.
@aaugustin @tomchristie — was there any breakthrough?
My take on this is -- if a request handler makes changes to an object, it should refetch if from the database before serializing it in the response. Otherwise you're always going to fail on some edge cases like changes performed by database triggers.
OK. That ties in with the conclusion we reached (I think)
Thanks!
@pySilver's [solution](https://github.com/tomchristie/django-rest-framework/issues/2442#issuecomment-71042005) worked for me in DRF 3.1, just had to switch to setting `self.instance` rather than `self.object` (per 2.x.x)
``` py
class MyModelSerializer(ModelSerializer):
def save(self, **kwargs):
"""
Due to DRF bug with M2M fields we refresh object state from database
directly if model contains m2m fields
Avoids ModelSerializers returning old results for m2m relations
when the queryset had calls to prefetch_related
See: https://github.com/tomchristie/django-rest-framework/issues/1556
https://github.com/tomchristie/django-rest-framework/issues/2442
"""
self.instance = super(MyModelSerializer, self).save(**kwargs)
model = self.Meta.model
if model._meta.model._meta.local_many_to_many and self.instance.pk:
self.instance = model.objects.get(pk=self.instance.pk)
return self.instance
```
I am facing similar issue with djangorestframework==3.3.1
http://stackoverflow.com/questions/36397357/how-to-update-values-in-instance-when-have-a-custom-update-to-update-many-to
I have three models Player, Team, and Membership, Where Player and Team have many-to-many relationship using Membership as intermediary model.
```
class Player(models.Model):
name = models.CharField(max_length=254)
rating = models.FloatField(null=True)
install_ts = models.DateTimeField(auto_now_add=True, blank=True)
update_ts = models.DateTimeField(auto_now_add=True, blank=True)
class Team(models.Model):
name = models.CharField(max_length=254)
rating = models.FloatField(null=True)
players = models.ManyToManyField(
Player,
through='Membership',
through_fields=('team', 'player'))
is_active = models.BooleanField(default=True)
install_ts = models.DateTimeField(auto_now_add=True, blank=True)
update_ts = models.DateTimeField(auto_now_add=True, blank=True)
class Membership(models.Model):
team = models.ForeignKey('Team')
player = models.ForeignKey('Player')
#date_of_joining = models.DateTimeField()
install_ts = models.DateTimeField(auto_now_add=True, blank=True)
update_ts = models.DateTimeField(auto_now_add=True, blank=True)
```
Now I was required to update this membership using django rest framework. I tried update those using Writable nested serializers by writing a custom .update() of team serializer.
```
@transaction.atomic
def update(self, instance, validated_data):
'''
Cutomize the update function for the serializer to update the
related_field values.
'''
if 'memberships' in validated_data:
instance = self._update_membership(instance, validated_data)
# remove memberships key from validated_data to use update method of
# base serializer class to update model fields
validated_data.pop('memberships', None)
return super(TeamSerializer, self).update(instance, validated_data)
def _update_membership(self, instance, validated_data):
'''
Update membership data for a team.
'''
memberships = self.initial_data.get('memberships')
if isinstance(membership, list) and len(memberships) >= 1:
# make a set of incoming membership
incoming_player_ids = set()
try:
for member in memberships:
incoming_player_ids.add(member['id'])
except:
raise serializers.ValidationError(
'id is required field in memberships objects.'
)
Membership.objects.filter(
team_id=instance.id
).delete()
# add merchant member mappings
Membership.objects.bulk_create(
[
Membership(
team_id=instance.id,
player_id=player
)
for player in incoming_player_ids
]
)
return instance
else:
raise serializers.ValidationError(
'memberships is not a list of objects'
)
```
Now this works well for updating values in database for membership table. Only problem I am facing is that I am not able to update prefetched instance in memory, which on PATCH request to this API updates values in database but API response is showing outdated data.
I have encountered the save problem.
What' the status?
Bumping the milestone on this to re-assess. Not at all clear what we can do, but needs looking at.
So clearly we need to refetch in this case, but... can we determine if a `prefetch_related` has been applied to the queryset?
Aha... https://github.com/django/django/search?utf8=%E2%9C%93&q=_prefetched_objects_cache
?
Mists of time... I recall referencing a closed Django issue on this one... It said to the effect, "User needs to be aware, and prepared to refresh themselves if using `prefetch_related`"
(Would find issue but Current status is: Ripped front off of iPad whilst fixing screen, so I can't really 😬)
@carltongibson - Yup, but we're doing this in the generic views, so the user isn't able to handle it themselves. We either need to see "don't use prefetch_related in XYZ situation" which is complicated, and users will anyways miss. Or we automatically handle the re-fetch on their behalf.
> Ripped front off of iPad whilst fixing screen
"fixing" :-/
"Replacing" then :-)
Something like
`we_need_to_do_a_refresh = hasattr(obj, '_prefetched_objects_cache')`
Is that the thought?
Yup, something along those lines.
How can I achieve this manually in the meantime? Is the right place to handle this in the serializer or in the views?
Simplest solution is _don't_ use prefetch related on `PUT`/`PATCH` - you can handle that in `get_queryset`.
Alternatively write the view manually, and have a second call to `get_object` which is used for populating the response data.
| 2016-10-11T09:51:35 |
encode/django-rest-framework | 4,554 | encode__django-rest-framework-4554 | [
"4476"
] | d0b3b6470a4f16d8256d0db5ed1be0f5a65dc0dc | diff --git a/rest_framework/relations.py b/rest_framework/relations.py
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -37,14 +37,21 @@ class Hyperlink(six.text_type):
We use this for hyperlinked URLs that may render as a named link
in some contexts, or render as a plain URL in others.
"""
- def __new__(self, url, name):
+ def __new__(self, url, obj):
ret = six.text_type.__new__(self, url)
- ret.name = name
+ ret.obj = obj
return ret
def __getnewargs__(self):
return(str(self), self.name,)
+ @property
+ def name(self):
+ # This ensures that we only called `__str__` lazily,
+ # as in some cases calling __str__ on a model instances *might*
+ # involve a database lookup.
+ return six.text_type(self.obj)
+
is_hyperlink = True
@@ -303,9 +310,6 @@ def get_url(self, obj, view_name, request, format):
kwargs = {self.lookup_url_kwarg: lookup_value}
return self.reverse(view_name, kwargs=kwargs, request=request, format=format)
- def get_name(self, obj):
- return six.text_type(obj)
-
def to_internal_value(self, data):
request = self.context.get('request', None)
try:
@@ -384,8 +388,7 @@ def to_representation(self, value):
if url is None:
return None
- name = self.get_name(value)
- return Hyperlink(url, name)
+ return Hyperlink(url, value)
class HyperlinkedIdentityField(HyperlinkedRelatedField):
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
@@ -135,7 +135,8 @@ def add_class(value, css_class):
@register.filter
def format_value(value):
if getattr(value, 'is_hyperlink', False):
- return mark_safe('<a href=%s>%s</a>' % (value, escape(value.name)))
+ name = six.text_type(value.obj)
+ return mark_safe('<a href=%s>%s</a>' % (value, escape(name)))
if value is None or isinstance(value, bool):
return mark_safe('<code>%s</code>' % {True: 'true', False: 'false', None: 'null'}[value])
elif isinstance(value, list):
| diff --git a/tests/test_lazy_hyperlinks.py b/tests/test_lazy_hyperlinks.py
new file mode 100644
--- /dev/null
+++ b/tests/test_lazy_hyperlinks.py
@@ -0,0 +1,49 @@
+from django.conf.urls import url
+from django.db import models
+from django.test import TestCase, override_settings
+
+from rest_framework import serializers
+from rest_framework.renderers import JSONRenderer
+from rest_framework.templatetags.rest_framework import format_value
+
+str_called = False
+
+
+class Example(models.Model):
+ text = models.CharField(max_length=100)
+
+ def __str__(self):
+ global str_called
+ str_called = True
+ return 'An example'
+
+
+class ExampleSerializer(serializers.HyperlinkedModelSerializer):
+ class Meta:
+ model = Example
+ fields = ('url', 'id', 'text')
+
+
+def dummy_view(request):
+ pass
+
+
+urlpatterns = [
+ url(r'^example/(?P<pk>[0-9]+)/$', dummy_view, name='example-detail'),
+]
+
+
+@override_settings(ROOT_URLCONF='tests.test_lazy_hyperlinks')
+class TestLazyHyperlinkNames(TestCase):
+ def setUp(self):
+ self.example = Example.objects.create(text='foo')
+
+ def test_lazy_hyperlink_names(self):
+ global str_called
+ context = {'request': None}
+ serializer = ExampleSerializer(self.example, context=context)
+ JSONRenderer().render(serializer.data)
+ assert not str_called
+ hyperlink_string = format_value(serializer.data['url'])
+ assert hyperlink_string == '<a href=/example/1/>An example</a>'
+ assert str_called
| `get_name()` call for hyperlinked relationships not required for JSON - should be lazy.
## 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
1. Set up a model with a related model.
2. Use that related model in the `__str__` method of the model.
3. Set up a viewset / HyperlinkedModelSerializer / etc. for the model with no nesting and no select_related() call.
## Expected behavior
The API should run one query to fetch the data to be serialized to JSON.
## Actual behavior
The API runs one query to fetch the data to be serialized. And then it runs N queries by calling get_name on each object (which calls `__str__`, which references the related model).
I suppose you could say that this is my fault for not having a 100% pure `__str__` method - but sometimes practicality beats purity. `__str__` for me is primarily supposed to make it easy for me to tell what an object is when introspecting it in the shell or some other situation. I would also expect it to be called, say, when I'm in the admin looking at a list of objects and their representations.
I would _not_ expect it to be called when I'm looking at a JSON serialized version of the model that doesn't even use the results of the method anywhere. This seems like a pretty big potential pitfall that people might not even realize they're walking into.
Potential solutions:
- make it lazy somehow?
- don't call it if the format is JSON?
| > and no select_related() call.
Isn't the danger mitigated when you would use `select_related` on your serializer?
This could be another motivation to get https://github.com/tomchristie/django-rest-framework/issues/1977 out.
Good point, yup, we return `Hyperlink(url, name)`, rather than the raw url, so as you say a `__str__` on the model that requires a lookup will be a problem.
We should make the call lazy.
Retitled to better match the intent.
| 2016-10-11T11:05:40 |
encode/django-rest-framework | 4,564 | encode__django-rest-framework-4564 | [
"4562"
] | 4c9b14bd972f1c74fc400297be5ecd1a1e0317f0 | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -507,6 +507,11 @@ def data(self):
@property
def errors(self):
ret = super(Serializer, self).errors
+ if isinstance(ret, list) and len(ret) == 1 and ret[0].code == 'null':
+ # Edge case. Provide a more descriptive error than
+ # "this field may not be null", when no data is passed.
+ detail = ErrorDetail('No data provided', code='null')
+ ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]}
return ReturnDict(ret, serializer=self)
@@ -700,6 +705,11 @@ def data(self):
@property
def errors(self):
ret = super(ListSerializer, self).errors
+ if isinstance(ret, list) and len(ret) == 1 and ret[0].code == 'null':
+ # Edge case. Provide a more descriptive error than
+ # "this field may not be null", when no data is passed.
+ detail = ErrorDetail('No data provided', code='null')
+ ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]}
if isinstance(ret, dict):
return ReturnDict(ret, serializer=self)
return ReturnList(ret, serializer=self)
| diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -62,6 +62,12 @@ def create(validated_data):
with pytest.raises(AssertionError):
serializer.save()
+ def test_validate_none_data(self):
+ data = None
+ serializer = self.Serializer(data=data)
+ assert not serializer.is_valid()
+ assert serializer.errors == {'non_field_errors': ['No data provided']}
+
class TestValidateMethod:
def test_non_field_error_validate_method(self):
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
@@ -41,6 +41,12 @@ def test_nested_serialize_empty(self):
serializer = self.Serializer()
assert serializer.data == expected_data
+ def test_nested_serialize_no_data(self):
+ data = None
+ serializer = self.Serializer(data=data)
+ assert not serializer.is_valid()
+ assert serializer.errors == {'non_field_errors': ['No data provided']}
+
class TestNotRequiredNestedSerializer:
def setup(self):
| WIP demonstrating the issue in 4561
## Description
Demonstrates #4561
| 2016-10-12T09:38:47 |
|
encode/django-rest-framework | 4,565 | encode__django-rest-framework-4565 | [
"4135"
] | b4199704316bd2d67281cbc3cf946eab9bded407 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1594,9 +1594,21 @@ def __init__(self, *args, **kwargs):
self.binary = kwargs.pop('binary', False)
super(JSONField, self).__init__(*args, **kwargs)
+ def get_value(self, dictionary):
+ if html.is_html_input(dictionary) and self.field_name in dictionary:
+ # When HTML form input is used, mark up the input
+ # as being a JSON string, rather than a JSON primative.
+ class JSONString(six.text_type):
+ def __new__(self, value):
+ ret = six.text_type.__new__(self, value)
+ ret.is_json_string = True
+ return ret
+ return JSONString(dictionary[self.field_name])
+ return dictionary.get(self.field_name, empty)
+
def to_internal_value(self, data):
try:
- if self.binary:
+ if self.binary or getattr(data, 'is_json_string', False):
if isinstance(data, six.binary_type):
data = data.decode('utf-8')
return json.loads(data)
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -1756,6 +1756,19 @@ class TestJSONField(FieldValues):
]
field = serializers.JSONField()
+ def test_html_input_as_json_string(self):
+ """
+ HTML inputs should be treated as a serialized JSON string.
+ """
+ class TestSerializer(serializers.Serializer):
+ config = serializers.JSONField()
+
+ data = QueryDict(mutable=True)
+ data.update({'config': '{"a":1}'})
+ serializer = TestSerializer(data=data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'config': {"a": 1}}
+
class TestBinaryJSONField(FieldValues):
"""
| JSONField webform-input always parsed as string
Hello Tom - we spoke on IRC yesterday, I apologize for the initial confusion since I hadn't quite figured out how this was happening at the time and I had some custom extensions which I needed to disable to be sure that this was actually general to rest-framework.
## Checklist
- [X] I have verified that that issue exists against the `master` branch of Django REST framework.
9b56dda91850a07cfaecbe972e0f586434b965c3@master
- [X] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
https://github.com/tomchristie/django-rest-framework/issues/3884
https://github.com/tomchristie/django-rest-framework/issues/3884#issuecomment-216495045:
> Closing due to lack of strictly delimited, actionable issue.
Opening with substantially more detail.
- [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.)
## Current Behaviour (web-form input - incorrect)

Result (note that json_field is a string literal):
``` python
In [47]: TestModel.objects.all()[0].attributes
Out[47]:
{'_state': <django.db.models.base.ModelState at 0x7f90a85b9390>,
'account_id': 38,
'created_at': datetime.datetime(2016, 5, 21, 4, 1, 17, 543922, tzinfo=<UTC>),
'id': 71,
'json_field': '{"a": true} ',
'updated_at': datetime.datetime(2016, 5, 21, 4, 1, 17, 545692, tzinfo=<UTC>)}
```
## Current Behaviour (curl -X POST - correct)
```
curl 'http://127.0.0.1:8000/api/test_models/' -H 'Pragma: no-cache' -H 'Cookie: sessionid=cw85hy8pelhvhyb4z3xtngfapyeokf1v' -H "Content-Type: application/json" -X POST -d '{"json_field":{"a":true}}'
```
Result (note that json_field is the parsed object of the JSON submitted via POST):
``` python
In [48]: TestModel.objects.all()[0].attributes
Out[48]:
{'_state': <django.db.models.base.ModelState at 0x7f90a8855630>,
'account_id': 35,
'created_at': datetime.datetime(2016, 5, 21, 4, 6, 10, 65872, tzinfo=<UTC>),
'id': 73,
'json_field': {'a': True},
'updated_at': datetime.datetime(2016, 5, 21, 4, 6, 10, 67324, tzinfo=<UTC>)}
```
## WebForm-Input (Here is what a POST using the webform-input looks like)
Request Headers:
```
POST /api/test_models/ HTTP/1.1
Host: 127.0.0.1:8000
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: http://127.0.0.1:8000/api/test_models/
Connection: keep-alive
```
Request Payload:
```
Content-Type: multipart/form-data; boundary=---------------------------991790026648295083338748743
Content-Length: 339
-----------------------------991790026648295083338748743
Content-Disposition: form-data; name="csrfmiddlewaretoken"
wNJTnxROcxtm9nXmK6sv0sN4MhY7PfC2
-----------------------------991790026648295083338748743
Content-Disposition: form-data; name="json_field"
{"a": true}
-----------------------------991790026648295083338748743--
```
It seems that any `Content-Disposition: form-data` will be parsed as a string input. Technically it should be possible\* to tag a portion of a `multipart/form-data` with `Content-Type` e.g. `Content-Type: application/json` or `Content-Type: text/json` but even if we do add it Django seems to ignore this.
[0] http://www.ietf.org/rfc/rfc2388.txt
I think the best solution would be to modify `get_value` to check `html.is_html_input(dictionary)` and json.loads the string if it is. Therefore non-quoted inputs would be parsed as JSON objects e.g.

One could still express a JSON string literal e.g.

| > Technically it should be possible\* to tag a portion of a multipart/form-data with Content-Type
That's not possible. Form data only supports string and file upload primitives.
This behaviour is simply a limitation of what HTML forms do and don't support.
You'll need to use the Raw data input for endpoints that contain JSON or other nested/complex datatypes.
> That's not possible. Form data only supports string and file upload primitives.
according to the RFC
> As with all multipart MIME types, each part has an optional "Content-Type", which defaults to text/plain.
That implementations e. g. Django ignore it seems to be the case, but it's not obvious to me that this is entirely correct or at least that parsing other content-types would be 'less correct' - otherwise what's the sense of the RFC mentioning optional content-types?
In django-rest-framework case the current behaviour makes web-input for JSON 100% non-usable (i don't think any one is putting jsonb into their database schema for string literals). If you are against parsing the JSON provided in webform-input submitting the webform entirely as a seralized JSON would be preferable (although it may be a rather large change).
Otherwise it would be nice if at least the limitations of the current behavior were documented - since it's somewhat misleading and not very obvious.
Thanks for django-rest-framework, it's an awesome tool.
Some food for thought here : certainly agree that itd be nice to either improve the behaviour or the documentation, but it's not exactly clear how to do this best.
HTML forms are a limitation here, not just for JSON field but for any nested structures, but I'll reopen this for some consideration, even if that only ends up being documentation or similar.
(Specilative: we could mark fields that don't support plain HTML form input, and ensure that the browsable API renders some appropriate messaging)
> It seems that any Content-Disposition: form-data will be parsed as a string input. Technically it should be possible\* to tag a portion of a multipart/form-data with Content-Type e.g. Content-Type: application/json or Content-Type: text/json but even if we do add it Django seems to ignore this.
I was going to say I disagree here and would blame browsers for not supporting it.
However, things are starting to rage in my brain and pandora box is now opened.
Do we have a test case for a multipart/form-data with say JSON content and files linked ? I'm sorry, I just read http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/ which does something similar. DRF parser would not be able to cope with that but I've no idea how Django would do.
> which does something similar.
That example is just sending the JSON portion as `text/plain`, as far as I can see.
I've never seen any multipart implementations that handle primitives other than text and file uploads, and the content-type if set ought to indicate the media type of the uploaded file, as per here...
> If the contents of a file are returned via filling out a form, then the file input is identified as the appropriate media type, if known, or "application/octet-stream".
Reasonably strongly of the opinion that treating multipart as supporting anything other than text and file uploads isn't something we want to do.
Just out of curiosity, can't the framework itself handle the serialization. For eg., If serializer field is a JSONField and the json data passed is a string (from Browsable API), framework can convert it to json by itself when serialization is done in the background.
I am just a beginner, so if this idea seems vague, please ignore it.
Milestoning for review.
| 2016-10-12T12:54:56 |
encode/django-rest-framework | 4,566 | encode__django-rest-framework-4566 | [
"3647"
] | 26e51ecd6c0805770615e768e46ecc6716872670 | diff --git a/rest_framework/request.py b/rest_framework/request.py
--- a/rest_framework/request.py
+++ b/rest_framework/request.py
@@ -299,7 +299,10 @@ def _parse(self):
stream = None
if stream is None or media_type is None:
- empty_data = QueryDict('', encoding=self._request._encoding)
+ if media_type and not is_form_media_type(media_type):
+ empty_data = QueryDict('', encoding=self._request._encoding)
+ else:
+ empty_data = {}
empty_files = MultiValueDict()
return (empty_data, empty_files)
| diff --git a/tests/test_testing.py b/tests/test_testing.py
--- a/tests/test_testing.py
+++ b/tests/test_testing.py
@@ -8,6 +8,7 @@
from django.shortcuts import redirect
from django.test import TestCase, override_settings
+from rest_framework import fields, serializers
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.test import (
@@ -37,10 +38,22 @@ def redirect_view(request):
return redirect('/view/')
+class BasicSerializer(serializers.Serializer):
+ flag = fields.BooleanField(default=lambda: True)
+
+
+@api_view(['POST'])
+def post_view(request):
+ serializer = BasicSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ return Response(serializer.validated_data)
+
+
urlpatterns = [
url(r'^view/$', view),
url(r'^session-view/$', session_view),
url(r'^redirect-view/$', redirect_view),
+ url(r'^post-view/$', post_view)
]
@@ -181,6 +194,15 @@ def test_invalid_multipart_data(self):
path='/view/', data={'valid': 123, 'invalid': {'a': 123}}
)
+ def test_empty_post_uses_default_boolean_value(self):
+ response = self.client.post(
+ '/post-view/',
+ data=None,
+ content_type='application/json'
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.data, {"flag": True})
+
class TestAPIRequestFactory(TestCase):
def test_csrf_exempt_by_default(self):
| Empty requests treated differently from '{}'
This took me quite a while to work out :)
I have a Serializer with HyperlinkedRelatedField(many=True) on it. I had some API tests that would pass in an empty dict:
```
self.client.post(list_url, {}, format='json')
```
The response yielded the expected 401, stating that the given field was required. So far, so good.
Much to my surprise, if I sent an empty POST request to the same url on my production system (or Django's built-in development server), the resource was created succesfully, with an empty list for that field.
After quite a bit of digging, I learned that an empty request invariably means that request.data is a QueryDict, rather than a simple, empty dict. During validation, many Field implementations call html.is_html_dictionary() on request.data. is_html_dictionary simply checks for a .getlist() method. Incidentally, this getlist() method is the culprit. When called, it will always return a list, even if the given key is not found at all, in which case it yields an empty list.
I feel that the result for an empty request and a request that passes in an empty json object should yield the exact same results.
| Actually HTML forms and JSON requests differs a lot because there's no way we can have as much details with the forms as we have with JSON.
Will keep this open, need to think if we can improve things here.
I appreciate that, but I'm not using HTML forms anywhere. I'm even explicitly passing "application/json" as my content type.
It's not very elegant, but this fixes it for me and doesn't break any tests:
```
diff --git a/rest_framework/parsers.py b/rest_framework/parsers.py
index 2dc808f..d99fef9 100644
--- a/rest_framework/parsers.py
+++ b/rest_framework/parsers.py
@@ -62,6 +62,9 @@ class JSONParser(BaseParser):
parser_context = parser_context or {}
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
+ if not stream:
+ return {}
+
try:
data = stream.read().decode(encoding)
return json.loads(data)
diff --git a/rest_framework/request.py b/rest_framework/request.py
index 846cadc..785abd7 100644
--- a/rest_framework/request.py
+++ b/rest_framework/request.py
@@ -275,7 +275,7 @@ class Request(object):
stream = self.stream
media_type = self.content_type
- if stream is None or media_type is None:
+ if stream is None and not media_type:
empty_data = QueryDict('', encoding=self._request._encoding)
empty_files = MultiValueDict()
return (empty_data, empty_files)
```
@sorenh I think a failing test case would help more. Your workaround may not work with nested serializers for example.
I'm working on a good test case right now. I'll have it ready tomorrow, probably.
Thanks, this will help a lot !
I don't know.. I have test that fails, but I'm not sure if it's too specific:
https://github.com/sorenh/django-rest-framework/commit/d9a41859208e5dfa3860704b764f083e398182e0
Hi,
I have a problem that could maybe similar (if not, I can create new issue).
When a send a empty `PUT`, `json` or `form-url-encoded`, my `request.data` (`QueryDict`) is immutable.
If I just add a single attribut in my `json`, my `request.data` (`QueryDict`) is mutable.
Any idea? Is it related?
Thank you guys! :smiley:
Edit: `djangorestframework==3.2.4`
| 2016-10-12T14:14:27 |
encode/django-rest-framework | 4,568 | encode__django-rest-framework-4568 | [
"4312"
] | 2519ce9128e4e870e28d77c0f388e3d2deb130c7 | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -744,8 +744,8 @@ def raise_errors_on_nested_writes(method_name, serializer, validated_data):
# profile = ProfileSerializer()
assert not any(
isinstance(field, BaseSerializer) and
- (key in validated_data) and
- isinstance(validated_data[key], (list, dict))
+ (field.source in validated_data) and
+ isinstance(validated_data[field.source], (list, dict))
for key, field in serializer.fields.items()
), (
'The `.{method_name}()` method does not support writable nested '
| Validation error on raise_errors_on_nested_writes?
I have problems with nested serializers, the idea is to read with nested serializer and write with a primaryKeyRelated, but I have a nested write alert with my example:
### Raise error
```
class WorkerSerializer(serializers.ModelSerializer):
roles = data_serializers.RoleSerializer(many=True, read_only=True)
roles_ids = serializers.PrimaryKeyRelatedField(
allow_empty=False, many=True, queryset=data_models.Role.objects.all(),
write_only=True, source="roles"
)
```
### This works
```
class WorkerSerializer(serializers.ModelSerializer):
roles_data = data_serializers.RoleSerializer(many=True, read_only=True, source="roles")
roles = serializers.PrimaryKeyRelatedField(
allow_empty=False, many=True, queryset=data_models.Role.objects.all(),
write_only=True
)
```
This doesn't look a big problem, but for me it's huge to change a big api implementation, this behavior repeats a lot and I believe the solution it's quite simple.
I find in raise_errors_on_nested_writes function this validation:
```
assert not any(
isinstance(field, BaseSerializer) and
(key in validated_data) and
isinstance(validated_data[key], (list, dict))
for key, field in serializer.fields.items()
), (
'The `.{method_name}()` method does not support writable nested '
'fields by default.\nWrite an explicit `.{method_name}()` method for '
'serializer `{module}.{class_name}`, or set `read_only=True` on '
'nested serializer fields.'.format(
method_name=method_name,
module=serializer.__class__.__module__,
class_name=serializer.__class__.__name__
)
)
```
Adding a read_only check fix my problem
```
assert not any(
not field.read_only and
isinstance(field, BaseSerializer) and
(key in validated_data) and
isinstance(validated_data[key], (list, dict))
for key, field in serializer.fields.items()
), (
'The `.{method_name}()` method does not support writable nested '
'fields by default.\nWrite an explicit `.{method_name}()` method for '
'serializer `{module}.{class_name}`, or set `read_only=True` on '
'nested serializer fields.'.format(
method_name=method_name,
module=serializer.__class__.__module__,
class_name=serializer.__class__.__name__
)
)
```
My first issue on github, so I hope it's ok.
Thanks
| Seems fair - bit of an odd edge case the way it's been used, but yup see the issue.
Might be that we want to do something along the lines of testing `field.source` instead of `key` in `validated_data`, wasn't expecting to have to test `read_only` as we _already_ check if the data exists or not.
Started to look into resolving this, but trying to create the test case started taking slightly longer than expected.
If anyone is able to submit a failing test case, or provide the _simplest possible_ example of how to replicate this would go a long way towards helping get this case resolved.
| 2016-10-12T15:39:15 |
|
encode/django-rest-framework | 4,571 | encode__django-rest-framework-4571 | [
"3852"
] | 88c6c380c54d163d140485c8b53c923b7ec539e3 | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -1167,7 +1167,7 @@ def build_relational_field(self, field_name, relation_info):
field_kwargs = get_relation_kwargs(field_name, relation_info)
to_field = field_kwargs.pop('to_field', None)
- if to_field and not relation_info.related_model._meta.get_field(to_field).primary_key:
+ if to_field and not relation_info.reverse and not relation_info.related_model._meta.get_field(to_field).primary_key:
field_kwargs['slug_field'] = to_field
field_class = self.serializer_related_to_field
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
@@ -238,7 +238,7 @@ def get_relation_kwargs(field_name, relation_info):
"""
Creates a default instance of a flat relational field.
"""
- model_field, related_model, to_many, to_field, has_through_model = relation_info
+ model_field, related_model, to_many, to_field, has_through_model, reverse = relation_info
kwargs = {
'queryset': related_model._default_manager,
'view_name': get_detail_view_name(related_model)
diff --git a/rest_framework/utils/model_meta.py b/rest_framework/utils/model_meta.py
--- a/rest_framework/utils/model_meta.py
+++ b/rest_framework/utils/model_meta.py
@@ -23,7 +23,8 @@
'related_model',
'to_many',
'to_field',
- 'has_through_model'
+ 'has_through_model',
+ 'reverse'
])
@@ -81,7 +82,8 @@ def _get_forward_relationships(opts):
related_model=get_related_model(field),
to_many=False,
to_field=_get_to_field(field),
- has_through_model=False
+ has_through_model=False,
+ reverse=False
)
# Deal with forward many-to-many relationships.
@@ -94,7 +96,8 @@ def _get_forward_relationships(opts):
to_field=None,
has_through_model=(
not get_remote_field(field).through._meta.auto_created
- )
+ ),
+ reverse=False
)
return forward_relations
@@ -118,7 +121,8 @@ def _get_reverse_relationships(opts):
related_model=related,
to_many=get_remote_field(relation.field).multiple,
to_field=_get_to_field(relation.field),
- has_through_model=False
+ has_through_model=False,
+ reverse=True
)
# Deal with reverse many-to-many relationships.
@@ -135,7 +139,8 @@ def _get_reverse_relationships(opts):
has_through_model=(
(getattr(get_remote_field(relation.field), 'through', None) is not None) and
not get_remote_field(relation.field).through._meta.auto_created
- )
+ ),
+ reverse=True
)
return reverse_relations
| 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,15 @@ class ChoicesModel(models.Model):
choices_field_with_nonstandard_args = models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES, verbose_name='A label')
+class Issue3674ParentModel(models.Model):
+ title = models.CharField(max_length=64)
+
+
+class Issue3674ChildModel(models.Model):
+ parent = models.ForeignKey(Issue3674ParentModel, related_name='children')
+ value = models.CharField(primary_key=True, max_length=64)
+
+
class TestModelSerializer(TestCase):
def test_create_method(self):
class TestSerializer(serializers.ModelSerializer):
@@ -996,3 +1005,62 @@ class Meta:
fields = TestSerializer().fields
self.assertFalse(fields['field_1'].required)
self.assertTrue(fields['field_2'].required)
+
+
+class Issue3674Test(TestCase):
+ def test_nonPK_foreignkey_model_serializer(self):
+ class TestParentModel(models.Model):
+ title = models.CharField(max_length=64)
+
+ class TestChildModel(models.Model):
+ parent = models.ForeignKey(TestParentModel, related_name='children')
+ value = models.CharField(primary_key=True, max_length=64)
+
+ class TestChildModelSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = TestChildModel
+ fields = ('value', 'parent')
+
+ class TestParentModelSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = TestParentModel
+ fields = ('id', 'title', 'children')
+
+ parent_expected = dedent("""
+ TestParentModelSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ title = CharField(max_length=64)
+ children = PrimaryKeyRelatedField(many=True, queryset=TestChildModel.objects.all())
+ """)
+ self.assertEqual(unicode_repr(TestParentModelSerializer()), parent_expected)
+
+ child_expected = dedent("""
+ TestChildModelSerializer():
+ value = CharField(max_length=64, validators=[<UniqueValidator(queryset=TestChildModel.objects.all())>])
+ parent = PrimaryKeyRelatedField(queryset=TestParentModel.objects.all())
+ """)
+ self.assertEqual(unicode_repr(TestChildModelSerializer()), child_expected)
+
+ def test_nonID_PK_foreignkey_model_serializer(self):
+
+ class TestChildModelSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Issue3674ChildModel
+ fields = ('value', 'parent')
+
+ class TestParentModelSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Issue3674ParentModel
+ fields = ('id', 'title', 'children')
+
+ parent = Issue3674ParentModel.objects.create(title='abc')
+ child = Issue3674ChildModel.objects.create(value='def', parent=parent)
+
+ parent_serializer = TestParentModelSerializer(parent)
+ child_serializer = TestChildModelSerializer(child)
+
+ parent_expected = {'children': ['def'], 'id': 1, 'title': 'abc'}
+ self.assertEqual(parent_serializer.data, parent_expected)
+
+ child_expected = {'parent': 1, 'value': 'def'}
+ self.assertEqual(child_serializer.data, child_expected)
| Fixed #3674 -- Refactored _get_reverse_relationships() to use correct to_field.
overtakes #3696 (thanks to @benred42) !
| geez you're on fire :fire: :smile:
@jpadilla trying to get things moving. ATM Travis is on fire
And there we are.
LGTM :+1:
:+1: as well; I was the original reporter of this issue and can verify that it works for me. :)
Closes #3674.
Anything I can do to help with this one? :)
We need to answer the questions asked and merge trunk back in.
@xordoquy I attempted to answer the question re: `[0][1]` :)
| 2016-10-13T11:03:11 |
encode/django-rest-framework | 4,593 | encode__django-rest-framework-4593 | [
"3371"
] | 3f6004c5a9edab6336e93da85ce3849dee0b1311 | diff --git a/rest_framework/filters.py b/rest_framework/filters.py
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -5,9 +5,9 @@
from __future__ import unicode_literals
import operator
+import warnings
from functools import reduce
-from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.db.models.constants import LOOKUP_SEP
@@ -16,50 +16,10 @@
from django.utils.translation import ugettext_lazy as _
from rest_framework.compat import (
- coreapi, crispy_forms, distinct, django_filters, guardian, template_render
+ coreapi, distinct, django_filters, guardian, template_render
)
from rest_framework.settings import api_settings
-if 'crispy_forms' in settings.INSTALLED_APPS and crispy_forms and django_filters:
- # If django-crispy-forms is installed, use it to get a bootstrap3 rendering
- # of the DjangoFilterBackend controls when displayed as HTML.
- from crispy_forms.helper import FormHelper
- from crispy_forms.layout import Layout, Submit
-
- class FilterSet(django_filters.FilterSet):
- def __init__(self, *args, **kwargs):
- super(FilterSet, self).__init__(*args, **kwargs)
- for field in self.form.fields.values():
- field.help_text = None
-
- layout_components = list(self.form.fields.keys()) + [
- Submit('', _('Submit'), css_class='btn-default'),
- ]
-
- helper = FormHelper()
- helper.form_method = 'GET'
- helper.template_pack = 'bootstrap3'
- helper.layout = Layout(*layout_components)
-
- self.form.helper = helper
-
- filter_template = 'rest_framework/filters/django_filter_crispyforms.html'
-
-elif django_filters:
- # If django-crispy-forms is not installed, use the standard
- # 'form.as_p' rendering when DjangoFilterBackend is displayed as HTML.
- class FilterSet(django_filters.FilterSet):
- def __init__(self, *args, **kwargs):
- super(FilterSet, self).__init__(*args, **kwargs)
- for field in self.form.fields.values():
- field.help_text = None
-
- filter_template = 'rest_framework/filters/django_filter.html'
-
-else:
- FilterSet = None
- filter_template = None
-
class BaseFilterBackend(object):
"""
@@ -77,78 +37,34 @@ def get_schema_fields(self, view):
return []
+class FilterSet(object):
+ def __new__(cls, *args, **kwargs):
+ warnings.warn(
+ "The built in 'rest_framework.filters.FilterSet' is pending deprecation. "
+ "You should use 'django_filters.rest_framework.FilterSet' instead.",
+ PendingDeprecationWarning
+ )
+ from django_filters.rest_framework import FilterSet
+ return FilterSet(*args, **kwargs)
+
+
class DjangoFilterBackend(BaseFilterBackend):
"""
A filter backend that uses django-filter.
"""
- default_filter_set = FilterSet
- template = filter_template
-
- def __init__(self):
+ def __new__(cls, *args, **kwargs):
assert django_filters, 'Using DjangoFilterBackend, but django-filter is not installed'
+ assert django_filters.VERSION >= (0, 15, 3), 'django-filter 0.15.3 and above is required'
- def get_filter_class(self, view, queryset=None):
- """
- Return the django-filters `FilterSet` used to filter the queryset.
- """
- filter_class = getattr(view, 'filter_class', None)
- filter_fields = getattr(view, 'filter_fields', None)
-
- if filter_class:
- filter_model = filter_class.Meta.model
-
- assert issubclass(queryset.model, filter_model), \
- 'FilterSet model %s does not match queryset model %s' % \
- (filter_model, queryset.model)
-
- return filter_class
-
- if filter_fields:
- class AutoFilterSet(self.default_filter_set):
- class Meta:
- model = queryset.model
- fields = filter_fields
+ warnings.warn(
+ "The built in 'rest_framework.filters.DjangoFilterBackend' is pending deprecation. "
+ "You should use 'django_filters.rest_framework.DjangoFilterBackend' instead.",
+ PendingDeprecationWarning
+ )
- return AutoFilterSet
+ from django_filters.rest_framework import DjangoFilterBackend
- return None
-
- def filter_queryset(self, request, queryset, view):
- filter_class = self.get_filter_class(view, queryset)
-
- if filter_class:
- return filter_class(request.query_params, queryset=queryset).qs
-
- return queryset
-
- def to_html(self, request, queryset, view):
- filter_class = self.get_filter_class(view, queryset)
- if not filter_class:
- return None
- filter_instance = filter_class(request.query_params, queryset=queryset)
- context = {
- 'filter': filter_instance
- }
- template = loader.get_template(self.template)
- return template_render(template, context)
-
- def get_schema_fields(self, view):
- assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`'
- filter_class = getattr(view, 'filter_class', None)
- if filter_class:
- return [
- coreapi.Field(name=field_name, required=False, location='query')
- for field_name in filter_class().filters.keys()
- ]
-
- filter_fields = getattr(view, 'filter_fields', None)
- if filter_fields:
- return [
- coreapi.Field(name=field_name, required=False, location='query')
- for field_name in filter_fields
- ]
-
- return []
+ return DjangoFilterBackend(*args, **kwargs)
class SearchFilter(BaseFilterBackend):
| diff --git a/tests/test_filters.py b/tests/test_filters.py
--- a/tests/test_filters.py
+++ b/tests/test_filters.py
@@ -2,6 +2,7 @@
import datetime
import unittest
+import warnings
from decimal import Decimal
from django.conf.urls import url
@@ -134,6 +135,39 @@ class IntegrationTestFiltering(CommonFilteringTestCase):
Integration tests for filtered list views.
"""
+ @unittest.skipUnless(django_filters, 'django-filter not installed')
+ def test_backend_deprecation(self):
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+
+ view = FilterFieldsRootView.as_view()
+ request = factory.get('/')
+ response = view(request).render()
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.data, self.data)
+
+ self.assertTrue(issubclass(w[-1].category, PendingDeprecationWarning))
+ self.assertIn("'rest_framework.filters.DjangoFilterBackend' is pending deprecation.", str(w[-1].message))
+
+ @unittest.skipUnless(django_filters, 'django-filter not installed')
+ def test_no_df_deprecation(self):
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+
+ import django_filters.rest_framework
+
+ class DFFilterFieldsRootView(FilterFieldsRootView):
+ filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
+
+ view = DFFilterFieldsRootView.as_view()
+ request = factory.get('/')
+ response = view(request).render()
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.data, self.data)
+ self.assertEqual(len(w), 0)
+
@unittest.skipUnless(django_filters, 'django-filter not installed')
def test_get_filtered_fields_root_view(self):
"""
| Extract Django-Filter related code
As per discussion on #3315, it would be nice to pull the Django Filter related code out of DRF.
I'm happy to pull this into Django Filter itself. There's already an [issue there to add a more DRF friendly base FilterSet class](https://github.com/alex/django-filter/issues/275). It makes sense to combine the work into one.
Moving the code is simple enough — it should require a no more than a change of import for end users. Other queries: test coverage boundaries; docs.
| We'll also need to follow the deprecation path on DRF about this.
@xordoquy — Ah, yes. Good point.
In the past for cases where we can simply say "'x' is now an external package, make sure to install it." we've gone ahead and moved out of core without any further work. We could either:
- Just force it as an external package.
- Keep eg. `rest_framework.filters.DjangoFilterBackend` as a synonym during the deprecation process. (but still force the external install, rather than keeping the code locally)
- Keep the code local (duplicated) during the deprecation process.
Since `DjangoFilterBackend` relies on Django-Filter (already) there's no harm removing the code — leaving the alias, as you say.
Don't forget to use @jpadilla's excellent cookiecutter template when you take this on. :)
http://www.django-rest-framework.org/topics/third-party-resources/#how-to-create-a-third-party-package
I've still got an open task to remove the potential 'crispy-forms' dependency for the "filters in the browsable API" not sure best way to tackle that.
> ... excellent cookiecutter template ...
Just for my sanity, I'm thinking of putting this straight into Django Filter.
```
from django_filters.rest_framework import FilterBackend
```
... or such
> ... the potential 'crispy-forms' dependency ...
Yeah. I saw that. I'm in two-minds there.
At what point do we say, "Here's the hook and a simple default implementation — anything else you need is up to you"? i.e. Why not keep the dependency there — for the sake of working on (cough) _better things_?
> Just for my sanity, I'm thinking of putting this straight into Django Filter.
Great plan!
> Why not keep the dependency there — for the sake of working on (cough) better things?
Think I'm happy either way - with crispy or without.
I'm tempted by the 3rd option - Keep the code local (duplicated) during the deprecation process.
I really believe DRF will benefit having a strong deprecation policy en particular due to its popularity and a relatively fast release cycle.
@carltongibson BTW, the link to the issue in this description is broken (404 here).
Yeah. OK fine. (Although the API and behaviour would remain unchanged even if we move the code — and it's the API and behaviour, not the implementation, that's subject to the deprecation policy right?)
I will work first on the DF side of it (this week). I'll open a PR moving the Filter Backend into DF.
Once the target end is in place I'll come back and we can settle how to handle it the DRF end.
(@xordoquy Ta. Fixed.)
> it's the API and behaviour, not the implementation, that's subject to the deprecation policy right?
That's correct, but you may change a lot by requiring an update to an extra dependency in particular the valid Django version and co.
Sure. Lets review when we come to it.
Quick update: This is on my radar for over the holiday period. If that's not quick enough, PRs on Django Filter welcome :-)
> I really believe DRF will benefit having a strong deprecation policy en particular due to its popularity and a relatively fast release cycle.
I think I agree here. Everyone I speak to who's using Django is using DRF.
@tomchristie If you want something Django-Filter related. You could take this on. I'm happy to have this and maintain it in a `django_filters.rest_framework` module of the main Django-Filter repo — I just haven't got there.
Equally, there's no urgency to move it, so no rush. (Some of the other things seem more exciting.)
I think this would be valid, yup.
Probably not top of my list, at the moment, tho _possible_ that it'd be worth doing for the 3.4.0 release.
Right. Only about a year late but, progress.
Off the back of excellent effort from @rpkilby, we'll have the migrated `DjangoFilterBackend` code in Django Filter via https://github.com/carltongibson/django-filter/issues/476
This will go in this week. It'll be on PyPI shortly afterwards.
What will be missing there is decent docs: the PR has been sat for _ages™_ waiting and I'd rather merge it and add them after than let the updated PR get stale with little conflicts again. (There are only a couple more points until DF hits Inbox Zero, and it's even going to have a 1.0 at last; the docs is part of that, so I'm happy they'll actually happen, at some point 🙂 )
I'm pinging to restart discussion on a roadmap and tasks — including documentation — for dropping the code from DRF.
Very nice 👍😎
| 2016-10-20T09:39:06 |
encode/django-rest-framework | 4,609 | encode__django-rest-framework-4609 | [
"4606"
] | 0b346e94b1ed3016e79dd39be3ee48691cecb035 | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -507,7 +507,7 @@ def data(self):
@property
def errors(self):
ret = super(Serializer, self).errors
- if isinstance(ret, list) and len(ret) == 1 and ret[0].code == 'null':
+ if isinstance(ret, list) and len(ret) == 1 and getattr(ret[0], 'code', None) == 'null':
# Edge case. Provide a more descriptive error than
# "this field may not be null", when no data is passed.
detail = ErrorDetail('No data provided', code='null')
@@ -705,7 +705,7 @@ def data(self):
@property
def errors(self):
ret = super(ListSerializer, self).errors
- if isinstance(ret, list) and len(ret) == 1 and ret[0].code == 'null':
+ if isinstance(ret, list) and len(ret) == 1 and getattr(ret[0], 'code', None) == 'null':
# Edge case. Provide a more descriptive error than
# "this field may not be null", when no data is passed.
detail = ErrorDetail('No data provided', code='null')
| diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -357,3 +357,16 @@ def test_validation_success(self):
assert serializer.is_valid()
assert serializer.validated_data == {'name': '2'}
assert serializer.errors == {}
+
+
+class Test4606Regression:
+ def setup(self):
+ class ExampleSerializer(serializers.Serializer):
+ name = serializers.CharField(required=True)
+ choices = serializers.CharField(required=True)
+ self.Serializer = ExampleSerializer
+
+ def test_4606_regression(self):
+ serializer = self.Serializer(data=[{"name": "liz"}], many=True)
+ with pytest.raises(serializers.ValidationError):
+ serializer.is_valid(raise_exception=True)
| List serializer bug with only one object passed
There is a bug when validating only one object with a list serializer with raise_exception flag set as True.
It worked just fine in 3.4.7.
## Steps to reproduce
Here is the class that will cause the issue
```
class TheSerializer(serializers.Serializer):
name = serializers.CharField(required=True)
choices = serializers.CharField(required=True)
```
Then run
```
serializer = TheSerializer(data=[{"name": "hhj"}], many=True)
serializer.is_valid(raise_exception=True)
```
## Expected behavior
```
if self._errors and raise_exception:
> raise ValidationError(self.errors)
E rest_framework.exceptions.ValidationError: [{'choices': ['This field is required.']}]
```
## Actual behavior
```
self = TheSerializer(data=[{'name': 'hhj'}], many=True):
name = CharField(required=True)
choices = CharField(required=True)
@property
def errors(self):
ret = super(ListSerializer, self).errors
> if isinstance(ret, list) and len(ret) == 1 and ret[0].code == 'null':
E AttributeError: 'dict' object has no attribute 'code'
```
| 2016-10-21T14:21:07 |
|
encode/django-rest-framework | 4,611 | encode__django-rest-framework-4611 | [
"4605"
] | d647d37a99df3673000f17f7d565a8dab0770805 | diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -1,4 +1,3 @@
-import os
import re
from collections import OrderedDict
from importlib import import_module
@@ -37,6 +36,18 @@
})
+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
@@ -292,7 +303,7 @@ def determine_path_prefix(self, paths):
# one URL that doesn't have a path prefix.
return '/'
prefixes.append('/' + prefix + '/')
- return os.path.commonprefix(prefixes)
+ return common_path(prefixes)
def create_view(self, callback, method, request=None):
"""
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -335,3 +335,14 @@ def test_schema_for_regular_views(self):
}
)
self.assertEqual(schema, expected)
+
+
[email protected](coreapi, 'coreapi is not installed')
+class Test4605Regression(TestCase):
+ def test_4605_regression(self):
+ generator = SchemaGenerator()
+ prefix = generator.determine_path_prefix([
+ '/api/v1/items/',
+ '/auth/convert-token/'
+ ])
+ assert prefix == '/'
| Invalid prefix in Swagger.
I am using python 2.7 and rest framework 3.5.
As the title suggests, the prefix is invalid in swagger. It's best shown by this image.

## Expected behavior
The prefixes should have been "api" and "auth" instead of "pi" and "uth".
I suspect that it is due to the behavior of "os.path.commonprefix" in python 2.7
| Okay, thanks - can you include a minimal example that demonstrates reproducing the issue?
Confirmed. Register two API views with the URLs given above, and seeing the same issue.
See also http://nedbatchelder.com/blog/201003/whats_the_point_of_ospathcommonprefix.html
| 2016-10-21T15:28:34 |
encode/django-rest-framework | 4,612 | encode__django-rest-framework-4612 | [
"4608"
] | d647d37a99df3673000f17f7d565a8dab0770805 | diff --git a/rest_framework/compat.py b/rest_framework/compat.py
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -207,7 +207,6 @@ def value_from_object(field, obj):
try:
if 'guardian' in settings.INSTALLED_APPS:
import guardian
- import guardian.shortcuts # Fixes #1624
except ImportError:
pass
diff --git a/rest_framework/filters.py b/rest_framework/filters.py
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -289,6 +289,11 @@ def __init__(self):
perm_format = '%(app_label)s.view_%(model_name)s'
def filter_queryset(self, request, queryset, view):
+ # We want to defer this import until run-time, rather than import-time.
+ # See https://github.com/tomchristie/django-rest-framework/issues/4608
+ # (Also see #1624 for why we need to make this import explicitly)
+ from guardian.shortcuts import get_objects_for_user
+
extra = {}
user = request.user
model_cls = queryset.model
@@ -302,4 +307,4 @@ def filter_queryset(self, request, queryset, view):
extra = {'accept_global_perms': False}
else:
extra = {}
- return guardian.shortcuts.get_objects_for_user(user, permission, queryset, **extra)
+ return get_objects_for_user(user, permission, queryset, **extra)
diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -1,4 +1,3 @@
-import os
import re
from collections import OrderedDict
from importlib import import_module
@@ -37,6 +36,18 @@
})
+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
@@ -292,7 +303,7 @@ def determine_path_prefix(self, paths):
# one URL that doesn't have a path prefix.
return '/'
prefixes.append('/' + prefix + '/')
- return os.path.commonprefix(prefixes)
+ return common_path(prefixes)
def create_view(self, callback, method, request=None):
"""
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -335,3 +335,14 @@ def test_schema_for_regular_views(self):
}
)
self.assertEqual(schema, expected)
+
+
[email protected](coreapi, 'coreapi is not installed')
+class Test4605Regression(TestCase):
+ def test_4605_regression(self):
+ generator = SchemaGenerator()
+ prefix = generator.determine_path_prefix([
+ '/api/v1/items/',
+ '/auth/convert-token/'
+ ])
+ assert prefix == '/'
| Importing rest_framework.compat may raise AppRegistryNotReady
This may just be a wontfix, but wanted to at least make the issue known. In short `rest_framework.compat` cannot be imported during the Django's app registration/initialization process when django-guardian is in the `INSTALLED_APPS`. `guardian.shortcuts` imports Django's auth models, which in turn raises an `AppRegistryNotReady` exception.
Relevant portion of the stack trace:
``` py
File "lib/python2.7/site-packages/django_filters/compat.py", line 19, in <module>
from rest_framework.compat import coreapi
File "lib/python2.7/site-packages/rest_framework/compat.py", line 210, in <module>
import guardian.shortcuts # Fixes #1624
File "lib/python2.7/site-packages/guardian/shortcuts.py", line 6, in <module>
from django.contrib.auth.models import Group, Permission
```
See https://github.com/carltongibson/django-filter/issues/525 for more context.
## 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
As an example, add `'guardian'` and `'django_filters'` to `INSTALLED_APPS`.
| 2016-10-21T15:47:14 |
|
encode/django-rest-framework | 4,620 | encode__django-rest-framework-4620 | [
"4619"
] | 1bd35ad35553e1be91df85dadb163c240aa51498 | diff --git a/rest_framework/filters.py b/rest_framework/filters.py
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -37,15 +37,32 @@ def get_schema_fields(self, view):
return []
-class FilterSet(object):
- def __new__(cls, *args, **kwargs):
- warnings.warn(
- "The built in 'rest_framework.filters.FilterSet' is pending deprecation. "
- "You should use 'django_filters.rest_framework.FilterSet' instead.",
- PendingDeprecationWarning
- )
- from django_filters.rest_framework import FilterSet
- return FilterSet(*args, **kwargs)
+if django_filters:
+ from django_filters.filterset import FilterSetMetaclass as DFFilterSetMetaclass
+ from django_filters.rest_framework.filterset import FilterSet as DFFilterSet
+
+ class FilterSetMetaclass(DFFilterSetMetaclass):
+ def __new__(cls, name, bases, attrs):
+ warnings.warn(
+ "The built in 'rest_framework.filters.FilterSet' is pending deprecation. "
+ "You should use 'django_filters.rest_framework.FilterSet' instead.",
+ PendingDeprecationWarning
+ )
+ return super(FilterSetMetaclass, cls).__new__(cls, name, bases, attrs)
+ _BaseFilterSet = DFFilterSet
+else:
+ # Dummy metaclass just so we can give a user-friendly error message.
+ class FilterSetMetaclass(type):
+ def __init__(self, name, bases, attrs):
+ # Assert only on subclasses, so we can define FilterSet below.
+ if bases != (object,):
+ assert False, 'django-filter must be installed to use the `FilterSet` class'
+ super(FilterSetMetaclass, self).__init__(name, bases, attrs)
+ _BaseFilterSet = object
+
+
+class FilterSet(six.with_metaclass(FilterSetMetaclass, _BaseFilterSet)):
+ pass
class DjangoFilterBackend(BaseFilterBackend):
| diff --git a/tests/test_filters.py b/tests/test_filters.py
--- a/tests/test_filters.py
+++ b/tests/test_filters.py
@@ -79,12 +79,23 @@ class Meta:
model = BaseFilterableItem
fields = '__all__'
+ # Test the same filter using the deprecated internal FilterSet class.
+ class BaseFilterableItemFilterWithProxy(filters.FilterSet):
+ text = django_filters.CharFilter()
+
+ class Meta:
+ model = BaseFilterableItem
+ fields = '__all__'
+
class BaseFilterableItemFilterRootView(generics.ListCreateAPIView):
queryset = FilterableItem.objects.all()
serializer_class = FilterableItemSerializer
filter_class = BaseFilterableItemFilter
filter_backends = (filters.DjangoFilterBackend,)
+ class BaseFilterableItemFilterWithProxyRootView(BaseFilterableItemFilterRootView):
+ filter_class = BaseFilterableItemFilterWithProxy
+
# Regression test for #814
class FilterFieldsQuerysetView(generics.ListCreateAPIView):
queryset = FilterableItem.objects.all()
@@ -296,6 +307,18 @@ def test_base_model_filter(self):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)
+ @unittest.skipUnless(django_filters, 'django-filter not installed')
+ def test_base_model_filter_with_proxy(self):
+ """
+ The `get_filter_class` model checks should allow base model filters.
+ """
+ view = BaseFilterableItemFilterWithProxyRootView.as_view()
+
+ request = factory.get('/?text=aaa')
+ response = view(request).render()
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.data), 1)
+
@unittest.skipUnless(django_filters, 'django-filter not installed')
def test_unknown_filter(self):
"""
| FilterSet proxying broken in 3.5
The 3.5 release seems to have broken custom FilterSet classes with #4593. Any FilterSets I define behave as if no filters were included, returning all results.
The tests don't currently cover the new behaviour:
https://codecov.io/gh/tomchristie/django-rest-framework/src/1bd35ad35553e1be91df85dadb163c240aa51498/rest_framework/filters.py#L40
## 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
## Expected behavior
FilterSet behaves the same as django_filters FilterSet.
## Actual behavior
FilterSet doesn't filter properly. Filtering always returns the whole queryset.
| 2016-10-24T06:33:41 |
|
encode/django-rest-framework | 4,622 | encode__django-rest-framework-4622 | [
"4602"
] | 1bd35ad35553e1be91df85dadb163c240aa51498 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -54,12 +54,17 @@ def is_simple_callable(obj):
"""
True if the object is a callable that takes no arguments.
"""
- if not callable(obj):
+ if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
return False
sig = inspect.signature(obj)
params = sig.parameters.values()
- return all(param.default != param.empty for param in params)
+ return all(
+ param.kind == param.VAR_POSITIONAL or
+ param.kind == param.VAR_KEYWORD or
+ param.default != param.empty
+ for param in params
+ )
else:
def is_simple_callable(obj):
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -37,6 +37,9 @@ def valid(self):
def valid_kwargs(self, param='value'):
pass
+ def valid_vargs_kwargs(self, *args, **kwargs):
+ pass
+
def invalid(self, param):
pass
@@ -45,11 +48,13 @@ def invalid(self, param):
# unbound methods
assert not is_simple_callable(Foo.valid)
assert not is_simple_callable(Foo.valid_kwargs)
+ assert not is_simple_callable(Foo.valid_vargs_kwargs)
assert not is_simple_callable(Foo.invalid)
# bound methods
assert is_simple_callable(Foo().valid)
assert is_simple_callable(Foo().valid_kwargs)
+ assert is_simple_callable(Foo().valid_vargs_kwargs)
assert not is_simple_callable(Foo().invalid)
def test_function(self):
@@ -59,13 +64,31 @@ def simple():
def valid(param='value', param2='value'):
pass
+ def valid_vargs_kwargs(*args, **kwargs):
+ pass
+
def invalid(param, param2='value'):
pass
assert is_simple_callable(simple)
assert is_simple_callable(valid)
+ assert is_simple_callable(valid_vargs_kwargs)
assert not is_simple_callable(invalid)
+ def test_4602_regression(self):
+ from django.db import models
+
+ class ChoiceModel(models.Model):
+ choice_field = models.CharField(
+ max_length=1, default='a',
+ choices=(('a', 'A'), ('b', 'B')),
+ )
+
+ class Meta:
+ app_label = 'tests'
+
+ assert is_simple_callable(ChoiceModel().get_choice_field_display)
+
@unittest.skipUnless(typings, 'requires python 3.5')
def test_type_annotation(self):
# The annotation will otherwise raise a syntax error in python < 3.5
| Not calling function with source= anymore
Here the serializer:
``` python
class IndividuSerializer(ModelSerializer):
# ...
sexe_display = CharField(source='get_sexe_display', label='sexe', read_only=True)
```
The API doesn't display the choice values from Django models anymore.
``` json
{
"url": "http://localhost:8000/api/dsn/individu/1/",
"id": 1,
"metadatas": null,
"sexe_display": "<bound method curry.<locals>._curried of <Individu: XXX XXX>>",
"...": "..."
}
```
In the previous release it worked just fine. ;)
| I'm not able to replicate this.
For example...
```
class UserSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='get_username', read_only=True)
class Meta:
model = User
fields = ('id', 'username', 'email')
```
Results in this...

Could you try to reduce this to a reproducible test case, or similar?
``` python
class IndividuSerializer(ModelSerializer):
# ...
sexe_display = CharField(source='get_sexe_display', label='sexe', read_only=True)
```
The field `sexe` is defined in django model. And The method `get_sexe_display` is django's `_get_FIELD_display`. It's returned `<bound method curry.<locals>._curried of <Individu: XXX XXX>>`.
`_curried(*moreargs, **morekwargs)` is defined in django.utils.functional
But In drf 'fields.py' line 62, method `is_simple_callable`, `param.default` is always `param.empty`.
[https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py#L62](url)
| 2016-10-24T09:07:31 |
encode/django-rest-framework | 4,638 | encode__django-rest-framework-4638 | [
"4631"
] | 895c67c9a22eff1057703a8c578c4833f63a9d70 | diff --git a/rest_framework/views.py b/rest_framework/views.py
--- a/rest_framework/views.py
+++ b/rest_framework/views.py
@@ -445,7 +445,7 @@ def raise_uncaught_exception(self, exc):
renderer_format = getattr(request.accepted_renderer, 'format')
use_plaintext_traceback = renderer_format not in ('html', 'api', 'admin')
request.force_plaintext_errors(use_plaintext_traceback)
- raise exc
+ raise
# Note: Views are made CSRF exempt from within `as_view` as to prevent
# accidental removal of this exemption in cases where `dispatch` needs to
| Unhandled exception traceback hides exception original string on python 2.7
After commit e3686aca93a8224280b38b7669342bcadb24176e (3.5.1 version) python 2.7 traceback for unhandled exceptions no longer contain line where exception occured, because we're reraising exception explicitly.
```
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/viewsets.py", line 83, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/views.py", line 448, in raise_uncaught_exception
raise exc
KeyError: 'request'
```
Full tracebacks:
<details>
<summary>
Traceback on DRF 3.5.0 (good behavior)</summary>
```
Traceback (most recent call last):
File "/Users/coagulant/projects/myproject/project/tests/api/account_tests.py", line 346, in test_put_account_detail_restricted_fields_200
{'email': u'[email protected]'})
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/test.py", line 307, in put
path, data=data, format=format, content_type=content_type, **extra)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/test.py", line 225, in put
return self.generic('PUT', path, data, content_type, **extra)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/test/client.py", line 380, in generic
return self.request(**r)
File "/Users/coagulant/projects/myproject/project/tests/fixtures/clients.py", line 27, in request
return super(DRFAPIClient, self).request(**kwargs)
File "/Users/coagulant/projects/myproject/project/tests/fixtures/clients.py", line 17, in request
return super(AutoPrependBasePathMixin, self).request(**kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/test.py", line 288, in request
return super(APIClient, self).request(**kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/test.py", line 240, in request
request = super(APIRequestFactory, self).request(**kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/test/client.py", line 449, in request
response = self.handler(environ)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/test/client.py", line 123, in __call__
response = self.get_response(request)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/test.py", line 260, in get_response
return super(ForceAuthClientHandler, self).get_response(request)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/core/handlers/base.py", line 230, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/viewsets.py", line 83, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/views.py", line 474, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/mixins.py", line 78, in update
return Response(serializer.data)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/serializers.py", line 504, in data
ret = super(Serializer, self).data
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/serializers.py", line 239, in data
self._data = self.to_representation(self.instance)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/serializers.py", line 473, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/relations.py", line 371, in to_representation
url = self.get_url(value, self.view_name, request, format)
File "/Users/coagulant/projects/myproject/project/api/serializers.py", line 19, in get_url
version = kwargs['request'].version
KeyError: 'request'
```
</details>
<details>
<summary>
Traceback on DRF 3.5.1 (unexpected behavior)</summary>
```
Traceback (most recent call last):
File "/Users/coagulant/projects/myproject/project/tests/api/account_tests.py", line 346, in test_put_account_detail_restricted_fields_200
{'email': u'[email protected]'})
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/test.py", line 307, in put
path, data=data, format=format, content_type=content_type, **extra)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/test.py", line 225, in put
return self.generic('PUT', path, data, content_type, **extra)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/test/client.py", line 380, in generic
return self.request(**r)
File "/Users/coagulant/projects/myproject/project/tests/fixtures/clients.py", line 27, in request
return super(DRFAPIClient, self).request(**kwargs)
File "/Users/coagulant/projects/myproject/project/tests/fixtures/clients.py", line 17, in request
return super(AutoPrependBasePathMixin, self).request(**kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/test.py", line 288, in request
return super(APIClient, self).request(**kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/test.py", line 240, in request
request = super(APIRequestFactory, self).request(**kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/test/client.py", line 449, in request
response = self.handler(environ)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/test/client.py", line 123, in __call__
response = self.get_response(request)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/test.py", line 260, in get_response
return super(ForceAuthClientHandler, self).get_response(request)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/core/handlers/base.py", line 230, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/viewsets.py", line 83, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/coagulant/.envs/myproject/lib/python2.7/site-packages/rest_framework/views.py", line 448, in raise_uncaught_exception
raise exc
KeyError: 'request'
```
</details>
| Missed that line and agreed, raising should preserve the stack so it's either a raw raise or drf will have to backfeed the traceback
<details><summary>
Most of all what I've learned from this...</summary>
Is how to use `<details><summary>` in GitHub issues. 👍 </details>
Okay, so the change there was in response to https://github.com/tomchristie/django-rest-framework/pull/4600 "raise with no arguments can only be used in an except clause as of Python 3.5."
Any suggestions for how to proceed?
> Okay, so the change there was in response to #4600 "raise with no arguments can only be used in an except clause as of Python 3.5."
> Any suggestions for how to proceed?
I suppose handle_exception is called inside an except clause, and there was no problem in the first place?
| 2016-11-01T10:09:34 |
|
encode/django-rest-framework | 4,640 | encode__django-rest-framework-4640 | [
"4624"
] | 98df932194722d6fc81becedc55eb695a32f925f | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -644,8 +644,20 @@ class BooleanField(Field):
}
default_empty_html = False
initial = False
- TRUE_VALUES = {'t', 'T', 'true', 'True', 'TRUE', '1', 1, True}
- FALSE_VALUES = {'f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False}
+ TRUE_VALUES = {
+ 't', 'T',
+ 'true', 'True', 'TRUE',
+ 'on', 'On', 'ON',
+ '1', 1,
+ True
+ }
+ FALSE_VALUES = {
+ 'f', 'F',
+ 'false', 'False', 'FALSE',
+ 'off', 'Off', 'OFF',
+ '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.'
| BooleanField should also parse 'on'
## 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
`$(form).serialize()` serialize checkbox with no `value` to "`on`" or "`off`"
## Expected behavior
Add "`on`" to `TRUE_VALUES` and "`off`" to `FALSE_VALUES`
(I don't always have the control over html/js to add `value` to checkboxes).
## Actual behavior
Value is ignored
| 2016-11-01T10:34:30 |
||
encode/django-rest-framework | 4,660 | encode__django-rest-framework-4660 | [
"4644"
] | 06df61e38c6ed99732007b0e9f3cc26e8317389e | diff --git a/rest_framework/filters.py b/rest_framework/filters.py
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -38,31 +38,19 @@ def get_schema_fields(self, view):
if django_filters:
- from django_filters.filterset import FilterSetMetaclass as DFFilterSetMetaclass
from django_filters.rest_framework.filterset import FilterSet as DFFilterSet
- class FilterSetMetaclass(DFFilterSetMetaclass):
- def __new__(cls, name, bases, attrs):
+ class FilterSet(DFFilterSet):
+ def __init__(self, *args, **kwargs):
warnings.warn(
"The built in 'rest_framework.filters.FilterSet' is pending deprecation. "
"You should use 'django_filters.rest_framework.FilterSet' instead.",
PendingDeprecationWarning
)
- return super(FilterSetMetaclass, cls).__new__(cls, name, bases, attrs)
- _BaseFilterSet = DFFilterSet
+ return super(FilterSet, self).__init__(*args, **kwargs)
else:
- # Dummy metaclass just so we can give a user-friendly error message.
- class FilterSetMetaclass(type):
- def __init__(self, name, bases, attrs):
- # Assert only on subclasses, so we can define FilterSet below.
- if bases != (object,):
- assert False, 'django-filter must be installed to use the `FilterSet` class'
- super(FilterSetMetaclass, self).__init__(name, bases, attrs)
- _BaseFilterSet = object
-
-
-class FilterSet(six.with_metaclass(FilterSetMetaclass, _BaseFilterSet)):
- pass
+ def FilterSet():
+ assert False, 'django-filter must be installed to use the `FilterSet` class'
class DjangoFilterBackend(BaseFilterBackend):
| No friendly message about removal of filtersets emitted.
I'm getting the following backtrace since 3.5.2 was released.
```
mod_wsgi (pid=107917): Exception occurred processing WSGI script '/my_project/my_app/deploy/my_app.wsgi'.
Traceback (most recent call last):
File "my_project/my_app/deploy/python-env/lib/python2.7/site-packages/Django-1.8-py2.7.egg/django/core/handlers/wsgi.py", line 170, in __call__
self.load_middleware()
File "my_project/my_app/deploy/python-env/lib/python2.7/site-packages/Django-1.8-py2.7.egg/django/core/handlers/base.py", line 52, in load_middleware
mw_instance = mw_class()
File "my_project/my_app/deploy/python-env/lib/python2.7/site-packages/Django-1.8-py2.7.egg/django/middleware/locale.py", line 24, in __init__
for url_pattern in get_resolver(None).url_patterns:
File "my_project/my_app/deploy/python-env/lib/python2.7/site-packages/Django-1.8-py2.7.egg/django/core/urlresolvers.py", line 402, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "my_project/my_app/deploy/python-env/lib/python2.7/site-packages/Django-1.8-py2.7.egg/django/core/urlresolvers.py", line 396, in urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "my_project/my_app/deploy/cgi/my_app/urls.py", line 7, in <module>
from rest_framework import routers, serializers, viewsets
File "my_project/my_app/deploy/python-env/lib/python2.7/site-packages/djangorestframework-3.5.2-py2.7.egg/rest_framework/viewsets.py", line 26, in <module>
from rest_framework import generics, mixins, views
File "my_project/my_app/deploy/python-env/lib/python2.7/site-packages/djangorestframework-3.5.2-py2.7.egg/rest_framework/generics.py", line 25, in <module>
class GenericAPIView(views.APIView):
File "my_project/my_app/deploy/python-env/lib/python2.7/site-packages/djangorestframework-3.5.2-py2.7.egg/rest_framework/generics.py", line 44, in GenericAPIView
filter_backends = api_settings.DEFAULT_FILTER_BACKENDS
File "my_project/my_app/deploy/python-env/lib/python2.7/site-packages/djangorestframework-3.5.2-py2.7.egg/rest_framework/settings.py", line 220, in __getattr__
val = perform_import(val, attr)
File "my_project/my_app/deploy/python-env/lib/python2.7/site-packages/djangorestframework-3.5.2-py2.7.egg/rest_framework/settings.py", line 165, in perform_import
return [import_from_string(item, setting_name) for item in val]
File "my_project/my_app/deploy/python-env/lib/python2.7/site-packages/djangorestframework-3.5.2-py2.7.egg/rest_framework/settings.py", line 181, in import_from_string
raise ImportError(msg)
ImportError: Could not import 'rest_framework.filters.DjangoFilterBackend' for API setting 'DEFAULT_FILTER_BACKENDS'. ImportError: No module named rest_framework.filterset.
```
with
```
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': (
'rest_framework.filters.DjangoFilterBackend',
),
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
),
'DEFAULT_RENDERER_CLASSES' : [
'rest_framework.renderers.JSONRenderer',
],
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAdminUser',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
)
}
```
My reading of #4620 is that this should be a friendly warning pointing be to the direct issue. Instead I had to dig through the diff of pip freeze outputs to trace it down. No worries it's done now. BVUt it might help other later if your warning appears . ;-).
| :-/
Related: #4643
As is, 3.5.1+ are not compatible with code written for 3.5.0. I get that this was a bugfix (or did I understand something wrong ?) but 3.5.1 should really be called 4.0.0, and so on. Getting an ImportError because you depend on "djangorestframework>=3.5,<3.6" is really bad semver practice :(
It's not intentional. It's a bugfix causing a bug. We'll resolve it and issue a new release ASAP.
| 2016-11-07T12:26:59 |
|
encode/django-rest-framework | 4,662 | encode__django-rest-framework-4662 | [
"4654"
] | ea60872e9e18909577a2603f5ff630a7c9d04b16 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -92,11 +92,19 @@ def get_package_data(package):
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
+ 'Framework :: Django :: 1.8',
+ 'Framework :: Django :: 1.9',
+ 'Framework :: Django :: 1.10',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.3',
+ 'Programming Language :: Python :: 3.4',
+ 'Programming Language :: Python :: 3.5',
'Topic :: Internet :: WWW/HTTP',
]
)
| Update Trove Classifers in setup.py
## 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
None. Issue is with the [trove classifiers](https://pypi.python.org/pypi?%3Aaction=list_classifiers) in the https://github.com/tomchristie/django-rest-framework/blob/master/setup.py
## Expected behavior
Have the [trove classifiers](https://pypi.python.org/pypi?%3Aaction=list_classifiers) to match the documented [Django REST Framework Requirements](http://www.django-rest-framework.org/#requirements) in future releases:
```
Framework :: Django
Framework :: Django :: 1.8
Framework :: Django :: 1.9
Framework :: Django :: 1.10
Programming Language :: Python :: 2
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3
Programming Language :: Python :: 3.2
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
Programming Language :: Python :: 3.5
```
## Actual behavior
Currently, the below are listed:
```
Framework :: Django
Programming Language :: Python
Programming Language :: Python :: 3
```
If doing filtering by the [trove classifiers](https://pypi.python.org/pypi?%3Aaction=list_classifiers), it would be nice to see the exact versions of Django/Python supported. Additionally, it helps with third-party sites to list the correct requirements that are retrieved from the [trove classifiers](https://pypi.python.org/pypi?%3Aaction=list_classifiers) within the PyPI API ([example](https://pypi.python.org/pypi/djangorestframework/json)).
| Seems fair enough. Pull requests welcome.
| 2016-11-08T17:01:37 |
|
encode/django-rest-framework | 4,668 | encode__django-rest-framework-4668 | [
"4661"
] | 388cf7622c24fee33f998cbe44198bada1872ebb | diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py
--- a/rest_framework/mixins.py
+++ b/rest_framework/mixins.py
@@ -71,9 +71,8 @@ def update(self, request, *args, **kwargs):
if getattr(instance, '_prefetched_objects_cache', None):
# If 'prefetch_related' has been applied to a queryset, we need to
- # refresh the instance from the database.
- instance = self.get_object()
- serializer = self.get_serializer(instance)
+ # forcibly invalidate the prefetch cache on the instance.
+ instance._prefetched_objects_cache = {}
return Response(serializer.data)
| diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md
--- a/docs/api-guide/testing.md
+++ b/docs/api-guide/testing.md
@@ -187,7 +187,12 @@ As usual CSRF validation will only apply to any session authenticated views. Th
# RequestsClient
REST framework also includes a client for interacting with your application
-using the popular Python library, `requests`.
+using the popular Python library, `requests`. This may be useful if:
+
+* You are expecting to interface with the API primarily from another Python service,
+and want to test the service at the same level as the client will see.
+* You want to write tests in such a way that they can also be run against a staging or
+live environment. (See "Live tests" below.)
This exposes exactly the same interface as if you were using a requests session
directly.
@@ -198,6 +203,10 @@ directly.
Note that the requests client requires you to pass fully qualified URLs.
+## `RequestsClient` and working with the database
+
+The `RequestsClient` class is useful if
+
## Headers & Authentication
Custom headers and authentication credentials can be provided in the same way
diff --git a/tests/test_prefetch_related.py b/tests/test_prefetch_related.py
--- a/tests/test_prefetch_related.py
+++ b/tests/test_prefetch_related.py
@@ -14,7 +14,7 @@ class Meta:
class UserUpdate(generics.UpdateAPIView):
- queryset = User.objects.all().prefetch_related('groups')
+ queryset = User.objects.exclude(username='exclude').prefetch_related('groups')
serializer_class = UserSerializer
@@ -39,3 +39,21 @@ def test_prefetch_related_updates(self):
'email': '[email protected]'
}
assert response.data == expected
+
+ def test_prefetch_related_excluding_instance_from_original_queryset(self):
+ """
+ Regression test for https://github.com/tomchristie/django-rest-framework/issues/4661
+ """
+ view = UserUpdate.as_view()
+ pk = self.user.pk
+ groups_pk = self.groups[0].pk
+ request = factory.put('/', {'username': 'exclude', 'groups': [groups_pk]}, format='json')
+ response = view(request, pk=pk)
+ assert User.objects.get(pk=pk).groups.count() == 1
+ expected = {
+ 'id': pk,
+ 'username': 'exclude',
+ 'groups': [1],
+ 'email': '[email protected]'
+ }
+ assert response.data == expected
| Reload for `prefetch_related` updates may fail if object is filtered out.
In the awkward case where `prefetch_related` has been applied to an update operation, we are required to refresh the instance from the database (see #4553)
The current implementation re-calls `get_object()`. We should instead call `refresh_from_db` directly on the model instance. This means that we don't have a potential case of `get_object` returning `None` because the update itself has effectively removed the object from the base queryset causing the lookup to fail.
| 2016-11-10T15:43:30 |
|
encode/django-rest-framework | 4,669 | encode__django-rest-framework-4669 | [
"4634"
] | 388cf7622c24fee33f998cbe44198bada1872ebb | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -769,7 +769,7 @@ def raise_errors_on_nested_writes(method_name, serializer, validated_data):
isinstance(field, BaseSerializer) and
(field.source in validated_data) and
isinstance(validated_data[field.source], (list, dict))
- for key, field in serializer.fields.items()
+ for field in serializer._writable_fields
), (
'The `.{method_name}()` method does not support writable nested '
'fields by default.\nWrite an explicit `.{method_name}()` method for '
| Multiple fields with the same source clobber each other
Hey guys, I'm getting weird behavior with many related fields. Is this an error?
## 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 a model serializer where one field renders the relation, and the other field writes to it.
``` python
class UserSerializer(serializers.ModelSerializer):
dogs = DogSerializer(many=True, read_only=True)
dog_ids = serializers.PrimaryKeyRelatedField(source='dogs', many=True, queryset=Dog.objects.all())
class Meta:
fields = ('dogs', 'dog_ids',)
model = User
```
Then do a patch.
```
PATCH /api/users/23 HTTP/1.1
Content-Type: application/json
{
"dog_ids": [5, 9]
}
```
## Expected behavior
It should update my model.
## Actual behavior
It throws an error complaining that nested writes aren't allowed.
```
AssertionError at /api/users/23
The `.update()` method does not support writable nestedfields by default.
Write an explicit `.update()` method for serializer `app.serializers.DogSerializer`, or set `read_only=True` on nested serializer fields.
```
## tl;dr
This assertion gets called, but it checks all fields rather than just the writable ones:
https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L721
``` python
def raise_errors_on_nested_writes(method_name, serializer, validated_data):
assert not any(
isinstance(field, BaseSerializer) and
(key in validated_data) and
isinstance(validated_data[key], (list, dict))
for key, field in serializer.fields.items()
), (
'The `.{method_name}()` method does not support writable nested'
'fields by default.\nWrite an explicit `.{method_name}()` method for '
'serializer `{module}.{class_name}`, or set `read_only=True` on '
'nested serializer fields.'.format(
method_name=method_name,
module=serializer.__class__.__module__,
class_name=serializer.__class__.__name__
)
)
```
| Passing a list of ids to a PrimaryKeyRelatedField? Can you post what you are trying to achieve here?
Hey @aswinm, basically I want to be able to:
1. serialize a many-to-many field as nested objects
2. modify a many-to-many field by passing an array of ids to a "meta" field, in this case `dog_ids`
3. use the same field name as the django model in the serialization of the nested objects, in this case `dogs`
FYI, the following code works and accomplishes 1 and 2, but not 3.
``` python
class UserSerializer(serializers.ModelSerializer):
dog_objects = DogSerializer(source='dogs', many=True, read_only=True)
dog_ids = serializers.PrimaryKeyRelatedField(source='dogs', many=True, queryset=Dog.objects.all())
class Meta:
fields = ('dog_objects', 'dog_ids',)
model = User
```
I can confirm the issue, the pull request that changed the behaviour of nested write check is this #4568 and in my humble opionion i would go for the extra 'read_only' check proposed by @educolo otherwise the issue will happen one way or another.
Having same exact problem.
| 2016-11-10T16:02:57 |
|
encode/django-rest-framework | 4,852 | encode__django-rest-framework-4852 | [
"4574"
] | 21166a3ab62934266ebef5f4a3123a7ead3460ad | diff --git a/rest_framework/utils/model_meta.py b/rest_framework/utils/model_meta.py
--- a/rest_framework/utils/model_meta.py
+++ b/rest_framework/utils/model_meta.py
@@ -76,7 +76,12 @@ def _get_forward_relationships(opts):
Returns an `OrderedDict` of field names to `RelationInfo`.
"""
forward_relations = OrderedDict()
- for field in [field for field in opts.fields if field.serialize and get_remote_field(field)]:
+ for field in [
+ field for field in opts.fields
+ if field.serialize and get_remote_field(field) and not (field.primary_key and field.one_to_one)
+ # If the field is a OneToOneField and it's been marked as PK, then this
+ # is a multi-table inheritance auto created PK ('%_ptr').
+ ]:
forward_relations[field.name] = RelationInfo(
model_field=field,
related_model=get_related_model(field),
| MultiTable Inherited Model Tests fail with Django 1.11a1
running `tox` on master I get (I don't have Python 3.4 installed):
```
ERROR: py27-djangomaster: commands failed
...
ERROR: py35-djangomaster: commands failed
```
For me Django master is at `74a575e`: https://github.com/django/django/commit/74a575eb7296fb04e1fc2bd4e3f68dee3c66ee0a
SHA256 for the https://github.com/django/django/archive/master.tar.gz I'm seeing: `bc2874ca4e3bce55f528d4cd4fc9b36a5164313675ad534b8b900502ffe9f79d``
The failing tests are:
```
_________________________________ IntegrationTestFiltering.test_filter_with_queryset _________________________________
tests/test_filters.py:179: in test_filter_with_queryset
self.assertEqual(response.data, expected_data)
E AssertionError: [OrderedDict([('id', 3), ('text', 'ccc'), [72 chars]3)])] != [{'decimal': '2.25', 'date': '2012-10-04',[20 chars]: 3}]
_____________________________ IntegrationTestFiltering.test_get_filtered_class_root_view _____________________________
tests/test_filters.py:204: in test_get_filtered_class_root_view
self.assertEqual(response.data, self.data)
E AssertionError: [OrderedDict([('id', 1), ('text', 'aaa'), [1145 chars]0)])] != [{'decimal': '0.25', 'date': '2012-10-08',[624 chars] 10}]
____________________________ IntegrationTestFiltering.test_get_filtered_fields_root_view _____________________________
tests/test_filters.py:148: in test_get_filtered_fields_root_view
self.assertEqual(response.data, self.data)
E AssertionError: [OrderedDict([('id', 1), ('text', 'aaa'), [1145 chars]0)])] != [{'decimal': '0.25', 'date': '2012-10-08',[624 chars] 10}]
____________________________ IntegrationTestDetailFiltering.test_get_filtered_detail_view ____________________________
tests/test_filters.py:298: in test_get_filtered_detail_view
self.assertEqual(response.data, data)
E AssertionError: {'dec[26 chars]12-10-08', 'basefilterableitem_ptr': 1, 'text': 'aaa', 'id': 1} != {'dec[26 chars]12-10-08', 'text': 'aaa', 'id': 1}
_______________________ InheritedModelSerializationTests.test_data_is_valid_without_parent_ptr _______________________
tests/test_multitable_inheritance.py:71: in test_data_is_valid_without_parent_ptr
self.assertEqual(serializer.is_valid(), True)
E AssertionError: False != True
________________ InheritedModelSerializationTests.test_multitable_inherited_model_fields_as_expected _________________
tests/test_multitable_inheritance.py:48: in test_multitable_inherited_model_fields_as_expected
set(['name1', 'name2', 'id']))
E AssertionError: Items in the first set but not the second:
E 'parentmodel_ptr'
```
| Indeed. Needs further investigation. We don't necessarily support running against Django master, as some bits of public & private API may change under our feet, but it's worth having these resolved in anticipation of 1.11.
Any further digging from anyone on this is most welcome.
btw, the django-filter backend is migrating to the django-filter package. Any fixes to `IntegrationTestFiltering` here should probably have a corresponding PR in django-filter.
To review as part of 3.5, depending on if we deprecate Django filter as part of that release or not.
As per #4648, this doesn't look like it's anything to do with Django Filter.
It comes up combining Django master, Model Inheritance, ModelSerializer and `fields = '__all__'`: in this case we get an extra pointer to the the parent model in the serialiser's `data`.
bd3fe75e introduced a test for this, which is now failing:
```
______InheritedModelSerializationTests.test_data_is_valid_without_parent_ptr _________
tests/test_multitable_inheritance.py:71: in test_data_is_valid_without_parent_ptr
self.assertEqual(serializer.is_valid(), True)
E AssertionError: False != True
```
I think that's the key one.
| 2017-01-25T19:09:55 |
|
encode/django-rest-framework | 4,919 | encode__django-rest-framework-4919 | [
"4897"
] | d82dbc09257a521e8d912880855e5758c758dafb | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -1290,6 +1290,15 @@ def get_extra_kwargs(self):
kwargs['read_only'] = True
extra_kwargs[field_name] = kwargs
+ else:
+ # Guard against the possible misspelling `readonly_fields` (used
+ # by the Django admin and others).
+ assert not hasattr(self.Meta, 'readonly_fields'), (
+ 'Serializer `%s.%s` has field `readonly_fields`; '
+ 'the correct spelling for the option is `read_only_fields`.' %
+ (self.__class__.__module__, self.__class__.__name__)
+ )
+
return extra_kwargs
def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs):
| 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
@@ -10,6 +10,7 @@
import decimal
from collections import OrderedDict
+import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.validators import (
MaxValueValidator, MinLengthValidator, MinValueValidator
@@ -1064,3 +1065,18 @@ class Meta:
child_expected = {'parent': 1, 'value': 'def'}
self.assertEqual(child_serializer.data, child_expected)
+
+
+class Issue4897TestCase(TestCase):
+ def test_should_assert_if_writing_readonly_fields(self):
+ class TestSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = OneFieldModel
+ fields = ('char_field',)
+ readonly_fields = fields
+
+ obj = OneFieldModel.objects.create(char_field='abc')
+
+ with pytest.raises(AssertionError) as cm:
+ TestSerializer(obj).fields
+ cm.match(r'readonly_fields')
| Possibly easy to make typo: `readonly_fields` in serializers
In DRF serializers, one way to make fields read-only is to use the `read_only_fields` attribute:
```python
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
read_only_fields = ('account_name',)
```
There is similar functionality in the Django admin, only there it is spelled [`readonly_fields`](https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields):
```python
class AccountAdmin(admin.ModelAdmin):
fields = ('id', 'account_name', 'users', 'created')
readonly_fields = ('account_name',)
````
If one is familiar with the Django admin, they are somewhat likely to spell it wrong in serializers (hmm I'm not talking about myself of course), with possibly bad results.
I have noticed that in several places DRF contains preemptive checks against common errors and raises helpful warnings for them. Do you think it makes sense to do something like that in case someone writes `readonly_fields` in a serializer? (I'll be happy to write a patch if so.)
| Would probably make sense. | 2017-02-22T11:26:37 |
encode/django-rest-framework | 4,973 | encode__django-rest-framework-4973 | [
"4705"
] | e94011eb77a1030ff0e1b25755274aa0af7ff4a6 | diff --git a/rest_framework/viewsets.py b/rest_framework/viewsets.py
--- a/rest_framework/viewsets.py
+++ b/rest_framework/viewsets.py
@@ -79,6 +79,9 @@ 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
+
# And continue as usual
return self.dispatch(request, *args, **kwargs)
| diff --git a/tests/test_generics.py b/tests/test_generics.py
--- a/tests/test_generics.py
+++ b/tests/test_generics.py
@@ -101,6 +101,15 @@ def test_get_root_view(self):
assert response.status_code == status.HTTP_200_OK
assert response.data == self.data
+ def test_head_root_view(self):
+ """
+ HEAD requests to ListCreateAPIView should return 200.
+ """
+ request = factory.head('/')
+ with self.assertNumQueries(1):
+ response = self.view(request).render()
+ assert response.status_code == status.HTTP_200_OK
+
def test_post_root_view(self):
"""
POST requests to ListCreateAPIView should create a new object.
diff --git a/tests/test_viewsets.py b/tests/test_viewsets.py
--- a/tests/test_viewsets.py
+++ b/tests/test_viewsets.py
@@ -24,6 +24,15 @@ def test_initialize_view_set_with_actions(self):
assert response.status_code == status.HTTP_200_OK
assert response.data == {'ACTION': 'LIST'}
+ def testhead_request_against_viewset(self):
+ request = factory.head('/', '', content_type='application/json')
+ my_view = BasicViewSet.as_view(actions={
+ 'get': 'list',
+ })
+
+ response = my_view(request)
+ assert response.status_code == status.HTTP_200_OK
+
def test_initialize_view_set_with_empty_actions(self):
try:
BasicViewSet.as_view()
| A "pure" HEAD request on a ViewSet does'nt behave like a GET
A HEAD request on a ViewSet let the action attribute empty.
```curl -I http://myhost/api/foo/```
It should fallback to simulate a GET request for everything but the rendering.
Meaning self.action should be either 'list' or 'retrieve'.
Note: ```curl -I -XGET [...]``` behaves as expected.
| 2017-03-13T12:53:57 |
|
encode/django-rest-framework | 4,979 | encode__django-rest-framework-4979 | [
"4751"
] | 8f6173cd8afadd503dde124a616355ea80b5f6fe | diff --git a/rest_framework/documentation.py b/rest_framework/documentation.py
--- a/rest_framework/documentation.py
+++ b/rest_framework/documentation.py
@@ -6,7 +6,9 @@
from rest_framework.schemas import SchemaGenerator, get_schema_view
-def get_docs_view(title=None, description=None, schema_url=None, public=True, generator_class=SchemaGenerator):
+def get_docs_view(
+ title=None, description=None, schema_url=None, public=True,
+ patterns=None, generator_class=SchemaGenerator):
renderer_classes = [DocumentationRenderer, CoreJSONRenderer]
return get_schema_view(
@@ -15,11 +17,14 @@ def get_docs_view(title=None, description=None, schema_url=None, public=True, ge
description=description,
renderer_classes=renderer_classes,
public=public,
+ patterns=patterns,
generator_class=generator_class,
)
-def get_schemajs_view(title=None, description=None, schema_url=None, public=True, generator_class=SchemaGenerator):
+def get_schemajs_view(
+ title=None, description=None, schema_url=None, public=True,
+ patterns=None, generator_class=SchemaGenerator):
renderer_classes = [SchemaJSRenderer]
return get_schema_view(
@@ -28,16 +33,20 @@ def get_schemajs_view(title=None, description=None, schema_url=None, public=True
description=description,
renderer_classes=renderer_classes,
public=public,
+ patterns=patterns,
generator_class=generator_class,
)
-def include_docs_urls(title=None, description=None, schema_url=None, public=True, generator_class=SchemaGenerator):
+def include_docs_urls(
+ title=None, description=None, schema_url=None, public=True,
+ patterns=None, generator_class=SchemaGenerator):
docs_view = get_docs_view(
title=title,
description=description,
schema_url=schema_url,
public=public,
+ patterns=patterns,
generator_class=generator_class,
)
schema_js_view = get_schemajs_view(
@@ -45,6 +54,7 @@ def include_docs_urls(title=None, description=None, schema_url=None, public=True
description=description,
schema_url=schema_url,
public=public,
+ patterns=patterns,
generator_class=generator_class,
)
urls = [
diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -695,18 +695,15 @@ def get(self, request, *args, **kwargs):
def get_schema_view(
- title=None,
- url=None,
- description=None,
- urlconf=None,
- renderer_classes=None,
- public=False,
- generator_class=SchemaGenerator,
-):
+ title=None, url=None, description=None, urlconf=None, renderer_classes=None,
+ public=False, patterns=None, generator_class=SchemaGenerator):
"""
Return a schema view.
"""
- generator = generator_class(title=title, url=url, description=description, urlconf=urlconf)
+ generator = generator_class(
+ title=title, url=url, description=description,
+ urlconf=urlconf, patterns=patterns,
+ )
return SchemaView.as_view(
renderer_classes=renderer_classes,
schema_generator=generator,
| get_schema_view parameters lack SchemaGenerator parameters
## 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
Call `get_schema_view` with `patterns=something` and you get an error because it is not defined.
```
get_schema_view(title=None, url=None, renderer_classes=None):
generator = SchemaGenerator(title=title, url=url)
```
[link](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/schemas.py#L574)
but `SchemaGenerator` object allows:
```
class SchemaGenerator(object):
def __init__(self, title=None, url=None, patterns=None, urlconf=None)
```
## Expected behavior
Be able to call `get_schema_view` with `patterns`.
I don't know why it is not allowed given that the `SchemaGenerator` object that is instantiated allows `patterns` to limit the inspected urls.
## Actual behavior
`TypeError` unexpected keyword argument
| 2017-03-15T07:11:55 |
||
encode/django-rest-framework | 4,998 | encode__django-rest-framework-4998 | [
"4997"
] | 73ad88eaae2f49bfd09508f2dcd6446677800a26 | diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -600,7 +600,8 @@ def get_pagination_fields(self, path, method, view):
if not is_list_view(path, method, view):
return []
- if not getattr(view, 'pagination_class', None):
+ pagination = getattr(view, 'pagination_class', None)
+ if not pagination or not pagination.page_size:
return []
paginator = view.pagination_class()
| #4996 DEFAULT_PAGINATION_CLASS is changed to 'None' in api_settings
because the default value was specified, it did not work properly in API
Document
*Note*: Before submitting this pull request, please review our [contributing guidelines](https://github.com/tomchristie/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.
| 2017-03-17T21:24:04 |
||
encode/django-rest-framework | 5,042 | encode__django-rest-framework-5042 | [
"4999"
] | 66e015c5ecfb3fd5ce8311fa925783224e45193d | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -38,7 +38,8 @@
get_relation_kwargs, get_url_kwargs
)
from rest_framework.utils.serializer_helpers import (
- BindingDict, BoundField, NestedBoundField, ReturnDict, ReturnList
+ BindingDict, BoundField, JSONBoundField, NestedBoundField, ReturnDict,
+ ReturnList
)
from rest_framework.validators import (
UniqueForDateValidator, UniqueForMonthValidator, UniqueForYearValidator,
@@ -521,6 +522,8 @@ def __getitem__(self, key):
error = self.errors.get(key) if hasattr(self, '_errors') else None
if isinstance(field, Serializer):
return NestedBoundField(field, value, error)
+ if isinstance(field, JSONField):
+ return JSONBoundField(field, value, error)
return BoundField(field, value, error)
# Include a backlink to the serializer class on return objects.
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
@@ -8,7 +8,7 @@
from django.db import models
from django.utils.text import capfirst
-from rest_framework.compat import DecimalValidator
+from rest_framework.compat import DecimalValidator, JSONField
from rest_framework.validators import UniqueValidator
NUMERIC_FIELD_TYPES = (
@@ -88,7 +88,7 @@ def get_field_kwargs(field_name, model_field):
if decimal_places is not None:
kwargs['decimal_places'] = decimal_places
- if isinstance(model_field, models.TextField):
+ if isinstance(model_field, models.TextField) or (JSONField and isinstance(model_field, JSONField)):
kwargs['style'] = {'base_template': 'textarea.html'}
if isinstance(model_field, models.AutoField) or not model_field.editable:
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,6 +1,7 @@
from __future__ import unicode_literals
import collections
+import json
from collections import OrderedDict
from django.utils.encoding import force_text
@@ -82,6 +83,16 @@ def as_form_field(self):
return self.__class__(self._field, value, self.errors, self._prefix)
+class JSONBoundField(BoundField):
+ def as_form_field(self):
+ value = self.value
+ try:
+ value = json.dumps(self.value, sort_keys=True, indent=4)
+ except TypeError:
+ pass
+ return self.__class__(self._field, value, self.errors, self._prefix)
+
+
class NestedBoundField(BoundField):
"""
This `BoundField` additionally implements __iter__ and __getitem__
| JSONField not rendered properly in DRF browsable API HTML form
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
- 73ad88eaae2f49bfd09508f2dcd6446677800a26
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- #4135: webform-input parsed as string (PR: #4565)
- [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.)
## Expected behavior
Assuming:
- a valid JSON object is stored in postgreSQL as a django `models.JSONField` and
- that data is serialized using DRF's serializers.JSONField,
then that data should render as a JSON object in DRF browsable API (particularly because the serializer requires input to be valid JSON for POST/PUT/PATCH methods)
## Actual behavior
Data renders as native python in DRF browsable API form field (e.g. single quotes, uppercase booleans)

Note that the "Raw data" view of the input section renders the data correctly as JSON.

## Steps to reproduce
```bash
(venv)vagrant@vm:/vagrant/src/app$ python -V
Python 3.4.3
(venv)vagrant@vm:/vagrant/src/app$ psql -V
psql (PostgreSQL) 9.6.2
```
```
# requirements.txt
Django==1.10.6
psycopg2==2.7.1
-e [email protected]:tomchristie/django-rest-framework.git@73ad88eaae2f49bfd09508f2dcd6446677800a26#egg=djangorestframework-origin/HEAD
```
```python
# models.py
from django.db import models
from django.contrib.postgres.fields import JSONField
class Foo(models.Model):
name = models.CharField(max_length=24)
data = JSONField()
```
```python
# serializers.py
from rest_framework import serializers
from jsontest import models
class FooSerializer(serializers.HyperlinkedModelSerializer):
name = serializers.CharField(max_length=24)
data = serializers.JSONField()
class Meta:
model = models.Foo
fields = ('url', 'name', 'data')
```
```
>>> from jsontest.models import *
>>> f = Foo()
>>> f.name = 'created via shell'
>>> f.data = {'input': 'native dict', 'bar': True}
>>> f.save()
>>> f.id
1
```
| Thanks for reporting.
I gave it a try and yeah, this is reproduced. | 2017-04-02T01:00:51 |
|
encode/django-rest-framework | 5,055 | encode__django-rest-framework-5055 | [
"5054"
] | 5e6b233977637f03ce8960039a5474daec7b024b | diff --git a/rest_framework/views.py b/rest_framework/views.py
--- a/rest_framework/views.py
+++ b/rest_framework/views.py
@@ -290,7 +290,7 @@ def get_exception_handler(self):
"""
Returns the exception handler that this view uses.
"""
- return api_settings.EXCEPTION_HANDLER
+ return self.settings.EXCEPTION_HANDLER
# API policy implementation methods
| diff --git a/tests/test_views.py b/tests/test_views.py
--- a/tests/test_views.py
+++ b/tests/test_views.py
@@ -8,7 +8,7 @@
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
-from rest_framework.settings import api_settings
+from rest_framework.settings import APISettings, api_settings
from rest_framework.test import APIRequestFactory
from rest_framework.views import APIView
@@ -45,6 +45,19 @@ def get(self, request, *args, **kwargs):
raise Exception
+def custom_handler(exc, context):
+ if isinstance(exc, SyntaxError):
+ return Response({'error': 'SyntaxError'}, status=400)
+ return Response({'error': 'UnknownError'}, status=500)
+
+
+class OverridenSettingsView(APIView):
+ settings = APISettings({'EXCEPTION_HANDLER': custom_handler})
+
+ def get(self, request, *args, **kwargs):
+ raise SyntaxError('request is invalid syntax')
+
+
@api_view(['GET'])
def error_view(request):
raise Exception
@@ -118,3 +131,14 @@ def test_function_based_view_exception_handler(self):
expected = 'Error!'
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.data == expected
+
+
+class TestCustomSettings(TestCase):
+ def setUp(self):
+ self.view = OverridenSettingsView.as_view()
+
+ def test_get_exception_handler(self):
+ request = factory.get('/', content_type='application/json')
+ response = self.view(request)
+ assert response.status_code == 400
+ assert response.data == {'error': 'SyntaxError'}
| EXCEPTION_HANDLER on View.settings not respected
## 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
1. Create a View with a custom `ApiSettings` with `EXCEPTION_HANDLER` specified
1. Trigger an exception and notice that the custom exception handler isn't triggered because the APIView class only ever uses `rest_framework.settings.api_settings`.
## Expected behavior
1. View uses `self.settings` since views can override settings objects so easily.
## Actual behavior
1. Uses default handler instead
## Extras
The 3.4 series used `self.settings.EXCEPTION_HANDLER` but 3.5 moved to use `get_exception_handler` which started using `rest_framework.settings.api_settings`.
| 2017-04-06T18:38:48 |
|
encode/django-rest-framework | 5,085 | encode__django-rest-framework-5085 | [
"4691"
] | 8f6173cd8afadd503dde124a616355ea80b5f6fe | diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py
--- a/rest_framework/schemas.py
+++ b/rest_framework/schemas.py
@@ -246,7 +246,9 @@ def get_allowed_methods(self, callback):
Return a list of the valid HTTP methods for this endpoint.
"""
if hasattr(callback, 'actions'):
- return [method.upper() for method in callback.actions.keys()]
+ actions = set(callback.actions.keys())
+ http_method_names = set(callback.cls.http_method_names)
+ return [method.upper() for method in actions & http_method_names]
return [
method for method in
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -246,6 +246,11 @@ class PermissionDeniedExampleViewSet(ExampleViewSet):
permission_classes = [DenyAllUsingPermissionDenied]
+class MethodLimitedViewSet(ExampleViewSet):
+ permission_classes = []
+ http_method_names = ['get', 'head', 'options']
+
+
class ExampleListView(APIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
@@ -368,6 +373,61 @@ def test_schema_for_regular_views(self):
assert schema == expected
[email protected](coreapi, 'coreapi is not installed')
+class TestSchemaGeneratorWithMethodLimitedViewSets(TestCase):
+ def setUp(self):
+ router = DefaultRouter()
+ router.register('example1', MethodLimitedViewSet, base_name='example1')
+ self.patterns = [
+ url(r'^', include(router.urls))
+ ]
+
+ def test_schema_for_regular_views(self):
+ """
+ Ensure that schema generation works for ViewSet classes
+ with method limitation by Django CBV's http_method_names attribute
+ """
+ generator = SchemaGenerator(title='Example API', patterns=self.patterns)
+ request = factory.get('/example1/')
+ schema = generator.get_schema(Request(request))
+
+ expected = coreapi.Document(
+ url='http://testserver/example1/',
+ title='Example API',
+ content={
+ 'example1': {
+ 'list': coreapi.Link(
+ url='/example1/',
+ action='get',
+ fields=[
+ coreapi.Field('page', required=False, location='query', schema=coreschema.Integer(title='Page', description='A page number within the paginated result set.')),
+ coreapi.Field('page_size', required=False, location='query', schema=coreschema.Integer(title='Page size', description='Number of results to return per page.')),
+ coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.'))
+ ]
+ ),
+ 'custom_list_action': coreapi.Link(
+ url='/example1/custom_list_action/',
+ action='get'
+ ),
+ 'custom_list_action_multiple_methods': {
+ 'read': coreapi.Link(
+ url='/example1/custom_list_action_multiple_methods/',
+ action='get'
+ )
+ },
+ 'read': coreapi.Link(
+ url='/example1/{id}/',
+ action='get',
+ fields=[
+ coreapi.Field('id', required=True, location='path', schema=coreschema.String())
+ ]
+ )
+ }
+ }
+ )
+ assert schema == expected
+
+
@unittest.skipUnless(coreapi, 'coreapi is not installed')
class TestSchemaGeneratorWithRestrictedViewSets(TestCase):
def setUp(self):
| CoreAPI integration for ViewSets ignores http_method_names limits.
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework.
Pypi 3.5.3
- [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
a. Have attached project to highlight issue [Uses Python 3.5]
/api/SampleRouteLimited/ will show single method available
/schema/ shows all methods normal for a viewset
b. Alternatively use an existing viewset.
1. Limit viewset to a single method
i.e., http_method_names = ['get']
2. generate schema
## Expected behavior
Only show schema information for requested methods.
## Actual behavior
Returns information for all methods, even if not allowed.
[coreapi_test.zip](https://github.com/tomchristie/django-rest-framework/files/602205/coreapi_test.zip)
| `http_method_names` is an internal implementation detail and is not intended a documented way to restrict which methods may be applied. I would suggest either:
* Use `ReadOnlyModelViewSet`.
* Build your viewset explicitly only including the actions you want... http://www.django-rest-framework.org/api-guide/viewsets/#custom-viewset-base-classes
* Use permission classes to restrict access.
Hope that helps move things forward.
The best place to start with questions like this is usually the discussion group rather than the issue tracker.
All the best,
Tom
I'm having the same problem, the thing is that I'm excluding only **patch** in the ``http_method_names``. I'm still using the UpdateModelMixin but I only want the **update** not the **partial_update** method in the schema, because it's making swagger add the patch method that it's really not implemented in this view.
Reopening for further consideration. | 2017-04-19T03:50:37 |
encode/django-rest-framework | 5,131 | encode__django-rest-framework-5131 | [
"4989"
] | 996e58739831659fc78e1d66bdc87deafa727958 | diff --git a/rest_framework/filters.py b/rest_framework/filters.py
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -11,6 +11,7 @@
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.db.models.constants import LOOKUP_SEP
+from django.db.models.sql.constants import ORDER_PATTERN
from django.template import loader
from django.utils import six
from django.utils.encoding import force_text
@@ -268,7 +269,7 @@ def get_valid_fields(self, queryset, view, context={}):
def remove_invalid_fields(self, queryset, fields, view, request):
valid_fields = [item[0] for item in self.get_valid_fields(queryset, view, {'request': request})]
- return [term for term in fields if term.lstrip('-') in valid_fields]
+ return [term for term in fields if term.lstrip('-') in valid_fields and ORDER_PATTERN.match(term)]
def filter_queryset(self, request, queryset, view):
ordering = self.get_ordering(request, queryset, view)
| diff --git a/tests/test_filters.py b/tests/test_filters.py
--- a/tests/test_filters.py
+++ b/tests/test_filters.py
@@ -764,6 +764,23 @@ class OrderingListView(generics.ListAPIView):
{'id': 1, 'title': 'zyx', 'text': 'abc'},
]
+ def test_incorrecturl_extrahyphens_ordering(self):
+ class OrderingListView(generics.ListAPIView):
+ queryset = OrderingFilterModel.objects.all()
+ serializer_class = OrderingFilterSerializer
+ filter_backends = (filters.OrderingFilter,)
+ ordering = ('title',)
+ ordering_fields = ('text',)
+
+ view = OrderingListView.as_view()
+ request = factory.get('/', {'ordering': '--text'})
+ response = view(request)
+ assert response.data == [
+ {'id': 3, 'title': 'xwv', 'text': 'cde'},
+ {'id': 2, 'title': 'yxw', 'text': 'bcd'},
+ {'id': 1, 'title': 'zyx', 'text': 'abc'},
+ ]
+
def test_incorrectfield_ordering(self):
class OrderingListView(generics.ListAPIView):
queryset = OrderingFilterModel.objects.all()
@@ -883,6 +900,7 @@ class OrderingListView(generics.ListAPIView):
queryset = OrderingFilterModel.objects.all()
filter_backends = (filters.OrderingFilter,)
ordering = ('title',)
+
# note: no ordering_fields and serializer_class specified
def get_serializer_class(self):
| Should ignore any invalidly formed query parameters for OrderingFilter.
## 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 a ViewSet with an OrderingFilter and add a field to order on (field_name)
- Call the viewset with `?ordering=--field_name`
## Expected behavior
No ordering to be applied
## Actual behavior
Throws a 500 error because --field_name is passed to the queryset because over [here](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/filters.py#L268) an lstrip is done instead of just removing the first - character before validation.
| Any chance you could include the error traceback - it's not obvious to me on first sight what the issue is here.
@tomchristie the thing is the value minus lstrip('-') is matched against existing fields but it passed as it is to the queryset. Result being that:
- "--field_name".lstrip('-') -> field_name which is valid
- .order_by('--field_name') is not valid
Hey folks,
Wanted to contribute to the test cases.
Wanted to know if the expected behaviour mentioned in @hvdklauw above is correct.
And by that logic can we add an arbitrary number of hyphens?
@vimarshc iirc, the current logic is to discard invalid ordering fields. To keep consistent I believe that "--field_name" should be simply discarded. | 2017-05-11T08:13:37 |
encode/django-rest-framework | 5,138 | encode__django-rest-framework-5138 | [
"5137"
] | 003c3041152f7f8c60363924201b914bf94a83ee | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -1010,7 +1010,7 @@ def get_fields(self):
continue
extra_field_kwargs = extra_kwargs.get(field_name, {})
- source = extra_field_kwargs.get('source') or field_name
+ source = extra_field_kwargs.get('source', '*') != '*' or field_name
# Determine the serializer field class and keyword arguments.
field_class, field_kwargs = self.build_field(
| 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
@@ -524,6 +524,37 @@ class Meta:
""")
self.assertEqual(unicode_repr(TestSerializer()), expected)
+ def test_nested_hyperlinked_relations_starred_source(self):
+ class TestSerializer(serializers.HyperlinkedModelSerializer):
+ class Meta:
+ model = RelationalModel
+ depth = 1
+ fields = '__all__'
+
+ extra_kwargs = {
+ 'url': {
+ 'source': '*',
+ }}
+
+ expected = dedent("""
+ TestSerializer():
+ url = HyperlinkedIdentityField(source='*', view_name='relationalmodel-detail')
+ foreign_key = NestedSerializer(read_only=True):
+ url = HyperlinkedIdentityField(view_name='foreignkeytargetmodel-detail')
+ name = CharField(max_length=100)
+ one_to_one = NestedSerializer(read_only=True):
+ url = HyperlinkedIdentityField(view_name='onetoonetargetmodel-detail')
+ name = CharField(max_length=100)
+ many_to_many = NestedSerializer(many=True, read_only=True):
+ url = HyperlinkedIdentityField(view_name='manytomanytargetmodel-detail')
+ name = CharField(max_length=100)
+ through = NestedSerializer(many=True, read_only=True):
+ url = HyperlinkedIdentityField(view_name='throughtargetmodel-detail')
+ name = CharField(max_length=100)
+ """)
+ self.maxDiff = None
+ self.assertEqual(unicode_repr(TestSerializer()), expected)
+
def test_nested_unique_together_relations(self):
class TestSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
| ImproperlyConfigured: Field name `*` is not valid for model `MyModel` with source="*"
https://github.com/encode/django-rest-framework/pull/4688 causes
"ImproperlyConfigured: Field name `*` is not valid for model `MyModel`." when
using `source="*"`.
While DRF 3.6.2 passes `url` to `build_field`, where it gets handled via `build_url_field`, DRF 3.6.3 passes `source` (`*`) there instead.
I will provide a PR with a failing test and a possible fix.
| 2017-05-16T10:06:48 |
|
encode/django-rest-framework | 5,149 | encode__django-rest-framework-5149 | [
"5148"
] | 1ca5a9d042aeff9c768e82e7c40254476cbe88f0 | diff --git a/rest_framework/authtoken/serializers.py b/rest_framework/authtoken/serializers.py
--- a/rest_framework/authtoken/serializers.py
+++ b/rest_framework/authtoken/serializers.py
@@ -6,7 +6,11 @@
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField(label=_("Username"))
- password = serializers.CharField(label=_("Password"), style={'input_type': 'password'})
+ password = serializers.CharField(
+ label=_("Password"),
+ style={'input_type': 'password'},
+ trim_whitespace=False
+ )
def validate(self, attrs):
username = attrs.get('username')
| diff --git a/tests/test_authtoken.py b/tests/test_authtoken.py
--- a/tests/test_authtoken.py
+++ b/tests/test_authtoken.py
@@ -27,3 +27,9 @@ def test_token_string_representation(self):
def test_validate_raise_error_if_no_credentials_provided(self):
with pytest.raises(ValidationError):
AuthTokenSerializer().validate({})
+
+ def test_whitespace_in_password(self):
+ data = {'username': self.user.username, 'password': 'test pass '}
+ self.user.set_password(data['password'])
+ self.user.save()
+ assert AuthTokenSerializer(data=data).is_valid()
| AuthTokenSerializer trims whitespace from passwords
## 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
1. Create a user with a leading and/or trailing spaces in their password (`User.objects.create(username='foo', password='bar ')`)
1. Attempt to authenticate/validate the user through `AuthTokenSerializer` (`AuthTokenSerializer(data={'username': 'foo', 'password': 'bar '}).is_valid()`)
## Expected behavior
Validation succeeds
## Actual behavior
Validation fails
| 2017-05-17T18:54:20 |
|
encode/django-rest-framework | 5,229 | encode__django-rest-framework-5229 | [
"5228"
] | 506ec8594de292aa277fb40b3635522092e3945b | diff --git a/rest_framework/viewsets.py b/rest_framework/viewsets.py
--- a/rest_framework/viewsets.py
+++ b/rest_framework/viewsets.py
@@ -82,6 +82,10 @@ def view(request, *args, **kwargs):
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
+ self.request = request
+ self.args = args
+ self.kwargs = kwargs
+
# And continue as usual
return self.dispatch(request, *args, **kwargs)
| diff --git a/tests/test_viewsets.py b/tests/test_viewsets.py
--- a/tests/test_viewsets.py
+++ b/tests/test_viewsets.py
@@ -13,6 +13,15 @@ def list(self, request, *args, **kwargs):
return Response({'ACTION': 'LIST'})
+class InstanceViewSet(GenericViewSet):
+
+ def dispatch(self, request, *args, **kwargs):
+ return self.dummy(request, *args, **kwargs)
+
+ def dummy(self, request, *args, **kwargs):
+ return Response({'view': self})
+
+
class InitializeViewSetsTestCase(TestCase):
def test_initialize_view_set_with_actions(self):
request = factory.get('/', '', content_type='application/json')
@@ -42,3 +51,17 @@ def test_initialize_view_set_with_empty_actions(self):
"For example `.as_view({'get': 'list'})`")
else:
self.fail("actions must not be empty.")
+
+ def test_args_kwargs_request_action_map_on_self(self):
+ """
+ Test a view only has args, kwargs, request, action_map
+ once `as_view` has been called.
+ """
+ bare_view = InstanceViewSet()
+ view = InstanceViewSet.as_view(actions={
+ 'get': 'dummy',
+ })(factory.get('/')).data['view']
+
+ for attribute in ('args', 'kwargs', 'request', 'action_map'):
+ self.assertNotIn(attribute, dir(bare_view))
+ self.assertIn(attribute, dir(view))
| AttributeError on self.request, self.args and self.kwargs
## 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
Create a `ViewSet` and overwrite `dispatch` method and try to access one of `self.request`, `self.args` or `self.kwargs` before calling `super`
## Expected behavior
It should return the appropriate objects
## Actual behavior
It raises `AttributeError`
This should be related to this Django ticket https://code.djangoproject.com/ticket/19316 which was fixed before 5 years in Django 1.6 and backported to Django 1.5.
The solution is to set these in the decorator generated in `as_view` method as Django does (https://github.com/django/django/commit/ea6b95dbec77371d517392ffb465017b8eb7001c)
I can try to prepare a PR
| 2017-06-22T13:25:06 |
|
encode/django-rest-framework | 5,231 | encode__django-rest-framework-5231 | [
"5223"
] | 0dd3aa4126e5dcd8efdaaecda79681d4321e5977 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -791,13 +791,17 @@ def __init__(self, regex, **kwargs):
class SlugField(CharField):
default_error_messages = {
- 'invalid': _('Enter a valid "slug" consisting of letters, numbers, underscores or hyphens.')
+ 'invalid': _('Enter a valid "slug" consisting of letters, numbers, underscores or hyphens.'),
+ 'invalid_unicode': _('Enter a valid "slug" consisting of Unicode letters, numbers, underscores, or hyphens.')
}
- def __init__(self, **kwargs):
+ def __init__(self, allow_unicode=False, **kwargs):
super(SlugField, self).__init__(**kwargs)
- slug_regex = re.compile(r'^[-a-zA-Z0-9_]+$')
- validator = RegexValidator(slug_regex, message=self.error_messages['invalid'])
+ self.allow_unicode = allow_unicode
+ if self.allow_unicode:
+ validator = RegexValidator(re.compile(r'^[-\w]+\Z', re.UNICODE), message=self.error_messages['invalid_unicode'])
+ else:
+ validator = RegexValidator(re.compile(r'^[-a-zA-Z0-9_]+$'), message=self.error_messages['invalid'])
self.validators.append(validator)
| 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
@@ -275,13 +275,13 @@ def test_multipart_encoding(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
- temp = tempfile.NamedTemporaryFile()
- temp.write(b'example file content')
- temp.flush()
+ with tempfile.NamedTemporaryFile() as temp:
+ temp.write(b'example file content')
+ temp.flush()
+ temp.seek(0)
- with open(temp.name, 'rb') as upload:
- name = os.path.basename(upload.name)
- data = client.action(schema, ['encoding', 'multipart'], params={'example': upload})
+ name = os.path.basename(temp.name)
+ data = client.action(schema, ['encoding', 'multipart'], params={'example': temp})
expected = {
'method': 'POST',
@@ -407,13 +407,13 @@ def test_raw_upload(self):
client = CoreAPIClient()
schema = client.get('http://api.example.com/')
- temp = tempfile.NamedTemporaryFile()
- temp.write(b'example file content')
- temp.flush()
+ with tempfile.NamedTemporaryFile(delete=False) as temp:
+ temp.write(b'example file content')
+ temp.flush()
+ temp.seek(0)
- with open(temp.name, 'rb') as upload:
- name = os.path.basename(upload.name)
- data = client.action(schema, ['encoding', 'raw_upload'], params={'example': upload})
+ name = os.path.basename(temp.name)
+ data = client.action(schema, ['encoding', 'raw_upload'], params={'example': temp})
expected = {
'method': 'POST',
diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -704,6 +704,17 @@ class TestSlugField(FieldValues):
outputs = {}
field = serializers.SlugField()
+ def test_allow_unicode_true(self):
+ field = serializers.SlugField(allow_unicode=True)
+
+ validation_error = False
+ try:
+ field.run_validation(u'slug-99-\u0420')
+ except serializers.ValidationError:
+ validation_error = True
+
+ assert not validation_error
+
class TestURLField(FieldValues):
"""
| SlugField doesn't accept Unicode
## Steps to reproduce
The model has a SlugField with `allow_unicode=True`
```
class Person(models.Model):
name = models.SlugField(
allow_unicode=True,
max_length=155,
unique=True
)
```
The serializer is a `ModelSerializers`:
```
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('name', )
```
## Expected behavior
The serializer should accept unicode values just like the field on the model.
## Actual behavior
By passing `علیرضا` as value for `name` field, it fails.
The serializer print out the following error:
```
{'name`: ['Enter a valid "slug" consisting of letters, numbers, underscores or hyphens.']}
```
| +1 I'm having this problem now.
The initializer doesn't respect `allow_unicode` at all.
`serializers.SlugField` also adds its non-Unicode-aware `RegexValidator` even if custom `validators` were passed in which is pretty mean. https://github.com/encode/django-rest-framework/blob/master/rest_framework/fields.py#L800
PR welcomed :) | 2017-06-24T05:33:55 |
encode/django-rest-framework | 5,259 | encode__django-rest-framework-5259 | [
"5258"
] | 3dab9056567218c724200bfe6910e60958338e1e | diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py
--- a/rest_framework/renderers.py
+++ b/rest_framework/renderers.py
@@ -556,7 +556,10 @@ def get_raw_data_form(self, data, view, method, request):
accepted = self.accepted_media_type
context = self.renderer_context.copy()
context['indent'] = 4
- content = renderer.render(serializer.data, accepted, context)
+ data = {k: v for (k, v) in serializer.data.items()
+ if not isinstance(serializer.fields[k],
+ serializers.HiddenField)}
+ content = renderer.render(data, accepted, context)
else:
content = None
| HiddenField appears in Raw Data form initial content
## 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~~fix as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
- create a serializer with a HiddenField
- create a ModelViewSet referencing that serializer
- visit the URL corresponding to that ModelViewSet
- switch to the Raw Data tab and observe that the initial value of the Content textarea is a JSON instance that contains a key for the HiddenField
## Expected behavior
The initial value of the Content textarea is a template JSON instance that contains a key for the HiddenField.
## Actual behavior
The initial value of the Content textarea is a template JSON instance that does not contain a key for the HiddenField.
| 2017-07-08T05:33:42 |
||
encode/django-rest-framework | 5,261 | encode__django-rest-framework-5261 | [
"5239"
] | 3dab9056567218c724200bfe6910e60958338e1e | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1137,18 +1137,16 @@ def to_internal_value(self, value):
if input_format.lower() == ISO_8601:
try:
parsed = parse_datetime(value)
- except (ValueError, TypeError):
- pass
- else:
if parsed is not None:
return self.enforce_timezone(parsed)
+ except (ValueError, TypeError):
+ pass
else:
try:
parsed = self.datetime_parser(value, input_format)
+ return self.enforce_timezone(parsed)
except (ValueError, TypeError):
pass
- else:
- return self.enforce_timezone(parsed)
humanized_format = humanize_datetime.datetime_formats(input_formats)
self.fail('invalid', format=humanized_format)
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -5,6 +5,7 @@
import uuid
from decimal import Decimal
+import django
import pytest
from django.http import QueryDict
from django.test import TestCase, override_settings
@@ -1152,6 +1153,7 @@ class TestDateTimeField(FieldValues):
invalid_inputs = {
'abc': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'],
'2001-99-99T99:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'],
+ '2018-08-16 22:00-24:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'],
datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'],
}
outputs = {
@@ -1165,6 +1167,11 @@ class TestDateTimeField(FieldValues):
field = serializers.DateTimeField(default_timezone=utc)
+if django.VERSION[:2] <= (1, 8):
+ # Doesn't raise an error on earlier versions of Django
+ TestDateTimeField.invalid_inputs.pop('2018-08-16 22:00-24:00')
+
+
class TestCustomInputFormatDateTimeField(FieldValues):
"""
Valid and invalid values for `DateTimeField` with a custom input format.
| Issue 5220
## Description
The PR includes a testcase for issue #5220 as well as a preliminary fix. What that means is that the fix is working but I believe it could be done in a better way.
| 2017-07-10T09:15:08 |
|
encode/django-rest-framework | 5,262 | encode__django-rest-framework-5262 | [
"5209"
] | 39f6f1137cc8c351d982cb82c9b0134e89fcdf32 | diff --git a/rest_framework/request.py b/rest_framework/request.py
--- a/rest_framework/request.py
+++ b/rest_framework/request.py
@@ -250,6 +250,10 @@ def _load_data_and_files(self):
else:
self._full_data = self._data
+ # copy files refs to the underlying request so that closable
+ # objects are handled appropriately.
+ self._request._files = self._files
+
def _load_stream(self):
"""
Return the content body of the request, as a stream.
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -1144,7 +1144,7 @@ class TestDateTimeField(FieldValues):
valid_inputs = {
'2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc),
'2001-01-01T13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc),
- '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc)
+ '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc),
datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc),
datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc),
}
diff --git a/tests/test_request.py b/tests/test_request.py
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -3,6 +3,9 @@
"""
from __future__ import unicode_literals
+import os.path
+import tempfile
+
from django.conf.urls import url
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
@@ -120,11 +123,39 @@ def post(self, request):
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+class FileUploadView(APIView):
+ def post(self, request):
+ filenames = [file.temporary_file_path() for file in request.FILES.values()]
+
+ for filename in filenames:
+ assert os.path.exists(filename)
+
+ return Response(status=status.HTTP_200_OK, data=filenames)
+
+
urlpatterns = [
url(r'^$', MockView.as_view()),
+ url(r'^upload/$', FileUploadView.as_view())
]
+@override_settings(
+ ROOT_URLCONF='tests.test_request',
+ FILE_UPLOAD_HANDLERS=['django.core.files.uploadhandler.TemporaryFileUploadHandler'])
+class FileUploadTests(TestCase):
+
+ def test_fileuploads_closed_at_request_end(self):
+ with tempfile.NamedTemporaryFile() as f:
+ response = self.client.post('/upload/', {'file': f})
+
+ # sanity check that file was processed
+ assert len(response.data) == 1
+
+ for file in response.data:
+ assert not os.path.exists(file)
+
+
@override_settings(ROOT_URLCONF='tests.test_request')
class TestContentParsingWithAuthentication(TestCase):
def setUp(self):
| request.FILES close
Django closes transparently the elements of requests.FILES since https://github.com/django/django/pull/2747/ , but Django Rest Framework forgets doing so. In particular it leaves /tmp/*.upload files.
| Django REST framework system is built on top of Django's. Moreover, I've seen cases where test failed because the file was closed during the API call.
I'm closing the issue due to the lack of evidences.
Will reconsider with a failing test case we can reproduce.
[demo.zip](https://github.com/encode/django-rest-framework/files/1068133/demo.zip)
Here `curl -F file=@/tmp/fff http://localhost:8080/A/` does not leave /tmp/.....upload file, but `curl -F file=@/tmp/fff http://localhost:8080/Z/` leaves.
Note `FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.TemporaryFileUploadHandler']`
Hi @dilyanpalauzov - the demo definitely demonstrates that temporary files remain after the request has been processed by DRF. DRF's stream processing is preempting Django's own data/files handling, so the underlying Django request object doesn't have any `_files` to close.
Would you be willing to open a PR with a failing test case?
I do not have the time to delve how to write test cases. | 2017-07-10T10:32:41 |
encode/django-rest-framework | 5,264 | encode__django-rest-framework-5264 | [
"4655"
] | 6d4d4dfd046e85253194f6bfe33574c080abf432 | diff --git a/rest_framework/filters.py b/rest_framework/filters.py
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -140,12 +140,14 @@ def filter_queryset(self, request, queryset, view):
]
base = queryset
+ conditions = []
for search_term in search_terms:
queries = [
models.Q(**{orm_lookup: search_term})
for orm_lookup in orm_lookups
]
- queryset = queryset.filter(reduce(operator.or_, queries))
+ conditions.append(reduce(operator.or_, queries))
+ queryset = queryset.filter(reduce(operator.and_, conditions))
if self.must_call_distinct(queryset, search_fields):
# Filtering against a many-to-many field requires us to
| 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 warnings
from decimal import Decimal
+import django
import pytest
from django.conf.urls import url
from django.core.exceptions import ImproperlyConfigured
@@ -645,6 +646,51 @@ def test_must_call_distinct(self):
)
+class Blog(models.Model):
+ name = models.CharField(max_length=20)
+
+
+class Entry(models.Model):
+ blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
+ headline = models.CharField(max_length=120)
+ pub_date = models.DateField(null=True)
+
+
+class BlogSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Blog
+ fields = '__all__'
+
+
+class SearchFilterToManyTests(TestCase):
+
+ @classmethod
+ def setUpTestData(cls):
+ b1 = Blog.objects.create(name='Blog 1')
+ b2 = Blog.objects.create(name='Blog 2')
+
+ # Multiple entries on Lennon published in 1979 - distinct should deduplicate
+ Entry.objects.create(blog=b1, headline='Something about Lennon', pub_date=datetime.date(1979, 1, 1))
+ Entry.objects.create(blog=b1, headline='Another thing about Lennon', pub_date=datetime.date(1979, 6, 1))
+
+ # Entry on Lennon *and* a separate entry in 1979 - should not match
+ Entry.objects.create(blog=b2, headline='Something unrelated', pub_date=datetime.date(1979, 1, 1))
+ Entry.objects.create(blog=b2, headline='Retrospective on Lennon', pub_date=datetime.date(1990, 6, 1))
+
+ @unittest.skipIf(django.VERSION < (1, 9), "Django 1.8 does not support transforms")
+ def test_multiple_filter_conditions(self):
+ class SearchListView(generics.ListAPIView):
+ queryset = Blog.objects.all()
+ serializer_class = BlogSerializer
+ filter_backends = (filters.SearchFilter,)
+ search_fields = ('=name', 'entry__headline', '=entry__pub_date__year')
+
+ view = SearchListView.as_view()
+ request = factory.get('/', {'search': 'Lennon,1979'})
+ response = view(request)
+ assert len(response.data) == 1
+
+
class OrderingFilterModel(models.Model):
title = models.CharField(max_length=20, verbose_name='verbose title')
text = models.CharField(max_length=100)
| SearchFilter time grows exponentially by # of search terms
## 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
Use `filters.SearchFilter` and include a seach_field which is a many to many lookup.
```
filter_backends = (filters.SearchFilter)
search_fields = ('many__to__many__field')
```
Make a query against this view with several search terms.
## Expected behavior
The search time would increase somewhat linearly with the # of terms.
## Actual behavior
The search grows exponentially with each added term. In our application several words (3) resulted in a 30 sec query against a model that only had several hundred entries. It would take several minutes for another term and so on.
## Summary
I was able to change a single block in drf and the performance became linear as I would expect. The problem and (a potential) solution are known. I wanted to bring them to your attention.
## The culprit
Chaining filters in `django` on querysets doesn't behave as one would expect when dealing with ManyToMany relations. If you look at the gist below, you'll see that the second bit of sql is quite different from the first bit because of this difference.
https://gist.github.com/cdosborn/cb4bdfd0467feaf987476f4aefdf7ee5
From looking at the sql, you'll notice the first bit generated a bunch of unnecessary joins. These joins result in a multiplicative factor on the number of rows that the query contains. Notice how the bottom query doesn't have the redundant joins. So what we can conclude is that chaining filters can produce unnecessary joins which can dramatically effect the performance.
So there is a bit of code in drf, which chains `filter` for each term in the search query. This explodes whenever the `search_fields` contains a ManyToMany.
## A solution
Rather than chaining filters in `SearchFilter` we build up a query first, and call `filter` once.
```diff
diff --git a/rest_framework/filters.py b/rest_framework/filters.py
index 531531e..0e7329b 100644
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -144,13 +144,15 @@ class SearchFilter(BaseFilterBackend):
]
base = queryset
+ conditions = []
for search_term in search_terms:
queries = [
models.Q(**{orm_lookup: search_term})
for orm_lookup in orm_lookups
]
- queryset = queryset.filter(reduce(operator.or_, queries))
+ conditions.append(reduce(operator.or_, queries))
+ queryset = queryset.filter(reduce(operator.and_, conditions))
if self.must_call_distinct(queryset, search_fields):
# Filtering against a many-to-many field requires us to
# call queryset.distinct() in order to avoid duplicate items
```
This may not be the fix you want. My guess is that the `must_call_distinct` was trying to fix this problem, but it's not sufficient. My impression is that this is a pretty serious issue that django needs to resolve.
| These [docs](https://docs.djangoproject.com/en/1.10/topics/db/queries/#spanning-multi-valued-relationships) are relevant here. At the end of the day, you're getting two different queries that return two completely different sets of results. Regardless of performance, I'd argue that the proposed changes are more correct.
Would you like me to submit a PR?
Some thoughts:
Can self.must_call_distinct be removed?
Should probably search for similar uses of filter.
How should we address that this is something django should fix or provide a workaround for (normally I'd inline a comment including a link to the [discussion](https://code.djangoproject.com/ticket/27303)).
> How should we address that this is something django should fix or provide a workaround for
If you believe this represents an issue in Django core then raise a ticket on Trac. It'd be worth reviewing what happens in the admin, and if this is replicable in the the search there too. I'd be surprised if the issue hadn't already come up before _if_ that's the case.
> Can self.must_call_distinct be removed?
Start by seeing what tests fail if you do remove it. We can then take the conversation from there.
In the past we have similar problem with a pure django project (not using django rest framework at all). We used django-tagging and searched in the tags (which are many to many to the object). We used MySQL for database engine and when query string in our form contained a lot of words then MySQL raised that it can not join more than 40 tables (or 41 I can't remember exactly).
We fixed that by using Q objects and `or`-ing them instead of the querysets.
@rpkilby yes at the end you have two different SQL queries but you still have the same results set because you are using `or` and not `and`. In the django docs that you linked they write about using `and` with many to many relations.
@cdosborn
About `self.must_call_distinct` it should not be removed. Everytime when you perform query against reverse relation (many to many is de facto reverse relation from both ends) you should call `distinct()` or you will have duplicates. The only exception is when the reverse relation is one to one.
> @rpkilby yes at the end you have two different SQL queries but you still have the same results set because you are using `or` and not `and`.
@vstoykov - The search *fields* per term are grouped together with `or`, however each group is `and`ed together. For example, take `ordering_fields = ('name', 'groups__name')` and this query:
```http
GET https://localhost/api/users?search=bob,joe
```
With the existing implementation, we should get a queryset equivalent to the following:
```python
User.objects \
.filter(Q(name__icontains='bob') | Q(groups__name__icontains='bob') \
.filter(Q(name__icontains='joe') | Q(groups__name__icontains='joe')
```
The proposed changes would result in this query:
```python
User.objects.filter((Q(name__icontains='bob') | Q(groups__name__icontains='bob'))
& (Q(name__icontains='joe') | Q(groups__name__icontains='joe')))
```
I'd have to double check, but this seems to fall under the caveats described in the docs.
@rpkilby Sorry I totally missed `operator.and_` in:
```
queryset = queryset.filter(reduce(operator.and_, conditions))
```
This will make the situation complex. On one hand the search need to return as many as possible matching results, on other hand it should not DOS the application.
Probably there should be something that can configure this (`SearchFilter`'s argument, or separate class which developers can use) and mentioning in documentation what are the differences and then each project developer will decide which variant to use.
From one point of view, the current behavior is a bug w.r.t to handling m2m. From the [docs](http://www.django-rest-framework.org/api-guide/filtering/#searchfilter):
> If multiple search terms are used then objects will be returned in the list only if **all the provided terms are matched**.
As you mentioned, if we went ahead with the changes, then applications would see fewer results.
Hey folks,
Wanted to inquire if these changes have been tested by anyone?
I wanted to override the SearchFilter class and add the changes to speed up M2M searches.
@vimarshc You may use [this](https://github.com/cyverse/atmosphere/blob/6ef13abb9e20a241bf5c7e68e790e02f4f1f761c/api/v2/views/image.py#L12-L43) as a reference. We monkey-patched the search filter for the mean time.
If anyone wants to progress this issue, I'd suggest making a pull request so we can look at the effects of this change on the current test suite, which would help highlight any problems it might have. | 2017-07-10T18:26:39 |
encode/django-rest-framework | 5,344 | encode__django-rest-framework-5344 | [
"5340"
] | d2286ba658f905bda3e7b1cade6f0caa0fedc4ee | 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.6.3'
+__version__ = '3.6.4'
__author__ = 'Tom Christie'
__license__ = 'BSD 2-Clause'
__copyright__ = 'Copyright 2011-2017 Tom Christie'
| 3.6.4 Release
Checklist:
- [x] Create pull request for [release notes](https://github.com/tomchristie/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [3.6.4 milestone](https://github.com/tomchristie/django-rest-framework/milestones/***). PR: #5344
- [x] Bump remaining unclosed issues.
- [x] Update the translations from [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).
- [x] Ensure the pull request increments the version to `3.6.4` in [`restframework/__init__.py`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/__init__.py).
- [x] Confirm with @tomchristie that release is finalized and ready to go.
- [x] Ensure that release date is included in pull request.
- [x] Merge the release pull request.
- [x] Push the package to PyPI with `./setup.py publish`.
- [x] Tag the release, with `git tag -a 3.6.4 -m 'version 3.6.4'; git push --tags`.
- [x] Deploy the documentation with `mkdocs gh-deploy`.
- [x] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).
- [x] Make a release announcement on twitter.
- [x] Close the milestone on GitHub.
| Target for this is over-the-weekend, possibly into Monday. | 2017-08-21T09:51:05 |
|
encode/django-rest-framework | 5,348 | encode__django-rest-framework-5348 | [
"4585"
] | fed85bc29d7965749e86ee86c63d140f2e50e843 | diff --git a/rest_framework/permissions.py b/rest_framework/permissions.py
--- a/rest_framework/permissions.py
+++ b/rest_framework/permissions.py
@@ -122,6 +122,9 @@ def has_permission(self, request, view):
if hasattr(view, 'get_queryset'):
queryset = view.get_queryset()
+ assert queryset is not None, (
+ '{}.get_queryset() returned None'.format(view.__class__.__name__)
+ )
else:
queryset = getattr(view, 'queryset', None)
| Unrelated assert error message when there is an error in get_queryset
In a view, I have define a `get_queryset` method in a `APIView` derived class. For some (not important) reasons, I have made a mistake in my code, but the error message I get is unrelated to the actual mistake: it is an `AssertError`, complaining there is no `.queryset` attribute or `get_queryset` method in the view. And the traceback does only imply files of the framework, not files I haver written and, obviously, neither the file I have made the mistake in.
## Steps to reproduce
Create a class in `views.py`, deriving from `APIView`. Define a `get_queryset` method with a mistake in it, ~~say an `IndexError`.~~ the method do not return anything. Run it.
## Txpected behavior
~~Get an error message involving an `IndexError`.~~
Get an error message about the empty return of `get_queryset`.
## Actual behavior
Get an error message related to an `AssertError`.
| Hi there, this feels like a chat I had at pycon.fr. Was it with you ?
That put appart, you need to provide a queryset for the view to work with routers, whether or not you override get_queryset. Will send more informations once I can use my computer.
Meanwhile I'm keeping this opened as we may have a documentation issue here
Yep, that is me.
I am following the [doc](http://www.django-rest-framework.org/api-guide/filtering/) about this.
I will give you a MWE to locate the problem more precisely.
Thanks for raising it :)
I managed to reproduce on the train back home.
We have an inconsistence here.
There's [a word in the documentation](http://www.django-rest-framework.org/api-guide/permissions/#using-with-views-that-do-not-include-a-queryset-attribute) about using permissions with views that don't have a `queryset` attribute but looking at the code, [permission are using `get_queryset`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/permissions.py#L119) [several times](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/permissions.py#L175)
I don't see a reason why routers don't use `get_queryset` instead of `queryset`. So, we'll need a PR to fix the permission documentation and one to let routers use `get_queryset` like permissions do.
I'm having hard time here and disgressing, sorry about that.
This issue is about getting rid of the assert message in favor of the initial exception within `get_queryset` right ?
> I don't see a reason why routers don't use get_queryset instead of queryset.
There's a good chance that if someone is overriding `get_queryset`, they are relying on something being set (the view object, request, etc.) that cannot normally be set without going through the view lifecycle. By using the `queryset` argument, it allows us to quickly get a queryset (even if it's an empty queryset, like `Model.objects.none()`) without having to prepare the view every time.
@kevin-brown good catch, thanks a lot for your feedback. That point will be solved by adding some words in the documentation.
It seems that the problem I tried to describe is far less systematic than I thought... Raising an exception is not enough for poping an `AssertError` instead. And I didn't took note of what I was doing precisely when facing this problem.
However, I think I have isolated one form of it: if (for some dumb reasons), the `get_queryset` method _did not return_ anything, I get:
```
AssertionError at /some/place
Cannot apply DjangoModelPermissions on a view that does not have `.queryset` property or overrides the `.get_queryset()` method.
```
It does not complain `get_queryset` did not return anything (which is the real problem), the error message is pretty confusing and the traceback does not involve files of my project.
> It does not complain get_queryset did not return anything (which is the real problem), the error message is pretty confusing.
Okay, that's a nicely isolated bit of behavior that'd be worth addressing. Let's constrain this issue to just that particular aspect, at least for now.
| 2017-08-22T14:09:08 |
|
encode/django-rest-framework | 5,351 | encode__django-rest-framework-5351 | [
"5349"
] | bafb3ec22a8d26f525ce6d3b2e66914ccfbbafec | diff --git a/rest_framework/request.py b/rest_framework/request.py
--- a/rest_framework/request.py
+++ b/rest_framework/request.py
@@ -303,7 +303,7 @@ def _parse(self):
stream = None
if stream is None or media_type is None:
- if media_type and not is_form_media_type(media_type):
+ if media_type and is_form_media_type(media_type):
empty_data = QueryDict('', encoding=self._request._encoding)
else:
empty_data = {}
| diff --git a/rest_framework/test.py b/rest_framework/test.py
--- a/rest_framework/test.py
+++ b/rest_framework/test.py
@@ -227,6 +227,15 @@ def options(self, path, data=None, format=None, content_type=None, **extra):
data, content_type = self._encode_data(data, format, content_type)
return self.generic('OPTIONS', path, data, content_type, **extra)
+ def generic(self, method, path, data='',
+ content_type='application/octet-stream', secure=False, **extra):
+ # Include the CONTENT_TYPE, regardless of whether or not data is empty.
+ if content_type is not None:
+ extra['CONTENT_TYPE'] = str(content_type)
+
+ return super(APIRequestFactory, self).generic(
+ method, path, data, content_type, secure, **extra)
+
def request(self, **kwargs):
request = super(APIRequestFactory, self).request(**kwargs)
request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
diff --git a/tests/test_testing.py b/tests/test_testing.py
--- a/tests/test_testing.py
+++ b/tests/test_testing.py
@@ -274,3 +274,12 @@ def test_request_factory_url_arguments_with_unicode(self):
assert dict(request.GET) == {'demo': ['testé']}
request = factory.get('/view/', {'demo': 'testé'})
assert dict(request.GET) == {'demo': ['testé']}
+
+ def test_empty_request_content_type(self):
+ factory = APIRequestFactory()
+ request = factory.post(
+ '/post-view/',
+ data=None,
+ content_type='application/json',
+ )
+ assert request.META['CONTENT_TYPE'] == 'application/json'
| returning QueryDict with content-type application/json and empty body
## 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
Hi, is this line correct? 5677d06#diff-6dc9b019ec1d96c56e0e31dac3bba51cR302
This line of code was added at this pull request.
if media_type and not is_form_media_type(media_type):
empty_data = QueryDict('', encoding=self._request._encoding)
else:
empty_data = {}
## Expected behavior
I suppose returning QueryDict should be only for form data type, not for application/json.
## Actual behavior
In my case I was sending empty request with content-type application/json and received immutable QueryDict(). Is this correct behaviour?
| Hi @Reskov. Yep - I think you're correct here. The condition should be
```python
# this
if media_type and is_form_media_type(media_type):
...
# not this
if media_type and not is_form_media_type(media_type):
...
```
I did a little debugging, and it looks like the test client isn't setting the request's `content_type`. Because of this, the condition fails on the first part of the expression and not on the `is_form_media_type` check.
Digging further, this is a behavior of Django's builtin `RequestFactory`. The `Content-Type` header is only set if data is [provided](https://github.com/django/django/blob/1.11/django/test/client.py#L402-L407).
----
~~To be more explicit, this is an inconsistency between actual clients and the test client. It is possible for a client to specify a `Content-Type` without providing a message. Django's request factory will not set the header if no data is present.~~
| 2017-08-22T19:08:59 |
encode/django-rest-framework | 5,375 | encode__django-rest-framework-5375 | [
"5371"
] | 7e3ba8b3ed5e89b79447594b4143839aacff1d0c | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -93,9 +93,6 @@ def get_attribute(instance, attrs):
Also accepts either attribute lookup on objects or dictionary lookups.
"""
for attr in attrs:
- if instance is None:
- # Break out early if we get `None` at any point in a nested lookup.
- return None
try:
if isinstance(instance, collections.Mapping):
instance = instance[attr]
| diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -411,6 +411,19 @@ def test_default_not_used_when_in_object(self):
serializer = self.Serializer(instance)
assert serializer.data == {'has_default': 'def', 'has_default_callable': 'ghi', 'no_default': 'abc'}
+ def test_default_for_source_source(self):
+ """
+ 'default="something"' should be used when a traversed attribute is missing from input.
+ """
+ class Serializer(serializers.Serializer):
+ traversed = serializers.CharField(default='x', source='traversed.attr')
+
+ assert Serializer({}).data == {'traversed': 'x'}
+ assert Serializer({'traversed': {}}).data == {'traversed': 'x'}
+ assert Serializer({'traversed': None}).data == {'traversed': 'x'}
+
+ assert Serializer({'traversed': {'attr': 'abc'}}).data == {'traversed': 'abc'}
+
class TestCacheSerializerData:
def test_cache_serializer_data(self):
| dotted source on CharField returns null from to_representation when allow_null=False
## 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 PersonSerializer(serializers.Serializer):
moms_name = serializers.CharField(
allow_blank=True,
allow_null=False,
default='',
required=False,
source='mom_props.name'
)
```
The instance passed to the PersonSerializer may or may not have a mom_props model relationship in the database so getting the dotted source path may raise an ObjectDoesNotExist.
## Expected behavior
If mom_props.name were to return None or an ObjectDoesNotExist because in the case of django related models the mom_props model doesn't exist then moms_name should be an empty string in the output of `to_representation`
## Actual behavior
None or null is returned instead. This is inconsistent behavior for my api consumers since moms_name returns null but null is not a valid value ever for the property. If they turn around & submit the data back then they will get a validiationerror from the data I just sent them. This is probably related to #2299 but couldn't a better default be chosen in the case of CharFields with allow_blank=True & allow_null=False?
It's also quite likely I'm doing something really dumb but what I'm trying to accomplish is a mashup of multiple django models into a single serializer so my api consumers can interact with the data more easily without having to know or care about my backend schema. Pretty common I'm sure so it's more of a flattened serializer with a not flat database schema.
Everything works great when writing & naturally I've overridden the `create` & `update` methods & elected to be more explicit using the Serializer class instead of a ModelSerializer so it's more clear what is the API's responsibilty & what is the ORM's.
Finally, the part of the code base I think would need to be tweaked is:
https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L492-L501
| Hi,
`allow_null` is only used for deserialization purposes. It's up to the developer to provide correct data for serialization as DRF will not perform check against since it's already supposed to be sane.
Is default only used for deserialization too? The docs say:
> When serializing the instance, default will be used if the the object attribute or dictionary key is not present in the instance.
@xordoquy - reopening this, since this seems like an edge case bug. It looks like serialization's `default` handling doesn't traverse relationships. As a quick test, I ran the following:
```python
class Serializer(serializers.Serializer):
bar = serializers.CharField(
allow_blank=True,
allow_null=False,
default="",
required=False,
source='foo.bar')
>>> Serializer({}).data
ReturnDict([('bar', '')])
>>> Serializer({'foo': {}}).data
ReturnDict([('bar', '')])
>>> Serializer({'foo': None}).data
ReturnDict([('bar', None)])
```
Thanks. What you just showed is what I experience as well.
Would you like me to update the issue description to better reflect default="" with dotted field sources serializes to null instead of empty string? | 2017-08-30T18:14:20 |
encode/django-rest-framework | 5,388 | encode__django-rest-framework-5388 | [
"5389"
] | 79be20a7c68e7c90dd4d5d23a9e6ee08b5f586ae | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -1010,7 +1010,9 @@ def get_fields(self):
continue
extra_field_kwargs = extra_kwargs.get(field_name, {})
- source = extra_field_kwargs.get('source', '*') != '*' or field_name
+ source = extra_field_kwargs.get('source', '*')
+ if source == '*':
+ source = field_name
# Determine the serializer field class and keyword arguments.
field_class, field_kwargs = self.build_field(
| 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
@@ -1135,3 +1135,24 @@ class Meta:
serializer = TestUniqueChoiceSerializer(data={'name': 'choice1'})
assert not serializer.is_valid()
assert serializer.errors == {'name': ['unique choice model with this name already exists.']}
+
+
+class TestFieldSource(TestCase):
+ def test_named_field_source(self):
+ class TestSerializer(serializers.ModelSerializer):
+
+ class Meta:
+ model = RegularFieldsModel
+ fields = ('number_field',)
+ extra_kwargs = {
+ 'number_field': {
+ 'source': 'integer_field'
+ }
+ }
+
+ expected = dedent("""
+ TestSerializer():
+ number_field = IntegerField(source='integer_field')
+ """)
+ self.maxDiff = None
+ self.assertEqual(unicode_repr(TestSerializer()), expected)
| ModelSerializer custom named field source evaluates to True instead of field_name
## 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
1. Create a `ModelSerializer` including a field in `Meta` with a custom name (that isn't on the model).
2. Set the source of the field, in `extra_kwargs` to a named field within the model.
3. Initialise the Serializer.
## Expected behavior
- Creates a Serializer with a field with a custom field name, that has it's source as the specified field on the Model.
## Actual behavior
- `TypeError: hasattr(): attribute name must be string`
Caused by #5138 when accounting for `*`-sourced fields.
https://github.com/encode/django-rest-framework/blob/79be20a7c68e7c90dd4d5d23a9e6ee08b5f586ae/rest_framework/serializers.py#L1013
In the case that `source` is specified AND is not `'*'`,
`extra_field_kwargs.get('source', '*') != '*'` evaluates to `True`, and thus `source = True`,
leading to the `TypeError`
Pull Request with test that fails on master, and fix: #5388
| 2017-09-04T14:54:53 |
|
encode/django-rest-framework | 5,421 | encode__django-rest-framework-5421 | [
"5240"
] | d54df8c438d224616a8bcd745589b65e16db0989 | 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
@@ -207,7 +207,7 @@ def get_description(self, path, method):
return formatting.dedent(smart_text(method_docstring))
description = view.get_view_description()
- lines = [line.strip() for line in description.splitlines()]
+ lines = [line for line in description.splitlines()]
current_section = ''
sections = {'': ''}
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -15,6 +15,7 @@
AutoSchema, ManualSchema, SchemaGenerator, get_schema_view
)
from rest_framework.test import APIClient, APIRequestFactory
+from rest_framework.utils import formatting
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
@@ -577,3 +578,38 @@ class CustomView(APIView):
view = CustomView()
link = view.schema.get_link(path, method, base_url)
assert link == expected
+
+
+def test_docstring_is_not_stripped_by_get_description():
+ class ExampleDocstringAPIView(APIView):
+ """
+ === title
+
+ * item a
+ * item a-a
+ * item a-b
+ * item b
+
+ - item 1
+ - item 2
+
+ code block begin
+ code
+ code
+ code
+ code block end
+
+ the end
+ """
+
+ def get(self, *args, **kwargs):
+ pass
+
+ def post(self, request, *args, **kwargs):
+ pass
+
+ view = ExampleDocstringAPIView()
+ schema = view.schema
+ descr = schema.get_description('example', 'get')
+ # the first and last character are '\n' correctly removed by get_description
+ assert descr == formatting.dedent(ExampleDocstringAPIView.__doc__[1:][:-1])
| SchemaGenerator:get_description break markdown syntax
This shema using for django-rest-swagger
[This](https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas.py#L479) code delete start/end spaces in descriptions.
```
lines = [line.strip() for line in description.splitlines()]
```
But spaces is a part markdown syntax!
Where is it important:
- list
- sublist
```
- list
- sublist
```
code
```
code
```
| Yep. This seems valid.
[`get_view_description` already handles `dedent`-ing](https://github.com/encode/django-rest-framework/blob/master/rest_framework/views.py#L51), so is this doing anything here?
@aklim007: a failing test case with your example would be a good start to a PR here. ;-) | 2017-09-14T09:34:17 |
encode/django-rest-framework | 5,435 | encode__django-rest-framework-5435 | [
"5408",
"3732"
] | c0a48622e150badb5440792d3e4b7cb3568a2147 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1125,7 +1125,9 @@ def enforce_timezone(self, value):
"""
field_timezone = getattr(self, 'timezone', self.default_timezone())
- if (field_timezone is not None) and not timezone.is_aware(value):
+ if field_timezone is not None:
+ if timezone.is_aware(value):
+ return value.astimezone(field_timezone)
try:
return timezone.make_aware(value, field_timezone)
except InvalidTimeError:
@@ -1135,7 +1137,7 @@ def enforce_timezone(self, value):
return value
def default_timezone(self):
- return timezone.get_default_timezone() if settings.USE_TZ else None
+ return timezone.get_current_timezone() if settings.USE_TZ else None
def to_internal_value(self, value):
input_formats = getattr(self, 'input_formats', api_settings.DATETIME_INPUT_FORMATS)
@@ -1174,6 +1176,7 @@ def to_representation(self, value):
return 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
@@ -10,12 +10,17 @@
from django.http import QueryDict
from django.test import TestCase, override_settings
from django.utils import six
-from django.utils.timezone import utc
+from django.utils.timezone import activate, deactivate, utc
import rest_framework
from rest_framework import compat, serializers
from rest_framework.fields import is_simple_callable
+try:
+ import pytz
+except ImportError:
+ pytz = None
+
try:
import typings
except ImportError:
@@ -1168,7 +1173,7 @@ class TestDateTimeField(FieldValues):
datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'],
}
outputs = {
- datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00',
+ datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00Z',
datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc): '2001-01-01T13:00:00Z',
'2001-01-01T00:00:00': '2001-01-01T00:00:00',
six.text_type('2016-01-10T00:00:00'): '2016-01-10T00:00:00',
@@ -1230,10 +1235,59 @@ class TestNaiveDateTimeField(FieldValues):
'2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00),
}
invalid_inputs = {}
- outputs = {}
+ outputs = {
+ datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00',
+ datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc): '2001-01-01T13:00:00',
+ }
field = serializers.DateTimeField(default_timezone=None)
[email protected](pytz is None, reason='pytz not installed')
+class TestTZWithDateTimeField(FieldValues):
+ """
+ Valid and invalid values for `DateTimeField` when not using UTC as the timezone.
+ """
+ @classmethod
+ def setup_class(cls):
+ # use class setup method, as class-level attribute will still be evaluated even if test is skipped
+ kolkata = pytz.timezone('Asia/Kolkata')
+
+ cls.valid_inputs = {
+ '2016-12-19T10:00:00': kolkata.localize(datetime.datetime(2016, 12, 19, 10)),
+ '2016-12-19T10:00:00+05:30': kolkata.localize(datetime.datetime(2016, 12, 19, 10)),
+ datetime.datetime(2016, 12, 19, 10): kolkata.localize(datetime.datetime(2016, 12, 19, 10)),
+ }
+ cls.invalid_inputs = {}
+ cls.outputs = {
+ datetime.datetime(2016, 12, 19, 10): '2016-12-19T10:00:00+05:30',
+ datetime.datetime(2016, 12, 19, 4, 30, tzinfo=utc): '2016-12-19T10:00:00+05:30',
+ }
+ cls.field = serializers.DateTimeField(default_timezone=kolkata)
+
+
[email protected](pytz is None, reason='pytz not installed')
+@override_settings(TIME_ZONE='UTC', USE_TZ=True)
+class TestDefaultTZDateTimeField(TestCase):
+ """
+ Test the current/default timezone handling in `DateTimeField`.
+ """
+
+ @classmethod
+ def setup_class(cls):
+ cls.field = serializers.DateTimeField()
+ cls.kolkata = pytz.timezone('Asia/Kolkata')
+
+ def test_default_timezone(self):
+ assert self.field.default_timezone() == utc
+
+ def test_current_timezone(self):
+ assert self.field.default_timezone() == utc
+ activate(self.kolkata)
+ assert self.field.default_timezone() == self.kolkata
+ deactivate()
+ assert self.field.default_timezone() == utc
+
+
class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues):
"""
Invalid values for `DateTimeField` with datetime in DST shift (non-existing or ambiguous) and timezone with DST.
| Fix timezone handling for DateTimeField
This should fix #3732, as well as the current/active timezone handling [mentioned](https://github.com/encode/django-rest-framework/issues/3732#issuecomment-326865278) by @RichardForshaw.
Serializer DateTimeField has unexpected timezone information
I have `TIME_ZONE = 'Asia/Kolkata'` and `USE_TZ = True` in my settings.
When I create a new object with the browsable api, the serializer displays the newly created object with datetimes that have a trailing `+5:30`, indicating the timezone. The database is storing the times in UTC.
The unexpected behavior is that when the object is serialized again later, the datetimes are all in UTC format with a trailing `Z`. According to the Django docs on current and default time zone, I would expect the serializer to convert the datetimes to the current time zone, which defaults to the default time zone, which is set by `TIME_ZONE = 'Asia/Kolkata'`.
Am I missing something?
|
[I asked on stack overflow](http://stackoverflow.com/questions/34275588/djangorestframework-modelserializer-datetimefield-only-converting-to-current-tim) and the conclusion is that the current timezone is only used for user-provided datetimes, as the datetime is serialized as-is after validation (ie after create or update). From the Django documentation, I find it hard to believe that this is intended behavior, but this is an issue with Django itself rather than the Rest Framework, so I will close this issue.
Hi @tomchristie ,
I think this is a DRF bug.
IMHO, the natural use of DRF is to use it as an output like a django templating.
In a django template the timezone is correctly showed, why the drf serializer do not respects the django timezone setting?
Hi,
looking into the code in `fields.py` at `DatetimeField` class I discover that Django timezone setting is well considered only for the internal value (`to_internal_value()`).
I have seen that using model serializer like this:
```
class MyModelSerializer(ModelSerializer):
class Meta:
model = MyModel
depth = 1
fields = ('some_field', 'my_date_time_field')
```
for the field `my_date_time_field` (that i think it's a DateTimeField :) ) the timezone for the representation is None for default (`to_representation()`).
In otherwords, if I'm not wrong, the Django timezone is considered only when the value is wrote into the storage backend.
IMHO I think the return value of `to_representation()` should be like this:
`return self.enforce_timezone(value).strftime(output_format)`
according to the Django `USE_TZ` setting.
I write a pull request for this.
Ciao
Valentino
@vpistis It'd be easier to review this if you could give an example of the API behavior you currently see, and what you'd expect to see (rather than discussing the implementation aspects first)
Set your `TIME_ZONE = 'Asia/Kolkata'` and create a model serializer with a single datetime field, `appointment`.
During create/update, send:
```
{
"appointment": "2016-12-19T10:00:00"
}
```
and get back:
```
{
"appointment": "2016-12-19T10:00:00+5:30"
}
```
But if you retrieve or list that object again, you get:
```
{
"appointment": "2016-12-19T04:30:00Z"
}
```
During creation, if the Z isn't specified, DRF assumes the client is using the timezone specified by `TIME_ZONE` and returns a time formatted to that timezone (by adding the `+5:30` at the end, which would actually be invalid if it were a client-provided time). It would probably make more sense if future accesses also returned a time formatted to that timezone, so the response during retrieval/list were the same as during create/update.
There is also the question of whether to return times in the configured timezone when the trailing Z is provided during creation/update, such that sending:
```
{
"appointment": "2016-12-19T04:30:00Z"
}
```
returns:
```
{
"appointment": "2016-12-19T10:00:00+5:30"
}
```
I would be for this, as it keeps the response consistent with the response for lists/retrievals.
Another option entirely would be to always return UTC times, even during creation/updates, but I find that less useful. Either way, having consistent timezones would be preferable to the 50/50ish situation we have right now.
> Set your TIME_ZONE = 'Asia/Kolkata' and create a model serializer with a single datetime field, appointment.
>
> During create/update, send:
>
> {
> "appointment": "2016-12-19T10:00:00"
> }
> and get back:
>
> {
> "appointment": "2016-12-19T10:00:00+5:30"
> }
> But if you retrieve or list that object again, you get:
>
> {
> "appointment": "2016-12-19T04:30:00Z"
> }
thanx @jonathan-golorry this is the exact behavior that I actually see.
For me the behavior should be like this (using @jonathan-golorry example :) ):
During create/update with default DATETIME_FORMAT, send:
```json
{
"appointment": "2016-12-19T10:00:00"
}
```
and get back:
```json
{
"appointment": "2016-12-19T10:00:00+5:30"
}
```
If you retrieve or list that object again , you get:
```json
{
"appointment": "2016-12-19T10:00:00+5:30"
}
```
IMHO maybe should be a DRF setting to manage this behavior, for example, a setting to force the DateTimeField to be represented with the default timezone.
thanx a lot @tomchristie
The inconsistency between differing actions is the clincher for reopening here. I'd not realized that was the case. I'd expect us to use UTC throughout by default, although we *could* make that optional.
For a production web app that use DRF 3.4.6, we have resolved with this workaround:
https://github.com/vpistis/django-rest-framework/commit/be62db9080b19998d4de3a1f651a291d691718f6
If anyone wants to submit a pull request that either includes:
* just includes failing test cases, *or*...
* test case + fix
that'd be most welcome.
I have wrote some code to test, but I'm not sure how use drf test cases. I don't know how can manage django settings to change Timezone and others settings at runtime.
Please, link me some specific example or guide.
thanx
If you're looking to modify the global test settings, they're located [here](https://github.com/tomchristie/django-rest-framework/blob/master/tests/conftest.py).
If you're trying to override the settings during testing, you can use the `override_settings` [decorator](https://docs.djangoproject.com/en/1.10/topics/testing/tools/#django.test.override_settings).
Would also appreciate this feature. I do feel that the the `USE_TZ` setting should be respected and the values should be converted, similar to standard Django behavior.
First step here would be to write a failing test case that we can add to the current test suite.
Next step would be to start a fix for that case :)
Hi,
for me this is a test case for this feature
``` python
class TestDateTimeFieldTimeZone(TestCase):
"""
Valid and invalid values for `DateTimeField`.
"""
from django.utils import timezone
valid_inputs = {
'2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.get_default_timezone()),
'2001-01-01T13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.get_default_timezone()),
'2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.get_default_timezone()),
datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.get_default_timezone()),
datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00,
tzinfo=timezone.get_default_timezone()),
# Django 1.4 does not support timezone string parsing.
'2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.get_default_timezone())
}
invalid_inputs = {}
outputs = {
# This is not simple, for now I suppose TIME_ZONE = "Europe/Rome"
datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.get_default_timezone()): '2001-01-01T13:00:00+01:00',
datetime.datetime(2001, 1, 1, 13, 00, ): '2001-01-01T13:00:00+01:00',
}
field = serializers.DateTimeField()
```
In my fork I use some trick to get times in the correct timezone [my 3.6.2_tz_fix](https://github.com/vpistis/django-rest-framework/tree/3.6.2_tz_fix).
I hope this help :)
I see this is closed but I am running drf 3.6.3 and in my postgres database I have this timestamp "2017-07-12 14:26:00-06" but when I get the data using postman I get this "timestamp": "2017-07-12T20:26:00Z". I looks like it is adding on the -06 hours.
My django settings use tzlocal to set the timezone `TIME_ZONE = str(get_localzone())`. So the timezone is set on startup.
I am using a basic modelSerializer
```
class SnapshotSerializer(serializers.ModelSerializer):
class Meta:
model = Snapshot
resource_name = 'snapshot'
read_only_fields = ('id',)
fields = ('id', 'timestamp', 'snapshot')
```
Am I missing something?
not closed, it's still open :)
the red "closed button" that you see is for the reference issue.
...and you are right, the "bug" is still there ;(
The milestone is changed form 3.6.3 to 3.6.4.
Oh ok. Thank you!
On Jul 12, 2017 5:10 PM, "Valentino Pistis" <[email protected]>
wrote:
> not closed, it's still open :)
> the red "closed button" that you see is for the reference issue.
> ...and you are right, the "bug" is still there ;(
> The milestone is changed form 3.6.3 to 3.6.4.
>
> —
> You are receiving this because you commented.
> Reply to this email directly, view it on GitHub
> <https://github.com/encode/django-rest-framework/issues/3732#issuecomment-314923582>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AIMBTcx-6PPbi_SOqeLCjeWV1Rb59-Ohks5sNVJ0gaJpZM4G0aRE>
> .
>
Hi,
I'm not sure if this is totally related to the original question, but should DRF be honouring any timezone overrides which are set, as per https://docs.djangoproject.com/en/1.11/ref/utils/#django.utils.timezone.activate ?
I have a system where my users are associated with a timezone, and the API receives naiive datetimes. I expect to be able to convert those datetimes into the current user's timezone, but I notice that `../rest_framework/fields.py` is applying the default timezone (i.e. the one from the django setting file:
```
def enforce_timezone(self, value):
field_timezone = getattr(self, 'timezone', self.default_timezone())
if (field_timezone is not None) and not timezone.is_aware(value):
try:
return timezone.make_aware(value, field_timezone)
[...]
def default_timezone(self):
return timezone.get_default_timezone() if settings.USE_TZ else None
```
Should this really be using `timezone.get_current_timezone()` as a preference in case the application has set an override, such as in my case?
Hi @RichardForshaw that seems like a distinct issue, but same ball park certainly.
If we can get a decent set of test cases covering the expected behaviour, I think we’d certainly look at a PR here.
My first thought is beyond that is to make sure you’re send the time zone info to the API, rather than relying on the server’s configured time zone. Beyond that I’m also inclined to think you need to be prepared to localise a time on the client.
But yes, there’s an inconsistency here to be addressed. (Did I mention PRs Welcome? 🙂)
carltongibson/django-filter#750 should be relevant here. I originally based django-filter's timezone handling on DRF, so the changes in 750 could easily be applied here.
Sorry for my newbie-ness but what exactly is the issue here? The timestamp in my psql database is correct and Django is set to use the correct timezone. Is there a DRF settings to just make it not convert timestamps?
Hi @michaelaelise — if you look at the example of the data (near the top):
1. They're sending a datetime without timezone info. (This is a bad move in my book.)
2. The server is applying its local timezone and it comes back as that (`+5:30` in this case)
3. But later, when you fetch it, it comes back as UTC (`Z`, for "Zulu" I suppose).
There's no real issue **on the assumption your client will handle the timezone conversion for you**. (Except maybe No1, because who's to say your client has the same timezone setting as your server...?)
**But** it's a little inconsistency, surely 2 and 3 should have the same format? (Even though a client will, correctly, accept either as equivalent values.)
I'm inclined to close this.
* There's no logic error here.
* These are the same time: `"2016-12-19T10:00:00+5:30"` and `"2016-12-19T04:30:00Z"` — to a certain extent, who cares how they come back?
* Thus, it's not something I can justify allocating time to really.
* The ticket is 2 years old and no-one has offered a PR.
I'm happy to look at a PR but I'm not sure I want to really consider this an _Open Issue_.
Oh, I did not realize that in my original post in this issue thread that the "Z" meant that.
So DRF is converting the aware datetime to UTC to be handled by the UI/caller?
Thank you for that clarification.
One last thing.
What if we would like "2016-12-19T10:00:00+5:30" to be returned because we are polling devices in different timezones.
Could this be a setting "RETURN_DATETIME_WITH_TIMEZONE"?
We are using django/drf on edge devices. So all datetimes being inserted do not care if it is naive or not because the edge device timezone is configured and postgres field will always be accurate for that devices datetime.
The cloud server in the current scenario would then need to know the timezone of each device, it probably will, that just shifts the work from django/drf to the cloud app to handle.
Assuming USE_TZ, DRF is already returning date times with the time zone info. So it’s already doing what you need there.
The only issue here is whether the same DT is formatted as in one time zone or another. (But they’re still the same time.)
@carltongibson
> There's no logic error here.
> These are the same time: "2016-12-19T10:00:00+5:30" and "2016-12-19T04:30:00Z" — to a certain extent, who cares how they come back?
IMHO this is the problem: the returned string!
I use Django Time zone settings and all templates return the correct time `"2016-12-19T10:00:00+5:30"` like we expected, but DRF not. DRF return `"2016-12-19T04:30:00Z"`.
Into the client, that consumes my REST apis, ther's no logic, no times conversions or datetime string interpretation.
In other words, I expect that the datetime from a DRF response is identical to the Django Template "response": the server prepare all data for the client and the client only shows it.
Anyway, thanx a lot for your patience, support and your great work to this fantastic project!
@vpistis my point here is just that the represented date is correct, just the representation Is not expected. As soon as you parse that to a native Date, however your language handles that, there is no difference.
I would expect users to be parsing the date string to a Date, however their client language provides for that, rather than consuming the raw string.
I accept if you’re consuming the raw string your expectations wont be met here. (But don’t do that: imagine if we sent UNIX timestamps; there’s no way you’d consume those raw. Convert to a proper Date object, whatever that is in your client language.)
I’m really happy to take a PR on this. (I haven’t closed it yet!)
But it’s been nearly two years since reported and nine months since the first comment (yours, a year later). Nobody has even given us a failing test case. It can’t be that important to anyone. As such it’s hard to allocate it time.
(As such I’m inclined to close it on the basis that we’ll take a PR if one ever turns up)
| 2017-09-20T10:03:49 |
encode/django-rest-framework | 5,440 | encode__django-rest-framework-5440 | [
"4749"
] | f6c19e5eacbdc8a132e996f66f019994f34fda70 | diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py
--- a/rest_framework/utils/encoders.py
+++ b/rest_framework/utils/encoders.py
@@ -37,8 +37,6 @@ def default(self, obj):
if timezone and timezone.is_aware(obj):
raise ValueError("JSON can't represent timezone-aware times.")
representation = obj.isoformat()
- if obj.microsecond:
- representation = representation[:12]
return representation
elif isinstance(obj, datetime.timedelta):
return six.text_type(total_seconds(obj))
| diff --git a/tests/test_encoders.py b/tests/test_encoders.py
--- a/tests/test_encoders.py
+++ b/tests/test_encoders.py
@@ -44,7 +44,7 @@ def test_encode_time(self):
Tests encoding a timezone
"""
current_time = datetime.now().time()
- assert self.encoder.default(current_time) == current_time.isoformat()[:12]
+ assert self.encoder.default(current_time) == current_time.isoformat()
def test_encode_time_tz(self):
"""
| Inconsistent time serialization
## 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
The implementation of time serialization in ISO-8601 format is not consistent in the codebase.
In https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py#L1284 microseconds are included in the serialized value
In https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/encoders.py#L41 only milliseconds are
This is basically the same issue as #4255 except for time instead of datetime.
## Expected behavior
I would expect a consistent implementation between the different serialization of time _and_ datetime, i.e. all of them should include microseconds.
## Actual behavior
See "Steps to reproduce"
| Yup seems clear. Milestoning for 3.7 so we can make to make the change against a major version (given that it'll change the API output) | 2017-09-22T10:03:53 |
encode/django-rest-framework | 5,448 | encode__django-rest-framework-5448 | [
"5309",
"5399"
] | 107e8b3d23a933b8cdc1f14045d7d42742be53a9 | diff --git a/rest_framework/documentation.py b/rest_framework/documentation.py
--- a/rest_framework/documentation.py
+++ b/rest_framework/documentation.py
@@ -4,11 +4,14 @@
CoreJSONRenderer, DocumentationRenderer, SchemaJSRenderer
)
from rest_framework.schemas import SchemaGenerator, get_schema_view
+from rest_framework.settings import api_settings
def get_docs_view(
title=None, description=None, schema_url=None, public=True,
- patterns=None, generator_class=SchemaGenerator):
+ patterns=None, generator_class=SchemaGenerator,
+ authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
+ permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES):
renderer_classes = [DocumentationRenderer, CoreJSONRenderer]
return get_schema_view(
@@ -19,12 +22,16 @@ def get_docs_view(
public=public,
patterns=patterns,
generator_class=generator_class,
+ authentication_classes=authentication_classes,
+ permission_classes=permission_classes,
)
def get_schemajs_view(
title=None, description=None, schema_url=None, public=True,
- patterns=None, generator_class=SchemaGenerator):
+ patterns=None, generator_class=SchemaGenerator,
+ authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
+ permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES):
renderer_classes = [SchemaJSRenderer]
return get_schema_view(
@@ -35,12 +42,16 @@ def get_schemajs_view(
public=public,
patterns=patterns,
generator_class=generator_class,
+ authentication_classes=authentication_classes,
+ permission_classes=permission_classes,
)
def include_docs_urls(
title=None, description=None, schema_url=None, public=True,
- patterns=None, generator_class=SchemaGenerator):
+ patterns=None, generator_class=SchemaGenerator,
+ authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
+ permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES):
docs_view = get_docs_view(
title=title,
description=description,
@@ -48,6 +59,8 @@ def include_docs_urls(
public=public,
patterns=patterns,
generator_class=generator_class,
+ authentication_classes=authentication_classes,
+ permission_classes=permission_classes,
)
schema_js_view = get_schemajs_view(
title=title,
@@ -56,6 +69,8 @@ def include_docs_urls(
public=public,
patterns=patterns,
generator_class=generator_class,
+ authentication_classes=authentication_classes,
+ permission_classes=permission_classes,
)
urls = [
url(r'^$', docs_view, name='docs-index'),
diff --git a/rest_framework/schemas/__init__.py b/rest_framework/schemas/__init__.py
--- a/rest_framework/schemas/__init__.py
+++ b/rest_framework/schemas/__init__.py
@@ -20,13 +20,17 @@
Other access should target the submodules directly
"""
+from rest_framework.settings import api_settings
+
from .generators import SchemaGenerator
from .inspectors import AutoSchema, ManualSchema # noqa
def get_schema_view(
title=None, url=None, description=None, urlconf=None, renderer_classes=None,
- public=False, patterns=None, generator_class=SchemaGenerator):
+ public=False, patterns=None, generator_class=SchemaGenerator,
+ authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
+ permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES):
"""
Return a schema view.
"""
@@ -40,4 +44,6 @@ def get_schema_view(
renderer_classes=renderer_classes,
schema_generator=generator,
public=public,
+ authentication_classes=authentication_classes,
+ permission_classes=permission_classes,
)
| allow custom authentication and permission classes for docs view
Currently (in 3.6.3) no authentication or permission classes can be supplied to the SchemaView, so it always uses the defaults.
This is a problem if, for example, the default is token authentication but the docs should be exposed on the web, or if permissions to access the API docs should be different from permissions to make requests to the API.
This PR allows the authentication and permission classes to be explicitly specified as kwargs to `include_docs_urls`.
Allow `include_docs_urls` to configure Schema View Authentication
Hi there, i am using the built in api documentation from drf 3.6 http://www.django-rest-framework.org/topics/documenting-your-api/
I am only able to access the API docs if i am logged into Django admin for example (even if my endpoints do not have any authentication).
Is there a way for me to disable the authentication in the API docs?
Thanks
|
@psychok7 What are your [`DEFAULT_AUTHENTICATION_CLASSES`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/settings.py#L41-L44)? You're probably requiring Session or Basic auth implicitly.
You can set these to `[]` as a work around. Either that or you'll need to manually configure the docs view.
`include_docs_urls` should allow this. (But currently doesn't)
@carltongibson your workaround worked, thanks. By the way i also had to set `'DEFAULT_PERMISSION_CLASSES': ()`
#5309 sketches this. | 2017-09-25T14:34:22 |
|
encode/django-rest-framework | 5,452 | encode__django-rest-framework-5452 | [
"3354"
] | 50acb9b2feb2fc3815e06cb881f81d3e16ff4864 | diff --git a/rest_framework/compat.py b/rest_framework/compat.py
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -11,13 +11,18 @@
import django
from django.apps import apps
from django.conf import settings
-from django.core.exceptions import ImproperlyConfigured
+from django.core.exceptions import ImproperlyConfigured, ValidationError
+from django.core.validators import \
+ MaxLengthValidator as DjangoMaxLengthValidator
+from django.core.validators import MaxValueValidator as DjangoMaxValueValidator
+from django.core.validators import \
+ MinLengthValidator as DjangoMinLengthValidator
+from django.core.validators import MinValueValidator as DjangoMinValueValidator
from django.db import connection, models, transaction
from django.template import Context, RequestContext, Template
from django.utils import six
from django.views.generic import View
-
try:
from django.urls import (
NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve
@@ -293,6 +298,28 @@ def pygments_css(style):
except ImportError:
DecimalValidator = None
+class CustomValidatorMessage(object):
+ """
+ We need to avoid evaluation of `lazy` translated `message` in `django.core.validators.BaseValidator.__init__`.
+ https://github.com/django/django/blob/75ed5900321d170debef4ac452b8b3cf8a1c2384/django/core/validators.py#L297
+
+ Ref: https://github.com/encode/django-rest-framework/pull/5452
+ """
+ def __init__(self, *args, **kwargs):
+ self.message = kwargs.pop('message', self.message)
+ super(CustomValidatorMessage, self).__init__(*args, **kwargs)
+
+class MinValueValidator(CustomValidatorMessage, DjangoMinValueValidator):
+ pass
+
+class MaxValueValidator(CustomValidatorMessage, DjangoMaxValueValidator):
+ pass
+
+class MinLengthValidator(CustomValidatorMessage, DjangoMinLengthValidator):
+ pass
+
+class MaxLengthValidator(CustomValidatorMessage, DjangoMaxLengthValidator):
+ pass
def set_rollback():
if hasattr(transaction, 'set_rollback'):
diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -13,8 +13,7 @@
from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.exceptions import ObjectDoesNotExist
from django.core.validators import (
- EmailValidator, MaxLengthValidator, MaxValueValidator, MinLengthValidator,
- MinValueValidator, RegexValidator, URLValidator, ip_address_validators
+ EmailValidator, RegexValidator, URLValidator, ip_address_validators
)
from django.forms import FilePathField as DjangoFilePathField
from django.forms import ImageField as DjangoImageField
@@ -25,14 +24,16 @@
from django.utils.duration import duration_string
from django.utils.encoding import is_protected_type, smart_text
from django.utils.formats import localize_input, sanitize_separators
+from django.utils.functional import lazy
from django.utils.ipv6 import clean_ipv6_address
from django.utils.timezone import utc
from django.utils.translation import ugettext_lazy as _
from rest_framework import ISO_8601
from rest_framework.compat import (
- InvalidTimeError, get_remote_field, unicode_repr, unicode_to_repr,
- value_from_object
+ InvalidTimeError, MaxLengthValidator, MaxValueValidator,
+ MinLengthValidator, MinValueValidator, get_remote_field, unicode_repr,
+ unicode_to_repr, value_from_object
)
from rest_framework.exceptions import ErrorDetail, ValidationError
from rest_framework.settings import api_settings
@@ -750,11 +751,17 @@ def __init__(self, **kwargs):
self.min_length = kwargs.pop('min_length', None)
super(CharField, self).__init__(**kwargs)
if self.max_length is not None:
- message = self.error_messages['max_length'].format(max_length=self.max_length)
- self.validators.append(MaxLengthValidator(self.max_length, message=message))
+ message = lazy(
+ self.error_messages['max_length'].format,
+ six.text_type)(max_length=self.max_length)
+ self.validators.append(
+ MaxLengthValidator(self.max_length, message=message))
if self.min_length is not None:
- message = self.error_messages['min_length'].format(min_length=self.min_length)
- self.validators.append(MinLengthValidator(self.min_length, message=message))
+ message = lazy(
+ self.error_messages['min_length'].format,
+ six.text_type)(min_length=self.min_length)
+ self.validators.append(
+ MinLengthValidator(self.min_length, message=message))
def run_validation(self, data=empty):
# Test for the empty string here so that it does not get validated,
@@ -909,11 +916,17 @@ def __init__(self, **kwargs):
self.min_value = kwargs.pop('min_value', None)
super(IntegerField, self).__init__(**kwargs)
if self.max_value is not None:
- message = self.error_messages['max_value'].format(max_value=self.max_value)
- self.validators.append(MaxValueValidator(self.max_value, message=message))
+ message = lazy(
+ self.error_messages['max_value'].format,
+ six.text_type)(max_value=self.max_value)
+ self.validators.append(
+ MaxValueValidator(self.max_value, message=message))
if self.min_value is not None:
- message = self.error_messages['min_value'].format(min_value=self.min_value)
- self.validators.append(MinValueValidator(self.min_value, message=message))
+ message = lazy(
+ self.error_messages['min_value'].format,
+ six.text_type)(min_value=self.min_value)
+ self.validators.append(
+ MinValueValidator(self.min_value, message=message))
def to_internal_value(self, data):
if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH:
@@ -943,11 +956,17 @@ def __init__(self, **kwargs):
self.min_value = kwargs.pop('min_value', None)
super(FloatField, self).__init__(**kwargs)
if self.max_value is not None:
- message = self.error_messages['max_value'].format(max_value=self.max_value)
- self.validators.append(MaxValueValidator(self.max_value, message=message))
+ message = lazy(
+ self.error_messages['max_value'].format,
+ six.text_type)(max_value=self.max_value)
+ self.validators.append(
+ MaxValueValidator(self.max_value, message=message))
if self.min_value is not None:
- message = self.error_messages['min_value'].format(min_value=self.min_value)
- self.validators.append(MinValueValidator(self.min_value, message=message))
+ message = lazy(
+ self.error_messages['min_value'].format,
+ six.text_type)(min_value=self.min_value)
+ self.validators.append(
+ MinValueValidator(self.min_value, message=message))
def to_internal_value(self, data):
@@ -996,11 +1015,17 @@ def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=
super(DecimalField, self).__init__(**kwargs)
if self.max_value is not None:
- message = self.error_messages['max_value'].format(max_value=self.max_value)
- self.validators.append(MaxValueValidator(self.max_value, message=message))
+ message = lazy(
+ self.error_messages['max_value'].format,
+ six.text_type)(max_value=self.max_value)
+ self.validators.append(
+ MaxValueValidator(self.max_value, message=message))
if self.min_value is not None:
- message = self.error_messages['min_value'].format(min_value=self.min_value)
- self.validators.append(MinValueValidator(self.min_value, message=message))
+ message = lazy(
+ self.error_messages['min_value'].format,
+ six.text_type)(min_value=self.min_value)
+ self.validators.append(
+ MinValueValidator(self.min_value, message=message))
def to_internal_value(self, data):
"""
@@ -1797,8 +1822,11 @@ def __init__(self, model_field, **kwargs):
max_length = kwargs.pop('max_length', None)
super(ModelField, self).__init__(**kwargs)
if max_length is not None:
- message = self.error_messages['max_length'].format(max_length=max_length)
- self.validators.append(MaxLengthValidator(max_length, message=message))
+ message = lazy(
+ self.error_messages['max_length'].format,
+ six.text_type)(max_length=self.max_length)
+ self.validators.append(
+ MaxLengthValidator(self.max_length, message=message))
def to_internal_value(self, data):
rel = get_remote_field(self.model_field, default=None)
| Don't call `.format()` on lazy-translated strings during Field.__init__
This from IRC...
```
[17:04:05] <__zer01> after adding the `min_value` kwarg to a serializer.DecimalField I get a `django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready.` error when running tests, any ideas?
[17:07:57] <__zer01> here's the end of the stack trace http://pastebin.com/B7ECdL6w
```
Which is:
```
File "/home/eugenio/spartan/rest/serializers.py", line 80, in MySerializer min_value=1.01)
File "/home/eugenio/Envs/spartan/lib/python3.4/site-packages/rest_framework/fields.py", line 906, in __init__
message = self.error_messages['min_value'].format(min_value=self.min_value)
File "/home/eugenio/Envs/spartan/lib/python3.4/site-packages/django/utils/functional.py", line 136, in __wrapper__ res = func(*self.__args, **self.__kw)
File "/home/eugenio/Envs/spartan/lib/python3.4/site-packages/django/utils/translation/__init__.py", line 84, in ugettext
return _trans.ugettext(message)
File "/home/eugenio/Envs/spartan/lib/python3.4/site-packages/django/utils/translation/trans_real.py", line 321, in gettext
return do_translate(message, 'gettext')
File "/home/eugenio/Envs/spartan/lib/python3.4/site-packages/django/utils/translation/trans_real.py", line 304, in do_translate
_default = _default or translation(settings.LANGUAGE_CODE)
File "/home/eugenio/Envs/spartan/lib/python3.4/site-packages/django/utils/translation/trans_real.py", line 206, in translation
_translations[language] = DjangoTranslation(language)
File "/home/eugenio/Envs/spartan/lib/python3.4/site-packages/django/utils/translation/trans_real.py", line 116, in __init__
self._add_installed_apps_translations()
File "/home/eugenio/Envs/spartan/lib/python3.4/site-packages/django/utils/translation/trans_real.py", line 164, in _add_installed_apps_translations
"The translation infrastructure cannot be initialized before the "
django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.
```
And...
```
[17:08:41] yuriheupa ([email protected]) joined the channel.
[17:09:26] yuriheupa ([email protected]) left IRC. (Remote host closed the connection)
[17:11:54] <tomchristie> Hrm
[17:13:14] <__zer01> I'm running djangorestframework==3.2.3 and Django==1.8.4
[17:13:28] <tomchristie> I think that may need raising as an issue
[17:14:13] <tomchristie> The error is being raised because we're calling .format on a lazy-translated error message
[17:14:34] <tomchristie> Due to it being passed a min_value which is included in the message
[17:15:00] <tomchristie> Prob is, that causes the translation machinary to attempt to run, and produce the translated output
[17:15:12] <tomchristie> But that can't happen yet because the app isn't setup and running
[17:15:23] <tomchristie> Looks like Django internally handles this a little diff, eg
[17:15:34] <tomchristie> This… https://github.com/django/django/blob/master/django/forms/fields.py#L258
[17:15:43] <tomchristie> vs
[17:16:09] <tomchristie> This: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py#L820-L821
[17:16:23] <tomchristie> Notive that we're calling .format when the field is instantiated
[17:16:31] <tomchristie> But same is not happening in Django
[17:16:37] <tomchristie> You may be able to resolve
[17:16:53] <tomchristie> by ensuring that you're not importing the serializers prior to the app setup
[17:16:54] marc_v92 (~marc_v92@unaffiliated/marc-v92/x-6202358) joined the channel.
[17:17:07] <tomchristie> (Eg if you import them in your settings I guess that's when it blows up)
```
| Really all that needs to be changed here is that these particular lines
``` python
message = self.error_messages['max_value'].format(max_value=self.max_value)
```
need to be removed?
Doing this and running the tests does not yield any test failures, but then again I am not sure where else `message` is used.
ping @tomchristie or @kevin-brown for the above. If this is the right approach and I have already made the changes and could push them out. Let me know when you get a chance :smile:
@nryoung we may lack a test for that particular string. It looks like the omitting the format will result in the max_value not being correctly filled whenever an error occurs.
> @nryoung we may lack a test for that particular string. It looks like the omitting the format will result in the max_value not being correctly filled whenever an error occurs.
This does seem to be the case. It seems like we could use the `message` class attribute of Django's `MaxValueValidator` since it is a simple inheritance of this class: https://github.com/django/django/blob/master/django/core/validators.py#L318
I have been doing some research on this.
#### For Django versions >= 1.8 `message` is optional in the `__init__` method:
- https://github.com/django/django/blob/stable/1.8.x/django/core/validators.py#L275
but, `message` is also defaulted as a class attribute here:
- https://github.com/django/django/blob/stable/1.8.x/django/core/validators.py#L298
#### For Django versions < 1.8 `message` is not expected:
- https://github.com/django/django/blob/stable/1.7.x/django/core/validators.py#L242
thus, that is why it is popped off here:
- https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/compat.py#L125
but, `message` is also defaulted here:
- https://github.com/django/django/blob/stable/1.7.x/django/core/validators.py#L258
I believe, that removing the `message` assignments here and other similar ones:
- https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py#L823
and not passing `message` in to the instantiation of the validator, it should default to the Django class attribute:
- https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py#L824
I will make a PR for what I outline above. As always, let me know if I am wrong here.
| 2017-09-25T20:33:54 |
|
encode/django-rest-framework | 5,454 | encode__django-rest-framework-5454 | [
"5237"
] | ab7e5c4551b828415db192ed8e1d8c272ae60d11 | 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
@@ -337,18 +337,33 @@ def get_pagination_fields(self, path, method):
paginator = view.pagination_class()
return paginator.get_schema_fields(view)
- def get_filter_fields(self, path, method):
- view = self.view
+ def _allows_filters(self, path, method):
+ """
+ Determine whether to include filter Fields in schema.
- if not is_list_view(path, method, view):
- return []
+ Default implementation looks for ModelViewSet or GenericAPIView
+ actions/methods that cause filtering on the default implementation.
+
+ Override to adjust behaviour for your view.
- if not getattr(view, 'filter_backends', None):
+ Note: Introduced in v3.7: Initially "private" (i.e. with leading underscore)
+ to allow changes based on user experience.
+ """
+ if getattr(self.view, 'filter_backends', None) is None:
+ return False
+
+ if hasattr(self.view, 'action'):
+ return self.view.action in ["list", "retrieve", "update", "partial_update", "destroy"]
+
+ return method.lower in ["get", "put", "patch", "delete"]
+
+ def get_filter_fields(self, path, method):
+ if not self._allows_filters(path, method):
return []
fields = []
- for filter_backend in view.filter_backends:
- fields += filter_backend().get_schema_fields(view)
+ for filter_backend in self.view.filter_backends:
+ fields += filter_backend().get_schema_fields(self.view)
return fields
def get_encoding(self, path, method):
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -139,7 +139,8 @@ def test_anonymous_request(self):
url='/example/{id}/',
action='get',
fields=[
- coreapi.Field('id', required=True, location='path', schema=coreschema.String())
+ coreapi.Field('id', required=True, location='path', schema=coreschema.String()),
+ coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.'))
]
)
}
@@ -179,7 +180,8 @@ def test_authenticated_request(self):
url='/example/{id}/',
action='get',
fields=[
- coreapi.Field('id', required=True, location='path', schema=coreschema.String())
+ coreapi.Field('id', required=True, location='path', schema=coreschema.String()),
+ coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.'))
]
),
'custom_action': coreapi.Link(
@@ -225,7 +227,8 @@ def test_authenticated_request(self):
fields=[
coreapi.Field('id', required=True, location='path', schema=coreschema.String()),
coreapi.Field('a', required=True, location='form', schema=coreschema.String(title='A', description=('A field description'))),
- coreapi.Field('b', required=False, location='form', schema=coreschema.String(title='B'))
+ coreapi.Field('b', required=False, location='form', schema=coreschema.String(title='B')),
+ coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.'))
]
),
'partial_update': coreapi.Link(
@@ -235,14 +238,16 @@ def test_authenticated_request(self):
fields=[
coreapi.Field('id', required=True, location='path', schema=coreschema.String()),
coreapi.Field('a', required=False, location='form', schema=coreschema.String(title='A', description='A field description')),
- coreapi.Field('b', required=False, location='form', schema=coreschema.String(title='B'))
+ coreapi.Field('b', required=False, location='form', schema=coreschema.String(title='B')),
+ coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.'))
]
),
'delete': coreapi.Link(
url='/example/{id}/',
action='delete',
fields=[
- coreapi.Field('id', required=True, location='path', schema=coreschema.String())
+ coreapi.Field('id', required=True, location='path', schema=coreschema.String()),
+ coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.'))
]
)
}
@@ -450,7 +455,8 @@ def test_schema_for_regular_views(self):
url='/example1/{id}/',
action='get',
fields=[
- coreapi.Field('id', required=True, location='path', schema=coreschema.String())
+ coreapi.Field('id', required=True, location='path', schema=coreschema.String()),
+ coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.'))
]
)
}
| SchemaGenerator.get_filter_fields is inconsistent with GenericAPIView.get_object
Hello devs,
In [SchemaGenerator.get_filter_fields,](https://github.com/encode/django-rest-framework/blob/master/rest_framework/schemas.py#L616) there's a default path for non-list actions that returns an empty list.
I believe this is inconsistent with the behavior of [GenericAPIView.get_object](https://github.com/encode/django-rest-framework/blob/master/rest_framework/generics.py#L85) which will use filter_queryset.
The [related documentation](http://www.django-rest-framework.org/api-guide/filtering/#filtering-and-object-lookups) tends to confirm that this behavior is legitimate :
> Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.
>
> For instance, given the previous example, and a product with an id of 4675, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance:
The schema generated by SchemaGenerator will not reflect that filter fields are available for object-lookup actions, this is especially annoying when filter fields expect a mandatory parameter (filtering objects against a required client_id parameter for example).
## Steps to reproduce
- create a filter subclass which overrides `get_schema_fields` and return a non empty list of `coreapi.Fields`
- create a `ModelViewSet` subclass with the above filter in `filter_backends`
- generate a schema including this view
## Expected behavior
- The generated schema should define the filter's schema fields for object-lookup actions
## Actual behavior
- It doesn't.
| Yep. This seems correct (there is an inconsistency). | 2017-09-26T10:30:09 |
encode/django-rest-framework | 5,464 | encode__django-rest-framework-5464 | [
"4704"
] | 2befa6c3160a48b9eb9cc63292bd43b540a5b4d5 | 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
@@ -51,6 +51,19 @@ def is_api_view(callback):
return (cls is not None) and issubclass(cls, APIView)
+INSERT_INTO_COLLISION_FMT = """
+Schema Naming Collision.
+
+coreapi.Link for URL path {value_url} cannot be inserted into schema.
+Position conflicts with coreapi.Link for URL path {target_url}.
+
+Attemped to insert link with keys: {keys}.
+
+Adjust URLs to avoid naming collision or override `SchemaGenerator.get_keys()`
+to customise schema structure.
+"""
+
+
def insert_into(target, keys, value):
"""
Nested dictionary insertion.
@@ -64,7 +77,15 @@ def insert_into(target, keys, value):
if key not in target:
target[key] = {}
target = target[key]
- target[keys[-1]] = value
+ try:
+ target[keys[-1]] = value
+ except TypeError:
+ msg = INSERT_INTO_COLLISION_FMT.format(
+ value_url=value.url,
+ target_url=target.url,
+ keys=keys
+ )
+ raise ValueError(msg)
def is_custom_action(action):
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -6,13 +6,15 @@
from django.http import Http404
from django.test import TestCase, override_settings
-from rest_framework import filters, pagination, permissions, serializers
+from rest_framework import (
+ filters, generics, pagination, permissions, serializers
+)
from rest_framework.compat import coreapi, coreschema
from rest_framework.decorators import (
api_view, detail_route, list_route, schema
)
from rest_framework.request import Request
-from rest_framework.routers import DefaultRouter
+from rest_framework.routers import DefaultRouter, SimpleRouter
from rest_framework.schemas import (
AutoSchema, ManualSchema, SchemaGenerator, get_schema_view
)
@@ -20,7 +22,9 @@
from rest_framework.test import APIClient, APIRequestFactory
from rest_framework.utils import formatting
from rest_framework.views import APIView
-from rest_framework.viewsets import ModelViewSet
+from rest_framework.viewsets import GenericViewSet, ModelViewSet
+
+from .models import BasicModel
factory = APIRequestFactory()
@@ -726,3 +730,81 @@ def get(self, request, *args, **kwargs):
"The `OldFashionedExcludedView.exclude_from_schema` attribute is "
"pending deprecation. Set `schema = None` instead."
)
+
+
+@api_view(["GET"])
+def simple_fbv(request):
+ pass
+
+
+class BasicModelSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = BasicModel
+ fields = "__all__"
+
+
+class NamingCollisionView(generics.RetrieveUpdateDestroyAPIView):
+ queryset = BasicModel.objects.all()
+ serializer_class = BasicModelSerializer
+
+
+class NamingCollisionViewSet(GenericViewSet):
+ """
+ Example via: https://stackoverflow.com/questions/43778668/django-rest-framwork-occured-typeerror-link-object-does-not-support-item-ass/
+ """
+ permision_class = ()
+
+ @list_route()
+ def detail(self, request):
+ return {}
+
+ @list_route(url_path='detail/export')
+ def detail_export(self, request):
+ return {}
+
+
+naming_collisions_router = SimpleRouter()
+naming_collisions_router.register(r'collision', NamingCollisionViewSet, base_name="collision")
+
+
+class TestURLNamingCollisions(TestCase):
+ """
+ Ref: https://github.com/encode/django-rest-framework/issues/4704
+ """
+ def test_manually_routing_nested_routes(self):
+ patterns = [
+ url(r'^test', simple_fbv),
+ url(r'^test/list/', simple_fbv),
+ ]
+
+ generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
+
+ with pytest.raises(ValueError):
+ generator.get_schema()
+
+ 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()),
+
+ # 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()),
+ ]
+
+ generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
+
+ with pytest.raises(ValueError):
+ generator.get_schema()
+
+ def test_from_router(self):
+ patterns = [
+ url(r'from-router', include(naming_collisions_router.urls)),
+ ]
+
+ generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
+
+ with pytest.raises(ValueError):
+ generator.get_schema()
| Schema generation doesn't work if URL ends with method name
## Steps to reproduce
If one would use urls like these (not a good practice but possible):
url(r'^test', ExampleView1.as_view()),
url(r'^test/delete/', ExampleView2.as_view()),
Schema generation using rest_framework.schemas.get_schema_view will fail.
I've attached minimal [test django project](https://github.com/tomchristie/django-rest-framework/files/611291/schema_bug_test.tar.gz) if anyone would like to reproduce the issue.
## Expected behavior
Schema should be generated as normally does.
## Actual behavior
Throws an exception:
```
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8001/
Django Version: 1.10.3
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'schema_bug_test_app']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Users/mlubimow/Projects/test_project/env/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/mlubimow/Projects/test_project/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/mlubimow/Projects/test_project/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/mlubimow/Projects/test_project/env/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/Users/mlubimow/Projects/test_project/env/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/mlubimow/Projects/test_project/env/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
477. response = self.handle_exception(exc)
File "/Users/mlubimow/Projects/test_project/env/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception
437. self.raise_uncaught_exception(exc)
File "/Users/mlubimow/Projects/test_project/env/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
474. response = handler(request, *args, **kwargs)
File "/Users/mlubimow/Projects/test_project/env/lib/python2.7/site-packages/rest_framework/schemas.py" in get
593. schema = generator.get_schema(request)
File "/Users/mlubimow/Projects/test_project/env/lib/python2.7/site-packages/rest_framework/schemas.py" in get_schema
242. links = self.get_links(request)
File "/Users/mlubimow/Projects/test_project/env/lib/python2.7/site-packages/rest_framework/schemas.py" in get_links
276. insert_into(links, keys, link)
File "/Users/mlubimow/Projects/test_project/env/lib/python2.7/site-packages/rest_framework/schemas.py" in insert_into
79. target[keys[-1]] = value
Exception Type: TypeError at /
Exception Value: 'Link' object does not support item assignment
```
| Any chance you could include the traceback of that exception?
Oh, yeah, sorry for that. I've updated report.
hello @tomchristie any idea when this will be solved?
Thanks
Not yet. Been focusing on functionality for 3.6 lately.
This also happens if an url is (or maybe **also** ends with? did not try this one) 'list' (a natural verb enough). The reason is that `insert_into` (in schemas.py) is passed a keys parameter whose last element's value is 'list', which eventually conflicts with the 'list' present in the url.
It also occurs when you use drf-extensions with NestedRoutes.
From what I remember it used to worked in 3.4.
Is it possible to have this resolved in the next patch release?
This issue is caused by usage of `url_path` in `detail_route` decorator. Any chance of fix?
```
class MyViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
...
@detail_route(
methods=['get', ],
url_name='children-list',
url_path='children(?:/(?P<child_id>[a-zA-Z0-9]+))?',
serializer_class=emg_serializers.ChildSerializer
)
def children(self, , request, parent_id=None, child_id=None):
...
```
You can temporary fix it in your project using a custom `SchemaView` with a custom `SchemaGenerator`: https://stackoverflow.com/a/45323639/5157209
@carltongibson is it possible to get this fixed in 3.7.0?
<img width="695" alt="screenshot 2017-09-28 17 44 03" src="https://user-images.githubusercontent.com/64686/30976251-a4ab0c60-a474-11e7-9f7e-dbe3379ae716.png">
😀
that's the idea.
I need to look into exactly what the issue is, and then the fix, but it's on [the short list](https://github.com/encode/django-rest-framework/milestone/49) | 2017-09-29T09:45:48 |
encode/django-rest-framework | 5,472 | encode__django-rest-framework-5472 | [
"5395"
] | 063534ae50d3d15a307205c91ed5a25974b0a1f4 | 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
@@ -245,6 +245,20 @@ def items(value):
return value.items()
[email protected]
+def data(value):
+ """
+ Simple filter to access `data` attribute of object,
+ specifically coreapi.Document.
+
+ As per `items` filter above, allows accessing `document.data` when
+ Document contains Link keyed-at "data".
+
+ See issue #5395
+ """
+ return value.data
+
+
@register.filter
def schema_links(section, sec_key=None):
"""
| diff --git a/tests/conftest.py b/tests/conftest.py
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -26,6 +26,9 @@ def pytest_configure():
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
+ 'OPTIONS': {
+ "debug": True, # We want template errors to raise
+ }
},
],
MIDDLEWARE=MIDDLEWARE,
diff --git a/tests/test_renderers.py b/tests/test_renderers.py
--- a/tests/test_renderers.py
+++ b/tests/test_renderers.py
@@ -14,9 +14,10 @@
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.renderers import (
- AdminRenderer, BaseRenderer, BrowsableAPIRenderer,
+ AdminRenderer, BaseRenderer, BrowsableAPIRenderer, DocumentationRenderer,
HTMLFormRenderer, JSONRenderer, StaticHTMLRenderer
)
from rest_framework.request import Request
@@ -706,3 +707,32 @@ def get(self, request):
response = view(request)
response.render()
self.assertInHTML('<tr><th>Iteritems</th><td>a string</td></tr>', str(response.content))
+
+
+class TestDocumentationRenderer(TestCase):
+
+ def test_document_with_link_named_data(self):
+ """
+ Ref #5395: Doc's `document.data` would fail with a Link named "data".
+ As per #4972, use templatetag instead.
+ """
+ document = coreapi.Document(
+ title='Data Endpoint API',
+ url='https://api.example.org/',
+ content={
+ 'data': coreapi.Link(
+ url='/data/',
+ action='get',
+ fields=[],
+ description='Return data.'
+ )
+ }
+ )
+
+ factory = APIRequestFactory()
+ request = factory.get('/')
+
+ renderer = DocumentationRenderer()
+
+ html = renderer.render(document, accepted_media_type="text/html", renderer_context={"request": request})
+ assert '<h1>Data Endpoint API</h1>' in html
diff --git a/tests/urls.py b/tests/urls.py
--- a/tests/urls.py
+++ b/tests/urls.py
@@ -1,4 +1,11 @@
"""
-Blank URLConf just to keep the test suite happy
+URLConf for test suite.
+
+We need only the docs urls for DocumentationRenderer tests.
"""
-urlpatterns = []
+from django.conf.urls import url
+from rest_framework.documentation import include_docs_urls
+
+urlpatterns = [
+ url(r'^docs/', include_docs_urls(title='Test Suite API')),
+]
| Docs crash when a viewset is called `data`
## Checklist
- [x] I have verified that that issue exists against the `master` branch of Django REST framework. (Commit 71ad99e0b276a90d055)
- [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
* Register a viewset with the name `data` to a router. (`router.register('data', SomeViewSet)`)
* Navigate to the generated API docs page (as included by `include_docs_urls()`)
👉 See a minimal test repo here: https://github.com/akx/drf-docs-fail
## Expected behavior
The docs work as usual.
## Actual behavior
Docs crash with
> *AttributeError*: 'Link' object has no attribute 'links'
> in djangorestframework/rest_framework/templatetags/rest_framework.py
> / schema_links, line 253
## Workaround
Don't name a viewset `data`.
(However, this isn't an acceptable workaround in my project, since the viewset literally concerns bits of data, and any other name would be worse.)
| This'll need the same fix as #4972 (Fancy doing a PR?)
Thanks of the report!
Mmm, if I understand correctly, this would require a `data` filter (to make it possible to reference the `data` attribute as opposed to Django's implicit `['data']`)?
If that is the case, would it maybe be better to write a generic `attr` filter?
```django
{% for link in document|attr:data|items %}...{% endfor %}
```
Yep. Sounds good. | 2017-10-02T09:30:39 |
encode/django-rest-framework | 5,480 | encode__django-rest-framework-5480 | [
"5165"
] | d8da6bb29b53675f837c8873cf8fcde171a3aae1 | diff --git a/rest_framework/schemas/utils.py b/rest_framework/schemas/utils.py
--- a/rest_framework/schemas/utils.py
+++ b/rest_framework/schemas/utils.py
@@ -3,6 +3,7 @@
See schemas.__init__.py for package overview.
"""
+from rest_framework.mixins import RetrieveModelMixin
def is_list_view(path, method, view):
@@ -15,6 +16,8 @@ def is_list_view(path, method, view):
if method.lower() != 'get':
return False
+ if isinstance(view, RetrieveModelMixin):
+ return False
path_components = path.strip('/').split('/')
if path_components and '{' in path_components[-1]:
return False
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -19,6 +19,7 @@
AutoSchema, ManualSchema, SchemaGenerator, get_schema_view
)
from rest_framework.schemas.generators import EndpointEnumerator
+from rest_framework.schemas.utils import is_list_view
from rest_framework.test import APIClient, APIRequestFactory
from rest_framework.utils import formatting
from rest_framework.views import APIView
@@ -808,3 +809,15 @@ def test_from_router(self):
with pytest.raises(ValueError):
generator.get_schema()
+
+
+def test_is_list_view_recognises_retrieve_view_subclasses():
+ class TestView(generics.RetrieveAPIView):
+ pass
+
+ path = '/looks/like/a/list/view/'
+ method = 'get'
+ view = TestView()
+
+ is_list = is_list_view(path, method, view)
+ assert not is_list, "RetrieveAPIView subclasses should not be classified as list views."
| Have `schemas.is_list_view` recognise `RetrieveAPIView` subclasses
If you create a `RetrieveAPIView` with a fixed URL (using `request.user` in `get_object()`, say) then `rest_framwork.schemas.is_list_view` will return `True` leasing to schemas with `list` as the key, where `retrieve` is desired.
It would be good if `is_list_view` could recognise this kind of instance.
| @carltongibson Are you already looking at the fix for this one? I was thinking the description made sense and I could try to setup a test case for it and then possibly a fix ...
@matteius I'm very happy for you to have a look at it. 🙂
@carltongibson So I was looking at the code and it seemed your case was falling into the final branch on whether or not the URL ends with a variable. I tried to make the logic more concrete to start that if the view inherits from a ListModelMixin that its a list style and if not when its a RetrieveApiView then its not a list style. That probably doesn't cover every case but gets us further, especially for model views. Let me know what you think of this and if you can think of some additional cases to cover. My next step would be to add test coverage of this change.
- https://github.com/matteius/django-rest-framework/commit/421d546bf56348275d623bb551f467de98b48e7b
@matteius I think that would work for my use-case.
I'm not sure I particularly like the _direction_ of the logic though... it seems to me that the answer to `is_list_view` should reside with the view itself—which is surely the relevant expert—rather than in an ever more baroque introspection function, ever expanded to handle more edge-cases. (This is more general observation than specific feedback on your change.)
I guess mine is a slightly different take on it. Having worked with this api framework for many different internal APIs a common learning is that people sub-class from the wrong primitive view types. The fact is ListModelMixin is an interface for looking up a list of things, and if you inherit your view from it (directly or indirectly) then you should both support a list retrieval and the scehama should reflect this. the generic RetrieveAPIView is also an interface for expressing a view that looks up a singular item.
In my opinion both of these checks are more concrete than logic I left come after it which introspect the URL to see if it ends with a variable. To me that is definitely an assumption that ending in a variable means specific item lookup vs otherwise imply a list. To me, the classes the view inherits from are the most internal thing about the view itself and definitely resides within it.
@matteius No (or "Yes"? 🙂) , in this case I agree. The check is fine.
My issue is more with the "top-down" nature of the schema generation: this leaves the generator (and helper classes) needing to _know_ too much, and quite inflexible, I'm finding. I don't (yet) have a solution for that. Your fix may be appropriate here, but I think it hints at a _smell_.
@carltongibson Hmmm, I so wrote some test cases to try and show this was working, and ended up showing its not working. I am not sure why yet, but the isinstance check isn't detecting the test view as being of that type. Here are my tests: https://github.com/matteius/django-rest-framework/commit/01297b3abfda2ca9c642b1b9638b5530375aa529
@matteius — errr... 🙂
I guess, how about opening a PR for this: as a small improvement I think it's probably worth suggesting — getting `list` for a `retrieve` view isn't great.
We can look at the `isinstance` check and see what's going on there.
| 2017-10-05T12:19:21 |
encode/django-rest-framework | 5,499 | encode__django-rest-framework-5499 | [
"5498"
] | bafbc60006af63c4b306fb2f266c2ea645332cd6 | diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py
--- a/rest_framework/renderers.py
+++ b/rest_framework/renderers.py
@@ -557,9 +557,12 @@ def get_raw_data_form(self, data, view, method, request):
accepted = self.accepted_media_type
context = self.renderer_context.copy()
context['indent'] = 4
- data = {k: v for (k, v) in serializer.data.items()
- if not isinstance(serializer.fields[k],
- serializers.HiddenField)}
+
+ # strip HiddenField from output
+ data = serializer.data.copy()
+ for name, field in serializer.fields.items():
+ if isinstance(field, serializers.HiddenField):
+ data.pop(name, None)
content = renderer.render(data, accepted, context)
else:
content = None
| Key error while building raw_data_form for a PUT request on ModelSerializer with extra field added in to_representation
## 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.)
#5259
## Steps to reproduce
This happens on 3.6.4 onwards
1. Override to_representation of a ModelSerializer to include an extra field (that does not exist in the ModelSerializer) e.g.
```
def to_representation(self, instance):
output = ModelSerializer.to_representation(self, instance)
output['meta_name'] = self.__class__.Meta.model.__name__
return output
```
2. Create a GenericAPI view on this ModelSerilizer and allow GET and PUT method on it
3. Make a GET request to this view via Browsable API
## Expected behavior
We should get serialized data as well as a PUT form. This was the case till 3.6.3 but not after #5259. In this fix a check was added to eliminate HiddenFields in the serializer while serializing for raw data form, but we should ensure that a 'field' is a real field before checking if it is a HiddenField
## Actual behavior
We get a KeyError on line 560 in rest_framework/renderers.py while building the raw form for PUT as 'meta_name' is actually not a field in the serializer but just added in to-representation
Stack trace:
Environment:
```
Request Method: GET
Request URL: /api/nextvisit/217/
Django Version: 1.10.5
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap4',
'rest_framework',
'clinic']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
```
Traceback:
```python
File "/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
217. response = self.process_exception_by_middleware(e, request)
File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
215. response = response.render()
File "/lib/python3.5/site-packages/django/template/response.py" in render
109. self.content = self.rendered_content
File "/lib/python3.5/site-packages/rest_framework/response.py" in rendered_content
72. ret = renderer.render(self.data, accepted_media_type, context)
File "/lib/python3.5/site-packages/rest_framework/renderers.py" in render
706. context = self.get_context(data, accepted_media_type, renderer_context)
File "/lib/python3.5/site-packages/rest_framework/renderers.py" in get_context
640. raw_data_put_form = self.get_raw_data_form(data, view, 'PUT', request)
File "/lib/python3.5/site-packages/rest_framework/renderers.py" in get_raw_data_form
559. data = {k: v for (k, v) in serializer.data.items()
File "/lib/python3.5/site-packages/rest_framework/renderers.py" in <dictcomp>
560. if not isinstance(serializer.fields[k],
File "/lib/python3.5/site-packages/rest_framework/utils/serializer_helpers.py" in __getitem__
148. return self.fields[key]
Exception Type: KeyError at /api/nextvisit/217/
Exception Value: 'meta_name'
```
----
Edited for formatting (@rpkilby)
| 2017-10-13T21:37:57 |
||
encode/django-rest-framework | 5,500 | encode__django-rest-framework-5500 | [
"5456"
] | bafbc60006af63c4b306fb2f266c2ea645332cd6 | diff --git a/rest_framework/compat.py b/rest_framework/compat.py
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -25,14 +25,35 @@
try:
from django.urls import (
- NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve
+ NoReverseMatch, URLPattern as RegexURLPattern, URLResolver as RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve
)
+
except ImportError:
from django.core.urlresolvers import ( # Will be removed in Django 2.0
NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve
)
+def get_regex_pattern(urlpattern):
+ if hasattr(urlpattern, 'pattern'):
+ # Django 2.0
+ return urlpattern.pattern.regex.pattern
+ else:
+ # Django < 2.0
+ return urlpattern.regex.pattern
+
+
+def make_url_resolver(regex, urlpatterns):
+ try:
+ # Django 2.0
+ from django.urls.resolvers import RegexPattern
+ return RegexURLResolver(RegexPattern(regex), urlpatterns)
+
+ except ImportError:
+ # Django < 2.0
+ return RegexURLResolver(regex, urlpatterns)
+
+
try:
import urlparse # Python 2.x
except ImportError:
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
@@ -15,7 +15,7 @@
from rest_framework import exceptions
from rest_framework.compat import (
- RegexURLPattern, RegexURLResolver, coreapi, coreschema
+ RegexURLPattern, RegexURLResolver, coreapi, coreschema, get_regex_pattern
)
from rest_framework.request import clone_request
from rest_framework.settings import api_settings
@@ -135,7 +135,7 @@ def get_api_endpoints(self, patterns=None, prefix=''):
api_endpoints = []
for pattern in patterns:
- path_regex = prefix + pattern.regex.pattern
+ path_regex = prefix + get_regex_pattern(pattern)
if isinstance(pattern, RegexURLPattern):
path = self.get_path_from_regex(path_regex)
callback = pattern.callback
diff --git a/rest_framework/urlpatterns.py b/rest_framework/urlpatterns.py
--- a/rest_framework/urlpatterns.py
+++ b/rest_framework/urlpatterns.py
@@ -2,7 +2,7 @@
from django.conf.urls import include, url
-from rest_framework.compat import RegexURLResolver
+from rest_framework.compat import RegexURLResolver, get_regex_pattern
from rest_framework.settings import api_settings
@@ -11,7 +11,7 @@ def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
for urlpattern in urlpatterns:
if isinstance(urlpattern, RegexURLResolver):
# Set of included URL patterns
- regex = urlpattern.regex.pattern
+ regex = get_regex_pattern(urlpattern)
namespace = urlpattern.namespace
app_name = urlpattern.app_name
kwargs = urlpattern.default_kwargs
@@ -22,7 +22,7 @@ def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
ret.append(url(regex, include((patterns, app_name), namespace), kwargs))
else:
# Regular URL pattern
- regex = urlpattern.regex.pattern.rstrip('$').rstrip('/') + suffix_pattern
+ regex = get_regex_pattern(urlpattern).rstrip('$').rstrip('/') + suffix_pattern
view = urlpattern.callback
kwargs = urlpattern.default_args
name = urlpattern.name
| diff --git a/tests/test_urlpatterns.py b/tests/test_urlpatterns.py
--- a/tests/test_urlpatterns.py
+++ b/tests/test_urlpatterns.py
@@ -5,7 +5,7 @@
from django.conf.urls import include, url
from django.test import TestCase
-from rest_framework.compat import RegexURLResolver, Resolver404
+from rest_framework.compat import Resolver404, make_url_resolver
from rest_framework.test import APIRequestFactory
from rest_framework.urlpatterns import format_suffix_patterns
@@ -28,7 +28,7 @@ def _resolve_urlpatterns(self, urlpatterns, test_paths):
urlpatterns = format_suffix_patterns(urlpatterns)
except Exception:
self.fail("Failed to apply `format_suffix_patterns` on the supplied urlpatterns")
- resolver = RegexURLResolver(r'^/', urlpatterns)
+ resolver = make_url_resolver(r'^/', urlpatterns)
for test_path in test_paths:
request = factory.get(test_path.path)
try:
@@ -43,7 +43,7 @@ def test_trailing_slash(self):
urlpatterns = format_suffix_patterns([
url(r'^test/$', dummy_view),
])
- resolver = RegexURLResolver(r'^/', urlpatterns)
+ resolver = make_url_resolver(r'^/', urlpatterns)
test_paths = [
(URLTestPath('/test.api', (), {'format': 'api'}), True),
| RegexURLResolver no longer exists in Django 2.0(a1)
## 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.)
In testing an application against Django 2.0a1, I ran into a confusing error:
```python
File ".tox/py36-django20/lib/python3.6/site-packages/rest_framework/serializers.py", line 30, in <module>
from rest_framework.compat import JSONField as ModelJSONField
File ".tox/py36-django20/lib/python3.6/site-packages/rest_framework/compat.py", line 26, in <module>
from django.core.urlresolvers import ( # Will be removed in Django 2.0
ModuleNotFoundError: No module named 'django.core.urlresolvers'
```
After investigating, it is related to a shim for older Django versions which now breaks as of Django 2.0a1:
```python
try:
from django.urls import (
NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve
)
except ImportError:
from django.core.urlresolvers import ( # Will be removed in Django 2.0
NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve
)
```
https://github.com/encode/django-rest-framework/blob/607e4edca77441f057ce40cd90175b1b5700f316/rest_framework/compat.py#L28
It turns out, `RegexURLResolver` no longer exists. I would imagine this is related to the new simplified URL patterns.
I'm unsure what the exact fix is at this moment, as I haven't dug into the new url implementation(s) yet, but I do recall that the old regex functionality is being maintained.
| Pretty sure it's `URLPattern` and `URLResolver` now. I'm trying to figure this one out.
Ok, so as far as I've been able to figure out, they're far from drop-in replacements. The entire way resolving paths used to work appears to have been refactored and you would need to do some work to work with this new api. You would need some compatibility shim, as some of the attributes have been renamed or layers of indirection have been added since Django 2.0.
Its now `django.urls.resolvers.RegexURLPattern`
`django.urls.resolvers.RegexURLPattern` doesn't exist anymore either, it was changed in https://github.com/django/django/commit/df41b5a05d4e00e80e73afe629072e37873e767a.
Also running Django 2.x alpha with the latest Rest Framework
When running python manage.py compress the following output is returned:
https://gist.github.com/diemuzi/e9049c96b703d87d061caa6d018be3fd
Just adding it here in case it helps with any debugging. Would be happy to do anything else to help too.
I just installed DRF 3.7, and it seems that there still is a compatibility issue with Django 2.0 (a1):
```bash
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "~/myproject/urls.py", line 4, in <module>
from django_rest_passwordreset.views import reset_password_request_token, reset_password_confirm
File "~/myproject/views.py", line 8, in <module>
from rest_framework import parsers, renderers, status
File "~/myproject/venv/lib/python3.5/site-packages/rest_framework/parsers.py", line 23, in <module>
from rest_framework import renderers
File "~/myproject/venv/lib/python3.5/site-packages/rest_framework/renderers.py", line 24, in <module>
from rest_framework import VERSION, exceptions, serializers, status
File "~/myproject/venv/lib/python3.5/site-packages/rest_framework/exceptions.py", line 17, in <module>
from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList
File "~/myproject/venv/lib/python3.5/site-packages/rest_framework/utils/serializer_helpers.py", line 8, in <module>
from rest_framework.compat import unicode_to_repr
File "~/myproject/venv/lib/python3.5/site-packages/rest_framework/compat.py", line 31, in <module>
from django.core.urlresolvers import ( # Will be removed in Django 2.0
ImportError: No module named 'django.core.urlresolvers'
```
Could be fixed by PR #5485
| 2017-10-14T19:48:10 |
encode/django-rest-framework | 5,524 | encode__django-rest-framework-5524 | [
"5523"
] | 916a4a27ef6d045475a61a1131439d2597dfc2ce | diff --git a/rest_framework/checks.py b/rest_framework/checks.py
--- a/rest_framework/checks.py
+++ b/rest_framework/checks.py
@@ -12,7 +12,10 @@ def pagination_system_check(app_configs, **kwargs):
"You have specified a default PAGE_SIZE pagination rest_framework setting,"
"without specifying also a DEFAULT_PAGINATION_CLASS.",
hint="The default for DEFAULT_PAGINATION_CLASS is None. "
- "In previous versions this was PageNumberPagination",
+ "In previous versions this was PageNumberPagination. "
+ "If you wish to define PAGE_SIZE globally whilst defining "
+ "pagination_class on a per-view basis you may silence this check.",
+ id="rest_framework.W001"
)
)
return errors
| Update checks.py
refs: #5170
## Description
If statement caused the error in normal cases without the solution before.
so I changed if statement to check only in user-settings and give solution and hint to handle that error
| 2017-10-23T10:24:12 |
||
encode/django-rest-framework | 5,532 | encode__django-rest-framework-5532 | [
"5528"
] | 1c9ad52cb6105c442b48fab2e2114969729b0ed9 | 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
@@ -222,12 +222,11 @@ def get_allowed_methods(self, callback):
if hasattr(callback, 'actions'):
actions = set(callback.actions.keys())
http_method_names = set(callback.cls.http_method_names)
- return [method.upper() for method in actions & http_method_names]
+ methods = [method.upper() for method in actions & http_method_names]
+ else:
+ methods = callback.cls().allowed_methods
- return [
- method for method in
- callback.cls().allowed_methods if method not in ('OPTIONS', 'HEAD')
- ]
+ return [method for method in methods if method not in ('OPTIONS', 'HEAD')]
class SchemaGenerator(object):
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -901,3 +901,53 @@ class TestView(generics.RetrieveAPIView):
is_list = is_list_view(path, method, view)
assert not is_list, "RetrieveAPIView subclasses should not be classified as list views."
+
+
+def test_head_and_options_methods_are_excluded():
+ """
+ Regression test for #5528
+ https://github.com/encode/django-rest-framework/issues/5528
+
+ Viewset OPTIONS actions were not being correctly excluded
+
+ Initial cases here shown to be working as expected.
+ """
+
+ @api_view(['options', 'get'])
+ def fbv(request):
+ pass
+
+ inspector = EndpointEnumerator()
+
+ path = '/a/path/'
+ callback = fbv
+
+ assert inspector.should_include_endpoint(path, callback)
+ assert inspector.get_allowed_methods(callback) == ["GET"]
+
+ class AnAPIView(APIView):
+
+ def get(self, request, *args, **kwargs):
+ pass
+
+ def options(self, request, *args, **kwargs):
+ pass
+
+ callback = AnAPIView.as_view()
+
+ assert inspector.should_include_endpoint(path, callback)
+ assert inspector.get_allowed_methods(callback) == ["GET"]
+
+ class AViewSet(ModelViewSet):
+
+ @detail_route(methods=['options', 'get'])
+ def custom_action(self, request, pk):
+ pass
+
+ callback = AViewSet.as_view({
+ "options": "custom_action",
+ "get": "custom_action"
+ })
+
+ assert inspector.should_include_endpoint(path, callback)
+ assert inspector.get_allowed_methods(callback) == ["GET"]
| Documentation fails when using detail_route with 'options' 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](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.)
Hello, thanks for this awesome piece of software!
The issue is the following:
When using detail_route in ModelViewSet and using "options" method , the documentation page fails with an exception.
## Steps to reproduce
1. Create a project with ModelViewSet
2. Add this method in the class
```
@detail_route(methods=['options', 'get', 'put'])
def test(self, request, *args, **kwargs):
pass
```
3. Check that the documentation is not working
## Expected behavior
The documentation should work using the "options" method
## Actual behavior
The documentation page is crashing with exception
KeyError: 'options'
Thanks for the help!
Amit.
| 2017-10-25T08:48:10 |
|
encode/django-rest-framework | 5,544 | encode__django-rest-framework-5544 | [
"5541"
] | 5009aeff180085d7d3a82c37d8f992d521d612a2 | diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py
--- a/rest_framework/mixins.py
+++ b/rest_framework/mixins.py
@@ -27,7 +27,7 @@ def perform_create(self, serializer):
def get_success_headers(self, data):
try:
- return {'Location': data[api_settings.URL_FIELD_NAME]}
+ return {'Location': str(data[api_settings.URL_FIELD_NAME])}
except (TypeError, KeyError):
return {}
| Unhanded exception is wsgiref (py3) caused from CreateModelMixin
## 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
## Steps to reproduce
- python3.x (reporduceable on 3.4 - 3.6)
- Install django 2.0beta & latest DRF
- Create simple model
- Create simple HyperlinkedModelSerializer that uses 'url' field instead of 'id'
- Create simple viewset
- run standard django runserver (wsgiref)
- POST new model
## Expected behavior
- model gets created without any issues
## Actual behavior
- models is created but:
- Exception is raised by wsgiref from here https://github.com/python/cpython/blob/3.6/Lib/wsgiref/headers.py#L43
The issue is that header is of type `Hyperlink`, and wsgiref explicitly checks for `str` only
It's caused here: https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py#L30
The data is not a `str`
| @canni Thanks for the report. Any chance you could post a minimal test project so we can quickly reproduce this?
Can you also post the full traceback so we can see that? `get_success_headers` is meant to return a `dict` so the problem isn't there exactly.
Our test suite is [passing against Django `master`](https://travis-ci.org/encode/django-rest-framework/jobs/294611809) — so we must be missing a test somewhere.
The reproduce steps seem simple enough. This must be new: what changed and where? (Is this even our bug...?)
> so we must be missing a test somewhere
The wsgiref tests are just more particular about WSGI conformance.
Unlikely that this is actually causing any issues with server implementations, since we've not had it raised in any other context, but we could wrap that expression with `str(...)` for completeness. | 2017-10-30T12:23:18 |
|
encode/django-rest-framework | 5,548 | encode__django-rest-framework-5548 | [
"5496"
] | e5cee43000e6ebe1db769165ef02011533de1922 | diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py
--- a/rest_framework/renderers.py
+++ b/rest_framework/renderers.py
@@ -812,6 +812,7 @@ class DocumentationRenderer(BaseRenderer):
format = 'html'
charset = 'utf-8'
template = 'rest_framework/docs/index.html'
+ error_template = 'rest_framework/docs/error.html'
code_style = 'emacs'
languages = ['shell', 'javascript', 'python']
@@ -824,9 +825,19 @@ def get_context(self, data, request):
}
def render(self, data, accepted_media_type=None, renderer_context=None):
- template = loader.get_template(self.template)
- context = self.get_context(data, renderer_context['request'])
- return template.render(context, request=renderer_context['request'])
+ if isinstance(data, coreapi.Document):
+ template = loader.get_template(self.template)
+ context = self.get_context(data, renderer_context['request'])
+ return template.render(context, request=renderer_context['request'])
+ else:
+ template = loader.get_template(self.error_template)
+ context = {
+ "data": data,
+ "request": renderer_context['request'],
+ "response": renderer_context['response'],
+ "debug": settings.DEBUG,
+ }
+ return template.render(context, request=renderer_context['request'])
class SchemaJSRenderer(BaseRenderer):
| Document not being generated correctly in docs
## 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](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.)
- [ ] I have reduced the issue to the simplest possible case.
- [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
## Steps to reproduce
## Expected behavior
Should display docs, when visiting /docs/
## Actual behavior
Error in template documentation/sidebar.html, 'dict' object has no attribute 'data'
It looks like the document is not being generated with data, also document.links is missing.

| There's little we can do without more context.
Do you have a simple test case we can reproduce ?
Will reopen if more informations are provided.
Steps to reproduce, in my case
Following steps in documentation:
http://www.django-rest-framework.org/topics/documenting-your-api/
Just went through those steps again and worked on my pet project.
@upatricck This looks similar to #5472 and #5395. (Are you running 3.7.0? Do you have `link` named `data`?)
This works under usual circumstances so you need to do some work to tell us why it's failing for you. Other we cannot help.
One thought is that we're expecting to see a `coreapi.Document` here. Your error is suggesting you've got a `dict`. Where's that `dict` coming from?
I got the same problem:
```
File "/home/kuboon/kikof/env/local/lib/python2.7/site-packages/rest_framework/templatetags/rest_framework.py", line 261, in data
return value.data
AttributeError: 'dict' object has no attribute 'data'
```
And value was:
`{u'detail': u'Authentication credentials were not provided.'}`
My temp fix:
```
from rest_framework.permissions import AllowAny
url(r'^api/new-docs/', include_docs_urls(..., permission_classes=(AllowAny,))),
```
I don't use sessions, only token auth
@kub00n Some thoughts:
* What are your authentication classes here? (Your defaults if you're not setting any?) If you disable authentication — `authentication_classes=[]` — does it work?
* I'm not sure authentication without Session Auth makes sense here. You're viewing a web page — either you're logged in (with the Session) or you're not.
* What's the behaviour we want for an authentication failure here? (403, rather than 500)
* (Why I|i)s the renderer setting the error dict as the `document` value in the template context?
I'm going to reopen this to give time to investigate.
I encountered this when I created a new project for DRF, and I hadn't yet created any URLs for DRF, I only had classic Django views. After I added my first URLs by using a DRF SimpleRouter, the problem went away.
This looks like we're just not handling the empty case correctly. (Some auth issue, no schema, etc.) Should be easy enough to clean up.
Right, I'm able to reproduce this a few ways:
1. You have any kind of `IsAuthenticated` permission as your default and or explicitly on your `SchemaView`, or call to `include_docs_url` and are either logged out, or do not have `SessionAuthentication` enabled.
2. You are logged in but do not have permissions to access the view.
3. Your call to SchemaGenerator returns `None` (i.e. no routed APIViews). (This last case raises `PermissionDenied`, so it reduces to 2.)
I was able to reproduce this bug by explicitly passing auth token in headers (using chrome extension), while using default drf ```TokenAuthentication```.
Default permission is ```AllowAny```
@Zeliboba5: Just to be certain, what's the value of `document` in the context when you do this? (i.e. what's the error dict?) Thanks.
@carltongibson There is no ```document``` in context, but it only value in context says about user being inactive, which is true. If I activate user - problem does not occur, sorry if previous comment was misleading about that.
Fine. That’s case 1 again. No problem. Thank you! | 2017-10-31T10:26:37 |
|
encode/django-rest-framework | 5,562 | encode__django-rest-framework-5562 | [
"5531"
] | 565c722762b623bf0c5da68eab2860b3c86fdb48 | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -997,7 +997,7 @@ 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, **kwargs):
+ localize=False, rounding=None, **kwargs):
self.max_digits = max_digits
self.decimal_places = decimal_places
self.localize = localize
@@ -1029,6 +1029,12 @@ def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=
self.validators.append(
MinValueValidator(self.min_value, message=message))
+ if rounding is not None:
+ valid_roundings = [v for k, v in vars(decimal).items() if k.startswith('ROUND_')]
+ assert rounding in valid_roundings, (
+ 'Invalid rounding option %s. Valid values for rounding are: %s' % (rounding, valid_roundings))
+ self.rounding = rounding
+
def to_internal_value(self, data):
"""
Validate that the input is a decimal number and return a Decimal
@@ -1121,6 +1127,7 @@ def quantize(self, value):
context.prec = self.max_digits
return value.quantize(
decimal.Decimal('.1') ** self.decimal_places,
+ rounding=self.rounding,
context=context
)
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -3,7 +3,7 @@
import re
import unittest
import uuid
-from decimal import Decimal
+from decimal import ROUND_DOWN, ROUND_UP, Decimal
import django
import pytest
@@ -1092,8 +1092,21 @@ class TestNoDecimalPlaces(FieldValues):
field = serializers.DecimalField(max_digits=6, decimal_places=None)
-# Date & time serializers...
+class TestRoundingDecimalField(TestCase):
+ def test_valid_rounding(self):
+ field = serializers.DecimalField(max_digits=4, decimal_places=2, rounding=ROUND_UP)
+ assert field.to_representation(Decimal('1.234')) == '1.24'
+
+ field = serializers.DecimalField(max_digits=4, decimal_places=2, rounding=ROUND_DOWN)
+ assert field.to_representation(Decimal('1.234')) == '1.23'
+
+ def test_invalid_rounding(self):
+ with pytest.raises(AssertionError) as excinfo:
+ serializers.DecimalField(max_digits=1, decimal_places=1, rounding='ROUND_UNKNOWN')
+ assert 'Invalid rounding option' in str(excinfo.value)
+
+# Date & time serializers...
class TestDateField(FieldValues):
"""
Valid and invalid values for `DateField`.
| Add rounding parameter to DecimalField
## 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
- Have a decimal field named score with decimal_places=1
- Serialize an objet with a score attribute that has a value of Decimal('7.25')
## Expected behavior
Output shows 7.3
## Actual behavior
Output shows 7.2.
The behaviour does not match human expectations and DecimalField does not accept a rounding parameter (for the Decimal.quantize method).
It seems overkill to install something like django-rest-framework-braces to work around one missing param in the API.
| I think this is a sensible addition, given that `quantize()` only has two arguments (in addition to the context).
For now, you *should* be able to control rounding by altering the global decimal context. It's not ideal, but it should work. | 2017-11-06T08:17:26 |
encode/django-rest-framework | 5,590 | encode__django-rest-framework-5590 | [
"5583",
"5582"
] | 15024f3f07b9311887ad6f5afb366f6c032c0486 | diff --git a/rest_framework/request.py b/rest_framework/request.py
--- a/rest_framework/request.py
+++ b/rest_framework/request.py
@@ -250,9 +250,10 @@ def _load_data_and_files(self):
else:
self._full_data = self._data
- # copy files refs to the underlying request so that closable
+ # copy data & files refs to the underlying request so that closable
# objects are handled appropriately.
- self._request._files = self._files
+ self._request._post = self.POST
+ self._request._files = self.FILES
def _load_stream(self):
"""
| diff --git a/tests/test_middleware.py b/tests/test_middleware.py
--- a/tests/test_middleware.py
+++ b/tests/test_middleware.py
@@ -1,34 +1,76 @@
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 rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.models import Token
+from rest_framework.request import is_form_media_type
+from rest_framework.response import Response
from rest_framework.test import APITestCase
from rest_framework.views import APIView
+
+class PostView(APIView):
+ def post(self, request):
+ return Response(data=request.data, status=200)
+
+
urlpatterns = [
- url(r'^$', APIView.as_view(authentication_classes=(TokenAuthentication,))),
+ url(r'^auth$', APIView.as_view(authentication_classes=(TokenAuthentication,))),
+ url(r'^post$', PostView.as_view()),
]
-class MyMiddleware(object):
+class RequestUserMiddleware(object):
+ def __init__(self, get_response):
+ self.get_response = get_response
- def process_response(self, request, response):
+ def __call__(self, request):
+ response = self.get_response(request)
assert hasattr(request, 'user'), '`user` is not set on request'
- assert request.user.is_authenticated(), '`user` is not authenticated'
+ assert request.user.is_authenticated, '`user` is not authenticated'
+
+ return response
+
+
+class RequestPOSTMiddleware(object):
+ def __init__(self, get_response):
+ self.get_response = get_response
+
+ def __call__(self, request):
+ assert isinstance(request, HttpRequest)
+
+ # Parse body with underlying Django request
+ request.body
+
+ # Process request with DRF view
+ response = self.get_response(request)
+
+ # Ensure request.POST is set as appropriate
+ if is_form_media_type(request.content_type):
+ assert request.POST == {'foo': ['bar']}
+ else:
+ assert request.POST == {}
+
return response
@override_settings(ROOT_URLCONF='tests.test_middleware')
class TestMiddleware(APITestCase):
+
+ @override_settings(MIDDLEWARE=('tests.test_middleware.RequestUserMiddleware',))
def test_middleware_can_access_user_when_processing_response(self):
user = User.objects.create_user('john', '[email protected]', 'password')
key = 'abcd1234'
Token.objects.create(key=key, user=user)
- with self.settings(
- MIDDLEWARE_CLASSES=('tests.test_middleware.MyMiddleware',)
- ):
- auth = 'Token ' + key
- self.client.get('/', HTTP_AUTHORIZATION=auth)
+ self.client.get('/auth', HTTP_AUTHORIZATION='Token %s' % key)
+
+ @override_settings(MIDDLEWARE=('tests.test_middleware.RequestPOSTMiddleware',))
+ def test_middleware_can_access_request_post_when_processing_response(self):
+ response = self.client.post('/post', {'foo': 'bar'})
+ assert response.status_code == 200
+
+ response = self.client.post('/post', {'foo': 'bar'}, format='json')
+ assert response.status_code == 200
| Failing test for #5582
## Description
A failing test for #5582. Works on 3.6.3, doesn't work on 3.6.4 and 3.7.0-3.7.3.
### Potential solution
Adding
```python
self._request._post = self._data
```
to `Request._load_data_and_files` makes the test pass, but I am not 100% sure this is the correct fix.
DRF 3.6.4/3.7.0 breaks reading request.POST if request.body was read
## 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
- Create any DRF view
- Add a middleware or a signal handler that uses `request.POST`
## Expected behavior
- `request.POST` works fine
## Actual behavior
- `AttributeError` is raised by Django's `HttpRequest._load_post_or_files`
----
The reason the exception is raised is because Django's `WSGIReqeust.POST` checks `if hasattr(self, '_post')` (which it doesn't have) and proceeds to `_load_post_and_data`, which in turn calls `parse_file_upload` which tries to set `self.upload_handlers`, but the `upload_handler.setter` checks `if hasattr(self, '_files')`. At this point, `_files` has already been [set by DRF](https://github.com/encode/django-rest-framework/blob/master/rest_framework/request.py#L255) (to make closing file handles possible), so it raises an exception.
I think the solution to this is to set `request._post` in addition to `request._files` to preserve the interface. I am not sure if there's an easy way to set it to the original `POST` as it seems DRF only calls `_load_data_and_files`, which deserializes the data etc.
----
edited for formatting (@rpkilby)
|
For context, this was changed in #5262, which superseded #5255. Amusingly enough, the original PR did set `_post` in addition to `_files`.
@D3X - would you be able to reduce this into a failing test case?
@rpkilby Thanks for the prompt response. I'll try to submit a PR later tonight.
(Misclicked on the mobile version and closed the ticket by mistake)
@rpkilby I played with it a bit and it seems it only breaks if `request.body` was read before DRF did its magic.
Also have added a failing test PR, as you can see above.
This doesn't look very new to me. Did you had that issue in prior versions ?
@xordoquy No. I bumped into it today, while trying to update my project's dependencies, including updating DRF from 3.6.3 to 3.6.4 (can't go to 3.7 yet). It has worked fine before that. | 2017-11-13T20:08:21 |
encode/django-rest-framework | 5,599 | encode__django-rest-framework-5599 | [
"5596"
] | 9f66e8baddd9d8106a121b159356422086e7d90c | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -1102,6 +1102,17 @@ def get_field_names(self, declared_fields, info):
if exclude is not None:
# If `Meta.exclude` is included, then remove those fields.
for field_name in exclude:
+ assert field_name not in self._declared_fields, (
+ "Cannot both declare the field '{field_name}' and include "
+ "it in the {serializer_class} 'exclude' option. Remove the "
+ "field or, if inherited from a parent serializer, disable "
+ "with `{field_name} = None`."
+ .format(
+ field_name=field_name,
+ serializer_class=self.__class__.__name__
+ )
+ )
+
assert field_name in fields, (
"The field '{field_name}' was included on serializer "
"{serializer_class} in the 'exclude' option, but does "
| 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
@@ -900,6 +900,22 @@ class Meta:
"Cannot set both 'fields' and 'exclude' options on serializer ExampleSerializer."
)
+ def test_declared_fields_with_exclude_option(self):
+ class ExampleSerializer(serializers.ModelSerializer):
+ text = serializers.CharField()
+
+ class Meta:
+ model = MetaClassTestModel
+ exclude = ('text',)
+
+ expected = (
+ "Cannot both declare the field 'text' and include it in the "
+ "ExampleSerializer 'exclude' option. Remove the field or, if "
+ "inherited from a parent serializer, disable with `text = None`."
+ )
+ with self.assertRaisesMessage(AssertionError, expected):
+ ExampleSerializer().fields
+
class Issue2704TestCase(TestCase):
def test_queryset_all(self):
| ModelSerializer exclude won't work well when field duplicate declear in Serializer
## 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
I found that when I use ModelSerializer, if I set a field in ModelSerializer which is duplicate in model. Then ModelSerializer 's exclude attribute won't work well. It still return the exclude fields.
I traced down the code, and found that it failed because `ModelSerializer`.`get_field_names` exclude fields by using list. Since I have set the field in the ModelSerializer, there are two fields name in the list returned by `ModelSerializer`.`get_default_field_names`.
django model I except to have
```python
class Car(models.Model):
name = models.CharField(max_length=128)
username = models.CharField(max_length=128)
```
serializar I have
```python
class VersionModelSerializer(serializers.ModelSerializer):
username = fields.IntegerField(validators=my_validator)
class Meta:
model = models.Car
exclude = ('username')
```
## Expected behavior
Excepted to return data like
```
{
"name": "car_name"
}
```
## Actual behavior
but username exists in the response like
```
{
"name": "car_name",
"username": "username"
}
```
according to the reason I explain above, I think `ModelSerializer`.`get_field_names` should use `set` instead of `list` to exclude fields.
| In such case, DRF should fail hard and refuse to start.
From the documentation:
> The names in the fields and exclude attributes will normally map to model fields on the model class.
> Alternatively names in the fields options can map to properties or methods which take no arguments that exist on the model class.
So I'm in favor of closing the issue as invalid since the documentation implies `exclude` fields are relating to model's and not those explicitly defined in the serializer.
I’m with @xordoquy here.
I look at the example serialiser and think “why would you explicitly define a field you’re going to exclude?” No doubt there’s some reuse scenario in play but it’s not the intended use: exclude is secondary to fields, just for some quick cases, fields is to be preferred, and fields requires including defined fields. (Thus this is a feature we can live with.) | 2017-11-15T21:40:57 |
encode/django-rest-framework | 5,600 | encode__django-rest-framework-5600 | [
"4033"
] | d71bd57b645190cf3edb8772f8886272c30c2a6b | diff --git a/rest_framework/request.py b/rest_framework/request.py
--- a/rest_framework/request.py
+++ b/rest_framework/request.py
@@ -10,6 +10,9 @@
"""
from __future__ import unicode_literals
+import sys
+from contextlib import contextmanager
+
from django.conf import settings
from django.http import QueryDict
from django.http.multipartparser import parse_header
@@ -59,6 +62,24 @@ def __exit__(self, *args, **kwarg):
self.view.action = self.action
+class WrappedAttributeError(Exception):
+ pass
+
+
+@contextmanager
+def wrap_attributeerrors():
+ """
+ Used to re-raise AttributeErrors caught during authentication, preventing
+ these errors from otherwise being handled by the attribute access protocol.
+ """
+ try:
+ yield
+ except AttributeError:
+ info = sys.exc_info()
+ exc = WrappedAttributeError(str(info[1]))
+ six.reraise(type(exc), exc, info[2])
+
+
class Empty(object):
"""
Placeholder for unset attributes.
@@ -191,7 +212,8 @@ def user(self):
by the authentication classes provided to the request.
"""
if not hasattr(self, '_user'):
- self._authenticate()
+ with wrap_attributeerrors():
+ self._authenticate()
return self._user
@user.setter
@@ -214,7 +236,8 @@ def auth(self):
request, such as an authentication token.
"""
if not hasattr(self, '_auth'):
- self._authenticate()
+ with wrap_attributeerrors():
+ self._authenticate()
return self._auth
@auth.setter
@@ -233,7 +256,8 @@ def successful_authenticator(self):
to authenticate the request, or `None`.
"""
if not hasattr(self, '_authenticator'):
- self._authenticate()
+ with wrap_attributeerrors():
+ self._authenticate()
return self._authenticator
def _load_data_and_files(self):
@@ -316,7 +340,7 @@ def _parse(self):
try:
parsed = parser.parse(stream, media_type, self.parser_context)
- except:
+ except Exception:
# If we get an exception during parsing, fill in empty data and
# re-raise. Ensures we don't simply repeat the error when
# attempting to render the browsable renderer response, or when
| diff --git a/tests/test_request.py b/tests/test_request.py
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -6,8 +6,10 @@
import os.path
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
from django.contrib.sessions.middleware import SessionMiddleware
from django.core.files.uploadedfile import SimpleUploadedFile
@@ -17,7 +19,7 @@
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.parsers import BaseParser, FormParser, MultiPartParser
-from rest_framework.request import Request
+from rest_framework.request import Request, WrappedAttributeError
from rest_framework.response import Response
from rest_framework.test import APIClient, APIRequestFactory
from rest_framework.views import APIView
@@ -185,7 +187,8 @@ def setUp(self):
# available to login and logout functions
self.wrapped_request = factory.get('/')
self.request = Request(self.wrapped_request)
- SessionMiddleware().process_request(self.request)
+ SessionMiddleware().process_request(self.wrapped_request)
+ AuthenticationMiddleware().process_request(self.wrapped_request)
User.objects.create_user('ringo', '[email protected]', 'yellow')
self.user = authenticate(username='ringo', password='yellow')
@@ -200,9 +203,9 @@ def test_user_can_login(self):
def test_user_can_logout(self):
self.request.user = self.user
- self.assertFalse(self.request.user.is_anonymous)
+ assert not self.request.user.is_anonymous
logout(self.request)
- self.assertTrue(self.request.user.is_anonymous)
+ assert self.request.user.is_anonymous
def test_logged_in_user_is_set_on_wrapped_request(self):
login(self.request, self.user)
@@ -215,22 +218,27 @@ def test_calling_user_fails_when_attribute_error_is_raised(self):
"""
class AuthRaisesAttributeError(object):
def authenticate(self, request):
- import rest_framework
- rest_framework.MISSPELLED_NAME_THAT_DOESNT_EXIST
+ self.MISSPELLED_NAME_THAT_DOESNT_EXIST
- self.request = Request(factory.get('/'), authenticators=(AuthRaisesAttributeError(),))
- SessionMiddleware().process_request(self.request)
+ request = Request(self.wrapped_request, authenticators=(AuthRaisesAttributeError(),))
- login(self.request, self.user)
- try:
- self.request.user
- except AttributeError as error:
- assert str(error) in (
- "'module' object has no attribute 'MISSPELLED_NAME_THAT_DOESNT_EXIST'", # Python < 3.5
- "module 'rest_framework' has no attribute 'MISSPELLED_NAME_THAT_DOESNT_EXIST'", # Python >= 3.5
- )
- else:
- assert False, 'AttributeError not raised'
+ # The middleware processes the underlying Django request, sets anonymous user
+ assert self.wrapped_request.user.is_anonymous
+
+ # The DRF request object does not have a user and should run authenticators
+ expected = r"no attribute 'MISSPELLED_NAME_THAT_DOESNT_EXIST'"
+ with pytest.raises(WrappedAttributeError, match=expected):
+ request.user
+
+ # python 2 hasattr fails for *any* exception, not just AttributeError
+ if six.PY2:
+ return
+
+ with pytest.raises(WrappedAttributeError, match=expected):
+ hasattr(request, 'user')
+
+ with pytest.raises(WrappedAttributeError, match=expected):
+ login(request, self.user)
class TestAuthSetter(TestCase):
| Suppressed AttributeError When Authenticating
My implementation of [BaseAuthentication's authenticate](https://github.com/tomchristie/django-rest-framework/blob/dd3b47ccbda59487e3768f3397a563fd740f667a/rest_framework/authentication.py#L40) had a bug where an AttributeError was thrown. DRF handles that by catching the thrown AttributeError and then accessing and returning "user" on Django's request instead.
The [perform_authenticate](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/views.py#L310) tries to authenticate when "user" is missing (see [invoke _authenticate](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/request.py#L195) but if the code for authenticating throws an AttributeError, then Django's request's user will be accessed instead, see [`__getattribute__`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/request.py#L354-L359).
The result of this behaviour was that the request was authorised when entering the DRF view but when executing request.user inside the view an AnonymousUser instance was received instead of an instance of my class that inherits BaseAuthentication and implements authenticate(self, request).
AttributeError thrown when accessing "user" attribute on a DRF request shouldn't be caught and it shouldn't access user on Django's request.
One simple but ugly way to solve it would be to check if attr is "user" at https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/request.py#L357 and in that case rethrow the AttributeError instead of accessing the attribute on _request.
| Unless we remove support for Python 2, using `hasattr` will not [be a better choice](https://hynek.me/articles/hasattr/).
I spent over 10 hours fixing this while porting raven to python 3 because of that subtle difference.
@xordoquy Sorry about that and thanks for answering.
However, that's not what I meant. Please see referenced pull request.
We found this problem when developing custom auth backends. Our implementation accidentally ate an AttributeError. This problem leads to difficult-to-debug problems. The AttributeError gets eaten because of the `__getattribute__` proxy to Django's request object. We're not sure how to actually fix this in the best way, but hopefully the test shows the issues.
| 2017-11-16T00:17:36 |
encode/django-rest-framework | 5,618 | encode__django-rest-framework-5618 | [
"2771"
] | d71bd57b645190cf3edb8772f8886272c30c2a6b | diff --git a/rest_framework/request.py b/rest_framework/request.py
--- a/rest_framework/request.py
+++ b/rest_framework/request.py
@@ -11,7 +11,7 @@
from __future__ import unicode_literals
from django.conf import settings
-from django.http import QueryDict
+from django.http import HttpRequest, QueryDict
from django.http.multipartparser import parse_header
from django.http.request import RawPostDataException
from django.utils import six
@@ -132,6 +132,12 @@ class Request(object):
def __init__(self, request, parsers=None, authenticators=None,
negotiator=None, parser_context=None):
+ assert isinstance(request, HttpRequest), (
+ 'The `request` argument must be an instance of '
+ '`django.http.HttpRequest`, not `{}.{}`.'
+ .format(request.__class__.__module__, request.__class__.__name__)
+ )
+
self._request = request
self.parsers = parsers or ()
self.authenticators = authenticators or ()
| diff --git a/tests/test_metadata.py b/tests/test_metadata.py
--- a/tests/test_metadata.py
+++ b/tests/test_metadata.py
@@ -9,12 +9,11 @@
exceptions, metadata, serializers, status, versioning, views
)
from rest_framework.renderers import BrowsableAPIRenderer
-from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
from .models import BasicModel
-request = Request(APIRequestFactory().options('/'))
+request = APIRequestFactory().options('/')
class TestMetadata:
diff --git a/tests/test_request.py b/tests/test_request.py
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -25,6 +25,18 @@
factory = APIRequestFactory()
+class TestInitializer(TestCase):
+ def test_request_type(self):
+ request = Request(factory.get('/'))
+
+ message = (
+ 'The `request` argument must be an instance of '
+ '`django.http.HttpRequest`, not `rest_framework.request.Request`.'
+ )
+ with self.assertRaisesMessage(AssertionError, message):
+ Request(request)
+
+
class PlainTextParser(BaseParser):
media_type = 'text/plain'
| initialize_request in view.py converts the request in Request without checking the incoming request type
I am trying to call a class baed view from another class based view using [This SO](http://stackoverflow.com/questions/14956678/django-call-class-based-view-from-another-class-based-view) post. I called a class baed view by passing in the request like `MyClassBasedView.as_view()(request)`. When I tried to access the HTTPRequest from request, I had to access it like request._request._request, instead of request._request. I checked the code in views.py and it is converting the incoming request to Request without checking the instance of request. I managed it by using `MyClassBasedView.as_view()(request._request)`
This is my first reporting of an issue. Please be gentle if I violated any guideline.
| Calling a view from another view isn't really supported behavior so odd things may happen, but we _could_ modify the behavior you saw eg. by modifying https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/request.py#L138 slightly so that passing a `Request` to `Request` uses the only underlying `HTTPRequest`, rather then ending up with the convoluted `._request._request`.
There might also be some cases where that'd be helpful if folks are manually constructing `Request` instances in test cases and passing them to the view.
I'm slightly unclear _why_ you'd need to access the underlying `HTTPRequest` instance tho, as the proxying behavior we provide should generally ensure that it's not needed.
I think this is related to a use case I'm trying to implement which is effectively [batching up data from many views](https://groups.google.com/forum/?fromgroups#!topic/django-rest-framework/39aJuJLpVmw).
If we do nothing else we should at least raise an error in this case.
| 2017-11-23T04:03:55 |
encode/django-rest-framework | 5,624 | encode__django-rest-framework-5624 | [
"5615"
] | c63e35cb09170e1166896ad31a1bb9a121aaa2f8 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -6,7 +6,7 @@
import sys
from io import open
-from setuptools import setup
+from setuptools import setup, find_packages
try:
from pypandoc import convert
@@ -28,31 +28,6 @@ def get_version(package):
return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
-def get_packages(package):
- """
- Return root package and all sub-packages.
- """
- return [dirpath
- for dirpath, dirnames, filenames in os.walk(package)
- if os.path.exists(os.path.join(dirpath, '__init__.py'))]
-
-
-def get_package_data(package):
- """
- Return all files under the root package, that are not in a
- package themselves.
- """
- walk = [(dirpath.replace(package + os.sep, '', 1), filenames)
- for dirpath, dirnames, filenames in os.walk(package)
- if not os.path.exists(os.path.join(dirpath, '__init__.py'))]
-
- filepaths = []
- for base, filenames in walk:
- filepaths.extend([os.path.join(base, filename)
- for filename in filenames])
- return {package: filepaths}
-
-
version = get_version('rest_framework')
@@ -84,8 +59,8 @@ def get_package_data(package):
long_description=read_md('README.md'),
author='Tom Christie',
author_email='[email protected]', # SEE NOTE BELOW (*)
- packages=get_packages('rest_framework'),
- package_data=get_package_data('rest_framework'),
+ packages=find_packages(exclude=['tests*']),
+ include_package_data=True,
install_requires=[],
zip_safe=False,
classifiers=[
| Wheels include .DS_Store files.
## Steps to reproduce
* Download latest wheel from PyPI (currently https://pypi.python.org/pypi/djangorestframework/3.7.3, https://pypi.python.org/packages/f5/2c/3c3c81b8ecd60952c20ccd5fc1d19c0b22731c80c75649dd2e3fef361aaf/djangorestframework-3.7.3-py2.py3-none-any.whl#md5=ee78a9aaddc972e9bf75ebaa4c0d6ff5)
* List the files in the wheel
* Search for DS_Store in the results
## Expected behavior
No hits.
## Actual behavior
```
unzip -l djangorestframework-3.7.3-py2.py3-none-any.whl | grep DS
6148 07-01-2014 01:42 rest_framework/templates/.DS_Store
6148 09-28-2017 10:00 rest_framework/templates/rest_framework/.DS_Store
```
| I think the issue here is the use of `package_data`. Since we provide a `MANIFEST.in`, we should be able to just use `include_package_data=True`.
Incoming `Fix MANIFEST.in` commit... 😀
Thanks for the report @sjoerdjob. We'll sort it for the next release. | 2017-11-25T02:33:34 |
|
encode/django-rest-framework | 5,625 | encode__django-rest-framework-5625 | [
"3817"
] | c63e35cb09170e1166896ad31a1bb9a121aaa2f8 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -9,10 +9,10 @@
from setuptools import setup
try:
- from pypandoc import convert
+ from pypandoc import convert_file
def read_md(f):
- return convert(f, 'rst')
+ return convert_file(f, 'rst')
except ImportError:
print("warning: pypandoc module not found, could not convert Markdown to RST")
| Use Pandoc to publish RestructuredText to PyPI
A little call out to Pandoc during the `publish` setup.py command would mean this:

would look more like:

If this is something wanted, I'm more than happy to make the pull request.
| I'd be ok if we just had moved our `README.md` to reStructuredText instead. That file only changes when a new version is released.
@pydanny sounds good. I'd probably rather see/review that first, before considering using .rst for the README
As reported in #4012, the pandoc reST output is not rendering properly on PyPI. PyPI doesn't really report these errors easily so here is some output that can hopefully help resolve the problem. On other projects, when I've resolved any errors from rst2html, the page starts to render properly on PyPI.
``` bash
python setup.py --long-description | rst2html.py > /dev/null
<stdin>:110: (WARNING/2) Cannot analyze code. Pygments package not found.
<stdin>:145: (WARNING/2) Cannot analyze code. Pygments package not found.
```
Installing Pygments made the errors go away.
@mblayman We already have a fix for that, see the related issues list.
I ran the above command from the stable branch that includes the merged PR referenced in the issues list. I did some triage and thought this might be new information.
My apologies if you were already aware of this.
| 2017-11-25T03:03:56 |
|
encode/django-rest-framework | 5,633 | encode__django-rest-framework-5633 | [
"5632"
] | 5f42cb70270d698df57df679726964e7fad11f45 | 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
@@ -172,7 +172,8 @@ 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`
"""
-
+ if manual_fields is None:
+ manual_fields = []
self._manual_fields = manual_fields
def get_link(self, path, method, base_url):
@@ -181,11 +182,8 @@ def get_link(self, path, method, base_url):
fields += self.get_pagination_fields(path, method)
fields += self.get_filter_fields(path, method)
- if self._manual_fields is not None:
- by_name = {f.name: f for f in fields}
- for f in self._manual_fields:
- by_name[f.name] = f
- fields = list(by_name.values())
+ manual_fields = self.get_manual_fields(path, method)
+ fields = self.update_fields(fields, manual_fields)
if fields and any([field.location in ('form', 'body') for field in fields]):
encoding = self.get_encoding(path, method)
@@ -379,6 +377,31 @@ def get_filter_fields(self, path, method):
fields += filter_backend().get_schema_fields(self.view)
return fields
+ def get_manual_fields(self, path, method):
+ return self._manual_fields
+
+ @staticmethod
+ def update_fields(fields, update_with):
+ """
+ Update list of coreapi.Field instances, overwriting on `Field.name`.
+
+ Utility function to handle replacing coreapi.Field fields
+ from a list by name. Used to handle `manual_fields`.
+
+ Parameters:
+
+ * `fields`: list of `coreapi.Field` instances to update
+ * `update_with: list of `coreapi.Field` instances to add or replace.
+ """
+ if not update_with:
+ return fields
+
+ by_name = OrderedDict((f.name, f) for f in fields)
+ for f in update_with:
+ by_name[f.name] = f
+ fields = list(by_name.values())
+ return fields
+
def get_encoding(self, path, method):
"""
Return the 'encoding' parameter to use for a given endpoint.
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -516,7 +516,7 @@ def test_4605_regression(self):
assert prefix == '/'
-class TestDescriptor(TestCase):
+class TestAutoSchema(TestCase):
def test_apiview_schema_descriptor(self):
view = APIView()
@@ -528,7 +528,43 @@ def test_get_link_requires_instance(self):
with pytest.raises(AssertionError):
descriptor.get_link(None, None, None) # ???: Do the dummy arguments require a tighter assert?
- def test_manual_fields(self):
+ def test_update_fields(self):
+ """
+ That updating fields by-name helper is correct
+
+ Recall: `update_fields(fields, update_with)`
+ """
+ schema = AutoSchema()
+ fields = []
+
+ # Adds a field...
+ fields = schema.update_fields(fields, [
+ coreapi.Field(
+ "my_field",
+ required=True,
+ location="path",
+ schema=coreschema.String()
+ ),
+ ])
+
+ assert len(fields) == 1
+ assert fields[0].name == "my_field"
+
+ # Replaces a field...
+ fields = schema.update_fields(fields, [
+ coreapi.Field(
+ "my_field",
+ required=False,
+ location="path",
+ schema=coreschema.String()
+ ),
+ ])
+
+ assert len(fields) == 1
+ assert fields[0].required is False
+
+ def test_get_manual_fields(self):
+ """That get_manual_fields is applied during get_link"""
class CustomView(APIView):
schema = AutoSchema(manual_fields=[
| Schema Generation: Extract Method for adjusting manual fields
Ref https://github.com/encode/django-rest-framework/pull/5621#issuecomment-346841479
Ref #5630
The logic to add/adjust `manual_fields` is currently inline in `get_link`:
https://github.com/encode/django-rest-framework/blob/c63e35cb09170e1166896ad31a1bb9a121aaa2f8/rest_framework/schemas/inspectors.py#L184-L188
This should be extracted to a separate method so the logic can be re-used when users are overriding `get_link`
| 2017-11-28T08:16:46 |
|
encode/django-rest-framework | 5,646 | encode__django-rest-framework-5646 | [
"5637"
] | b01ec450b2615c85bb121ed3eb5a432dfb7c0c14 | diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -398,6 +398,10 @@ def get_validators(self):
def get_initial(self):
if hasattr(self, 'initial_data'):
+ # initial_data may not be a valid type
+ if not isinstance(self.initial_data, Mapping):
+ return OrderedDict()
+
return OrderedDict([
(field_name, field.get_value(self.initial_data))
for field_name, field in self.fields.items()
| diff --git a/tests/browsable_api/test_form_rendering.py b/tests/browsable_api/test_form_rendering.py
--- a/tests/browsable_api/test_form_rendering.py
+++ b/tests/browsable_api/test_form_rendering.py
@@ -14,6 +14,10 @@ class Meta:
fields = '__all__'
+class StandardPostView(generics.CreateAPIView):
+ serializer_class = BasicSerializer
+
+
class ManyPostView(generics.GenericAPIView):
queryset = BasicModel.objects.all()
serializer_class = BasicSerializer
@@ -24,6 +28,32 @@ def post(self, request, *args, **kwargs):
return Response(serializer.data, status.HTTP_200_OK)
+class TestPostingListData(TestCase):
+ """
+ POSTing a list of data to a regular view should not cause the browsable
+ API to fail during rendering.
+
+ Regression test for https://github.com/encode/django-rest-framework/issues/5637
+ """
+
+ def test_json_response(self):
+ # sanity check for non-browsable API responses
+ view = StandardPostView.as_view()
+ request = factory.post('/', [{}], format='json')
+ response = view(request).render()
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertTrue('non_field_errors' in response.data)
+
+ def test_browsable_api(self):
+ view = StandardPostView.as_view()
+ request = factory.post('/?format=api', [{}], format='json')
+ response = view(request).render()
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertTrue('non_field_errors' in response.data)
+
+
class TestManyPostView(TestCase):
def setUp(self):
"""
diff --git a/tests/test_serializer.py b/tests/test_serializer.py
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -77,14 +77,23 @@ def test_valid_serializer(self):
serializer = self.Serializer(data={'char': 'abc', 'integer': 123})
assert serializer.is_valid()
assert serializer.validated_data == {'char': 'abc', 'integer': 123}
+ assert serializer.data == {'char': 'abc', 'integer': 123}
assert serializer.errors == {}
def test_invalid_serializer(self):
serializer = self.Serializer(data={'char': 'abc'})
assert not serializer.is_valid()
assert serializer.validated_data == {}
+ assert serializer.data == {'char': 'abc'}
assert serializer.errors == {'integer': ['This field is required.']}
+ def test_invalid_datatype(self):
+ serializer = self.Serializer(data=[{'char': 'abc'}])
+ assert not serializer.is_valid()
+ assert serializer.validated_data == {}
+ assert serializer.data == {}
+ assert serializer.errors == {'non_field_errors': ['Invalid data. Expected a dictionary, but got list.']}
+
def test_partial_validation(self):
serializer = self.Serializer(data={'char': 'abc'}, partial=True)
assert serializer.is_valid()
| POST list data breaks all Views / ViewSets
## 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.)
List data makes any view / viewset crash.
I tested versions from 3.6.3 till 3.7.3 (current pypi) and master.
## Steps to reproduce
Just create simple ApiView / Viewset and serializer (does not matter Serializer or ModelSerializer)
```
from rest_framework import generics, serializers
class TestSerializer(serializers.Serializer):
value = serializers.IntegerField()
class TestView(generics.CreateAPIView):
serializer_class = TestSerializer
def get_queryset(self):
return TestModel.objects.all()
```
then post JSON data (any array):
`[{}]`
You get stack trace:
```
Internal Server Error: /api/v1/test/
Traceback (most recent call last):
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 217, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 215, in _get_response
response = response.render()
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/django/template/response.py", line 107, in render
self.content = self.rendered_content
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/renderers.py", line 716, in render
context = self.get_context(data, accepted_media_type, renderer_context)
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/renderers.py", line 689, in get_context
'post_form': self.get_rendered_html_form(data, view, 'POST', request),
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/renderers.py", line 495, in get_rendered_html_form
return self.render_form_for_serializer(existing_serializer)
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/renderers.py", line 521, in render_form_for_serializer
serializer.data,
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/serializers.py", line 533, in data
ret = super(Serializer, self).data
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/serializers.py", line 266, in data
self._data = self.get_initial()
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/serializers.py", line 403, in get_initial
for field_name, field in self.fields.items()
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/serializers.py", line 404, in <listcomp>
if (field.get_value(self.initial_data) is not empty) and
File "/slowhome/ferox/Projects/ubp/myenv/lib/python3.5/site-packages/rest_framework/fields.py", line 433, in get_value
return dictionary.get(self.field_name, empty)
```
## Expected behavior
Validation input data type?
## Actual behavior
500
| If anyone's looking through the issues and wants to contribute... first thing we need to do here is see if someone else can reproduce and confirm the issue.
@FeroxTL This isn't specific enough to be actionable at the moment.
* What's the actual exception? You put the traceback by what's the error?
* `render_form_for_serializer` — So this is for the Browsable API right? What happens for a JSON request?
* Can you put together a test project that demonstrates this? — It clearly does not apply to just any view or viewset: posting your exact body to [an example endpoint](http://restframework.herokuapp.com/snippets/) give me the expected response:
```son
{
"non_field_errors": [
"Invalid data. Expected a dictionary, but got list."
]
}
```
So we need more to be able to reproduce this. (Most likely there's an error elsewhere in your code, but without the exception it's impossible to say...)
I'm going to close this as is. Happy to re-open if we can identify a concrete issue.
@carltongibson As far as I can see this bug exists in render_form_for_serializer that is used only in Browsable API. So when it gets a list instead of dict is fails.
If Browsable API is turned off (for example
```
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
]
...
```
) this would not be affected. By default it is on.
You need to activate Browsable API (if it is off) and try again. I have created repo with simple test, that shows this bug — https://github.com/FeroxTL/rest_test
Just follow readme.md
Thanks @FeroxTL. I'm reopening this, given the reproduction/test. | 2017-12-04T04:52:38 |
encode/django-rest-framework | 5,654 | encode__django-rest-framework-5654 | [
"5644"
] | 01587b9eb17bf68c716e84e616202d6e4ccbaecf | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1684,6 +1684,17 @@ def to_representation(self, value):
}
+class HStoreField(DictField):
+ child = CharField(allow_blank=True, allow_null=True)
+
+ def __init__(self, *args, **kwargs):
+ super(HStoreField, self).__init__(*args, **kwargs)
+ assert isinstance(self.child, CharField), (
+ "The `child` argument must be an instance of `CharField`, "
+ "as the hstore extension stores values as strings."
+ )
+
+
class JSONField(Field):
default_error_messages = {
'invalid': _('Value must be valid JSON.')
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -54,9 +54,9 @@
from rest_framework.fields import ( # NOQA # isort:skip
BooleanField, CharField, ChoiceField, DateField, DateTimeField, DecimalField,
DictField, DurationField, EmailField, Field, FileField, FilePathField, FloatField,
- HiddenField, IPAddressField, ImageField, IntegerField, JSONField, ListField,
- ModelField, MultipleChoiceField, NullBooleanField, ReadOnlyField, RegexField,
- SerializerMethodField, SlugField, TimeField, URLField, UUIDField,
+ HiddenField, HStoreField, IPAddressField, ImageField, IntegerField, JSONField,
+ ListField, ModelField, MultipleChoiceField, NullBooleanField, ReadOnlyField,
+ RegexField, SerializerMethodField, SlugField, TimeField, URLField, UUIDField,
)
from rest_framework.relations import ( # NOQA # isort:skip
HyperlinkedIdentityField, HyperlinkedRelatedField, ManyRelatedField,
@@ -1541,10 +1541,7 @@ def get_unique_for_date_validators(self):
ModelSerializer.serializer_field_mapping[models.IPAddressField] = IPAddressField
if postgres_fields:
- class CharMappingField(DictField):
- child = CharField(allow_blank=True)
-
- ModelSerializer.serializer_field_mapping[postgres_fields.HStoreField] = CharMappingField
+ ModelSerializer.serializer_field_mapping[postgres_fields.HStoreField] = HStoreField
ModelSerializer.serializer_field_mapping[postgres_fields.ArrayField] = ListField
ModelSerializer.serializer_field_mapping[postgres_fields.JSONField] = JSONField
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -1897,6 +1897,49 @@ class TestUnvalidatedDictField(FieldValues):
field = serializers.DictField()
+class TestHStoreField(FieldValues):
+ """
+ Values for `ListField` with CharField as child.
+ """
+ valid_inputs = [
+ ({'a': 1, 'b': '2', 3: 3}, {'a': '1', 'b': '2', '3': '3'}),
+ ({'a': 1, 'b': None}, {'a': '1', 'b': None}),
+ ]
+ invalid_inputs = [
+ ('not a dict', ['Expected a dictionary of items but got type "str".']),
+ ]
+ outputs = [
+ ({'a': 1, 'b': '2', 3: 3}, {'a': '1', 'b': '2', '3': '3'}),
+ ]
+ field = serializers.HStoreField()
+
+ def test_child_is_charfield(self):
+ with pytest.raises(AssertionError) as exc_info:
+ serializers.HStoreField(child=serializers.IntegerField())
+
+ assert str(exc_info.value) == (
+ "The `child` argument must be an instance of `CharField`, "
+ "as the hstore extension stores values as strings."
+ )
+
+ def test_no_source_on_child(self):
+ with pytest.raises(AssertionError) as exc_info:
+ serializers.HStoreField(child=serializers.CharField(source='other'))
+
+ assert str(exc_info.value) == (
+ "The `source` argument is not meaningful when applied to a `child=` field. "
+ "Remove `source=` from the field declaration."
+ )
+
+ def test_allow_null(self):
+ """
+ If `allow_null=True` then `None` is a valid input.
+ """
+ field = serializers.HStoreField(allow_null=True)
+ output = field.run_validation(None)
+ assert output is None
+
+
class TestJSONField(FieldValues):
"""
Values for `JSONField`.
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
@@ -21,7 +21,7 @@
from django.utils import six
from rest_framework import serializers
-from rest_framework.compat import unicode_repr
+from rest_framework.compat import postgres_fields, unicode_repr
def dedent(blocktext):
@@ -379,6 +379,54 @@ class Meta:
'{0}'.format(s.errors))
[email protected](postgres_fields, 'postgres is required')
+class TestPosgresFieldsMapping(TestCase):
+ def test_hstore_field(self):
+ class HStoreFieldModel(models.Model):
+ hstore_field = postgres_fields.HStoreField()
+
+ class TestSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = HStoreFieldModel
+ fields = ['hstore_field']
+
+ expected = dedent("""
+ TestSerializer():
+ hstore_field = HStoreField()
+ """)
+ self.assertEqual(unicode_repr(TestSerializer()), expected)
+
+ def test_array_field(self):
+ class ArrayFieldModel(models.Model):
+ array_field = postgres_fields.ArrayField(base_field=models.CharField())
+
+ class TestSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = ArrayFieldModel
+ fields = ['array_field']
+
+ expected = dedent("""
+ TestSerializer():
+ array_field = ListField(child=CharField(label='Array field', validators=[<django.core.validators.MaxLengthValidator object>]))
+ """)
+ self.assertEqual(unicode_repr(TestSerializer()), expected)
+
+ def test_json_field(self):
+ class JSONFieldModel(models.Model):
+ json_field = postgres_fields.JSONField()
+
+ class TestSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = JSONFieldModel
+ fields = ['json_field']
+
+ expected = dedent("""
+ TestSerializer():
+ json_field = JSONField(style={'base_template': 'textarea.html'})
+ """)
+ self.assertEqual(unicode_repr(TestSerializer()), expected)
+
+
# Tests for relational field mappings.
# ------------------------------------
| HStore: This field may not be null.
## Steps to reproduce
```python
class Product(models.Model):
title = CharField(max_length=512)
attributes = HStoreField(null=True, blank=True)
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('title', 'attributes')
```
Some try:
```python
p = Product(title="foobar", attributes={'first': 'value', 'second': None})
p.save() # Save success. No error here!
# Now, Let's try with Serializer
data = {"title": "foobar", "attributes": {"first": "value", "second": None}}
q = ProductSerializer(data=data)
q.is_valid()
#> False
q.errors
#> {'attributes': ['This field may not be null.']}
```
## Expected behavior
`q` is valid
## Actual behavior
As you can see, `q` is invalid with an error `{'attributes': ['This field may not be null.']}`.
When I remove `"second": None` from `attributes`. `q` is valid
| This issue seems valid. Django 1.11 added the ability to store nulls as values in addition to strings.
https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#hstorefield
Ideally the error message would be more specific too. (It would be nice if `second` were mentioned, so I knew where the problem lay, assuming the `null=False` case.)
@rpkilby I see. But It would be nice if Rest framework also support this too. | 2017-12-05T06:00:47 |
encode/django-rest-framework | 5,655 | encode__django-rest-framework-5655 | [
"3274"
] | 6602171184d8e5c7013407b57bff5745a70733ac | diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1626,7 +1626,7 @@ def to_internal_value(self, data):
self.fail('not_a_list', input_type=type(data).__name__)
if not self.allow_empty and len(data) == 0:
self.fail('empty')
- return [self.child.run_validation(item) for item in data]
+ return self.run_child_validation(data)
def to_representation(self, data):
"""
@@ -1634,6 +1634,20 @@ def to_representation(self, data):
"""
return [self.child.to_representation(item) if item is not None else None for item in data]
+ def run_child_validation(self, data):
+ result = []
+ errors = OrderedDict()
+
+ for idx, item in enumerate(data):
+ try:
+ result.append(self.child.run_validation(item))
+ except ValidationError as e:
+ errors[idx] = e.detail
+
+ if not errors:
+ return result
+ raise ValidationError(errors)
+
class DictField(Field):
child = _UnvalidatedField()
@@ -1669,10 +1683,7 @@ def to_internal_value(self, data):
data = html.parse_html_dict(data)
if not isinstance(data, dict):
self.fail('not_a_dict', input_type=type(data).__name__)
- return {
- six.text_type(key): self.child.run_validation(value)
- for key, value in data.items()
- }
+ return self.run_child_validation(data)
def to_representation(self, value):
"""
@@ -1683,6 +1694,22 @@ def to_representation(self, value):
for key, val in value.items()
}
+ def run_child_validation(self, data):
+ result = {}
+ errors = OrderedDict()
+
+ for key, value in data.items():
+ key = six.text_type(key)
+
+ try:
+ result[key] = self.child.run_validation(value)
+ except ValidationError as e:
+ errors[key] = e.detail
+
+ if not errors:
+ return result
+ raise ValidationError(errors)
+
class JSONField(Field):
default_error_messages = {
| diff --git a/tests/test_fields.py b/tests/test_fields.py
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -1767,7 +1767,7 @@ class TestListField(FieldValues):
]
invalid_inputs = [
('not a list', ['Expected a list of items but got type "str".']),
- ([1, 2, 'error'], ['A valid integer is required.']),
+ ([1, 2, 'error', 'error'], {2: ['A valid integer is required.'], 3: ['A valid integer is required.']}),
({'one': 'two'}, ['Expected a list of items but got type "dict".'])
]
outputs = [
@@ -1794,6 +1794,25 @@ def test_collection_types_are_invalid_input(self):
assert exc_info.value.detail == ['Expected a list of items but got type "dict".']
+class TestNestedListField(FieldValues):
+ """
+ Values for nested `ListField` with IntegerField as child.
+ """
+ valid_inputs = [
+ ([[1, 2], [3]], [[1, 2], [3]]),
+ ([[]], [[]])
+ ]
+ invalid_inputs = [
+ (['not a list'], {0: ['Expected a list of items but got type "str".']}),
+ ([[1, 2, 'error'], ['error']], {0: {2: ['A valid integer is required.']}, 1: {0: ['A valid integer is required.']}}),
+ ([{'one': 'two'}], {0: ['Expected a list of items but got type "dict".']})
+ ]
+ outputs = [
+ ([[1, 2], [3]], [[1, 2], [3]]),
+ ]
+ field = serializers.ListField(child=serializers.ListField(child=serializers.IntegerField()))
+
+
class TestEmptyListField(FieldValues):
"""
Values for `ListField` with allow_empty=False flag.
@@ -1834,13 +1853,13 @@ class TestUnvalidatedListField(FieldValues):
class TestDictField(FieldValues):
"""
- Values for `ListField` with CharField as child.
+ Values for `DictField` with CharField as child.
"""
valid_inputs = [
({'a': 1, 'b': '2', 3: 3}, {'a': '1', 'b': '2', '3': '3'}),
]
invalid_inputs = [
- ({'a': 1, 'b': None}, ['This field may not be null.']),
+ ({'a': 1, 'b': None, 'c': None}, {'b': ['This field may not be null.'], 'c': ['This field may not be null.']}),
('not a dict', ['Expected a dictionary of items but got type "str".']),
]
outputs = [
@@ -1866,9 +1885,26 @@ def test_allow_null(self):
assert output is None
+class TestNestedDictField(FieldValues):
+ """
+ Values for nested `DictField` with CharField as child.
+ """
+ valid_inputs = [
+ ({0: {'a': 1, 'b': '2'}, 1: {3: 3}}, {'0': {'a': '1', 'b': '2'}, '1': {'3': '3'}}),
+ ]
+ invalid_inputs = [
+ ({0: {'a': 1, 'b': None}, 1: {'c': None}}, {'0': {'b': ['This field may not be null.']}, '1': {'c': ['This field may not be null.']}}),
+ ({0: 'not a dict'}, {'0': ['Expected a dictionary of items but got type "str".']}),
+ ]
+ outputs = [
+ ({0: {'a': 1, 'b': '2'}, 1: {3: 3}}, {'0': {'a': '1', 'b': '2'}, '1': {'3': '3'}}),
+ ]
+ field = serializers.DictField(child=serializers.DictField(child=serializers.CharField()))
+
+
class TestDictFieldWithNullChild(FieldValues):
"""
- Values for `ListField` with allow_null CharField as child.
+ Values for `DictField` with allow_null CharField as child.
"""
valid_inputs = [
({'a': None, 'b': '2', 3: 3}, {'a': None, 'b': '2', '3': '3'}),
@@ -1883,7 +1919,7 @@ class TestDictFieldWithNullChild(FieldValues):
class TestUnvalidatedDictField(FieldValues):
"""
- Values for `ListField` with no `child` argument.
+ Values for `DictField` with no `child` argument.
"""
valid_inputs = [
({'a': 1, 'b': [4, 5, 6], 1: 123}, {'a': 1, 'b': [4, 5, 6], '1': 123}),
| Nested ListField serializer errors should include object reference
When validation errors happen in nested ListField serializers -- an OrderedDict is returned for the ListField containing the nested errors. However, it doesn't indicate which object in the list caused the error.
For example, my nested serializer has a URLField, if I pass in a list of 10 objects -- the error doesn't indicate which of the 10 objects contains the error.
``` python
class ChildSerializer(serializers.Serializer):
url = serializers.URLField()
uuid = serializers.UUIDField()
other_fields = serializers.CharField() # many more...
class MySerializer(serializers.ModelSerializer):
# my_nested_list_field is a JSONfield on the Django model
my_nested_list_field = serializer.ListField(child=ChildSerializer())
data = {#other fields...,
'my_nested_listfield': [
{"url": "some invalid url", "other_fields": "MANY"},
{"url": "http://www.google.com/", "other_fields": "MANY"},
#9 (n) more dicts...
]
}
x = MySerializer(data=data)
x.is_valid()
x.errors
{'my_nested_listfield': OrderedDict([('url', [u'Enter a valid URL.'])])}
# did this error occur in dict #1, #5, #10???? Start trawling through the list looking for the bad URL...
```
Nested errors should probably contain some metadata to indicate which item(s) failed validation so that useful errors can be displayed to the client.
Something like:
``` python
{'my_nested_listfield': OrderedDict([('url', [u'Enter a valid URL.'] "_meta_ref": "OBJECT_123")])}
# Oh, I see, the error occured on OBJECT_123 -- this will be quick and easy to debug
```
Where `_meta_ref` is generated by an overrideable method on the child serializer. It could default to the object `url` -- but in this case I would use an internal id that is meaningful to my application, like the `uuid`
| Get the general idea of this, but not clear what a nice way to do this would be.
I'm not super keen on `_meta_ref` but don't have any great alternative.
| 2017-12-05T06:40:30 |
encode/django-rest-framework | 5,668 | encode__django-rest-framework-5668 | [
"2466"
] | 1692feb535472cb78c49328613a14aef48f77787 | diff --git a/rest_framework/settings.py b/rest_framework/settings.py
--- a/rest_framework/settings.py
+++ b/rest_framework/settings.py
@@ -200,6 +200,7 @@ def __init__(self, user_settings=None, defaults=None, import_strings=None):
self._user_settings = self.__check_user_settings(user_settings)
self.defaults = defaults or DEFAULTS
self.import_strings = import_strings or IMPORT_STRINGS
+ self._cached_attrs = set()
@property
def user_settings(self):
@@ -223,6 +224,7 @@ def __getattr__(self, attr):
val = perform_import(val, attr)
# Cache the result
+ self._cached_attrs.add(attr)
setattr(self, attr, val)
return val
@@ -233,15 +235,21 @@ def __check_user_settings(self, user_settings):
raise RuntimeError("The '%s' setting has been removed. Please refer to '%s' for available settings." % (setting, SETTINGS_DOC))
return user_settings
+ def reload(self):
+ for attr in self._cached_attrs:
+ delattr(self, attr)
+ self._cached_attrs.clear()
+ if hasattr(self, '_user_settings'):
+ delattr(self, '_user_settings')
+
api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)
def reload_api_settings(*args, **kwargs):
- global api_settings
- setting, value = kwargs['setting'], kwargs['value']
+ setting = kwargs['setting']
if setting == 'REST_FRAMEWORK':
- api_settings = APISettings(value, DEFAULTS, IMPORT_STRINGS)
+ api_settings.reload()
setting_changed.connect(reload_api_settings)
| diff --git a/tests/test_settings.py b/tests/test_settings.py
--- a/tests/test_settings.py
+++ b/tests/test_settings.py
@@ -1,8 +1,8 @@
from __future__ import unicode_literals
-from django.test import TestCase
+from django.test import TestCase, override_settings
-from rest_framework.settings import APISettings
+from rest_framework.settings import APISettings, api_settings
class TestSettings(TestCase):
@@ -28,6 +28,23 @@ def test_warning_raised_on_removed_setting(self):
'MAX_PAGINATE_BY': 100
})
+ def test_compatibility_with_override_settings(self):
+ """
+ Ref #5658 & #2466: Documented usage of api_settings
+ is bound at import time:
+
+ from rest_framework.settings import api_settings
+
+ setting_changed signal hook must ensure bound instance
+ is refreshed.
+ """
+ assert api_settings.PAGE_SIZE is None, "Checking a known default should be None"
+
+ with override_settings(REST_FRAMEWORK={'PAGE_SIZE': 10}):
+ assert api_settings.PAGE_SIZE == 10, "Setting should have been updated"
+
+ assert api_settings.PAGE_SIZE is None, "Setting should have been restored"
+
class TestSettingTypes(TestCase):
def test_settings_consistently_coerced_to_list(self):
| Settings should be updated when overridden in Django tests
DRF has its own settings object at `rest_framework.settings.api_settings`. It appears that these are generated once and not updated when `override_settings` is used in Django testing.
## Failing test
With this in a settings file:
```
REST_FRAMEWORK = {
'PAGINATE_BY': 10,
}
```
This will fail:
```
from django.test.utils import override_settings
from rest_framework.settings import api_settings
from rest_framework.test import APITestCase
class TestSettings(TestCase):
def test_settings_normal(self):
self.assertEqual(settings.REST_FRAMEWORK['PAGINATE_BY'], 10)
self.assertEqual(api_settings.PAGINATE_BY, 10)
def test_settings_overridden(self):
with override_settings(REST_FRAMEWORK={'PAGINATE_BY': 999}):
self.assertEqual(settings.REST_FRAMEWORK['PAGINATE_BY'], 999)
self.assertEqual(api_settings.PAGINATE_BY, 999)
```
`test_settings_overridden` FAILS because `PAGINATE_BY` in `api_settings` is still 10 during override, when it should have been overridden to 999.
This is unexpected behaviour - Django developers familiar with the Django settings and the settings object will expect to be able to override at testing time as per the [Django docs](https://docs.djangoproject.com/en/1.7/topics/settings/).
## Simple solutions?
There are probably some elegant solutions to wire in the build of `api_settings` to listen for updates made by the settings override functions in Django tests... however, what about using what's in DRF already?
There is a `temporary_setting` function in `tests.utils`: https://github.com/tomchristie/django-rest-framework/blob/master/tests/utils.py#L9 , which looks like it can do the job. If this could be included in the DRF package and documented then it could be a "good enough" solution maybe.
| > which looks like it can do the job
Looking at it I'd say we have that in the tests because it isn't really adequate to go into the core package.
I guess I'd rather see us do something that works with `override_settings`.
I guess we probably want to look at hooking into the `setting_changed` signal. https://docs.djangoproject.com/en/1.4/ref/signals/#django.test.signals.setting_changed
@jamescooke Bunch of thoughts on #2473. Appreciate any feedback you might have. Unclear how to proceed from here.
This got me too, commenting on #2473.
Okay, merged #2473, which resolves the `api_settings` object being updated. Now we need to refactor any places where we have class attributes accessing API settings. In the meantime a note in the testing docs on the (sometime) need to `reload_module` on test setup, test teardown may be worthwhile.
``` python
$ ack "^ [a-z_]* = api_settings[.]" ./rest_framework/
rest_framework/fields.py
734: coerce_to_string = api_settings.COERCE_DECIMAL_TO_STRING
816: format = api_settings.DATETIME_FORMAT
817: input_formats = api_settings.DATETIME_INPUT_FORMATS
881: format = api_settings.DATE_FORMAT
882: input_formats = api_settings.DATE_INPUT_FORMATS
938: format = api_settings.TIME_FORMAT
939: input_formats = api_settings.TIME_INPUT_FORMATS
1073: use_url = api_settings.UPLOADED_FILES_USE_URL
rest_framework/filters.py
75: search_param = api_settings.SEARCH_PARAM
114: ordering_param = api_settings.ORDERING_PARAM
rest_framework/generics.py
59: paginate_by = api_settings.PAGINATE_BY
60: paginate_by_param = api_settings.PAGINATE_BY_PARAM
61: max_paginate_by = api_settings.MAX_PAGINATE_BY
62: pagination_serializer_class = api_settings.DEFAULT_PAGINATION_SERIALIZER_CLASS
66: filter_backends = api_settings.DEFAULT_FILTER_BACKENDS
rest_framework/renderers.py
61: compact = api_settings.COMPACT_JSON
rest_framework/test.py
24: renderer_classes_list = api_settings.TEST_REQUEST_RENDERER_CLASSES
25: default_format = api_settings.TEST_REQUEST_DEFAULT_FORMAT
rest_framework/urlpatterns.py
52: suffix_kwarg = api_settings.FORMAT_SUFFIX_KWARG
rest_framework/utils/breadcrumbs.py
14: view_name_func = api_settings.VIEW_NAME_FUNCTION
rest_framework/views.py
89: renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
90: parser_classes = api_settings.DEFAULT_PARSER_CLASSES
91: authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
92: throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
93: permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
94: content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS
95: metadata_class = api_settings.DEFAULT_METADATA_CLASS
```
See also #4324.
Unless I'm missing something, as far as I can see the changes made in response to this issue so far do not address the original issue of `override_settings` not being respected.
The current [`reload_api_settings()`](https://github.com/encode/django-rest-framework/blob/c7fb60bcd427ae3ceab0ff176c4840b9511cbfdb/rest_framework/settings.py#L240) signal handler sets the module level name `api_settings` in the `settings` module to a new `APISettings` instance, which is fine.
However, wherever `api_settings` is actually used (even in the code from #3363) the value is assigned to a local name in the importing module at import time. For example in [fields.py](https://github.com/encode/django-rest-framework/blob/f9e53091c1defb0971f941a529b5c813060952b7/rest_framework/fields.py#L31):
```python
from rest_framework.settings import api_settings
class DateField(Field):
def to_representation(self, value):
output_format = getattr(self, 'format', api_settings.DATE_FORMAT)
```
The name `api_settings` in `fields.py` will not be changed by `reload_api_settings()` and will always point at the `APISettings` instance imported at the time `fields.py` was imported.
My suggestion to resolve this, while maintaining the current settings attribute caching is to add a `reload()` method to `APISettings`:
```python
class APISettings(object):
def __init__(self, ...):
...
self._cached_attrs = set()
def __getattr__(self, attr):
...
self._cached_attrs.add(attr)
return val
def reload(self):
for attr in self._cached_attrs:
delattr(self, attr)
self._cached_attrs.clear()
if hasattr(self, '_user_settings'):
delattr(self, '_user_settings')
```
Then change `reload_api_settings()` to:
```python
def reload_api_settings(*args, **kwargs):
if kwargs['setting'] == 'REST_FRAMEWORK':
dynamic_settings.reload()
```
I just ran into this. It's behaving exactly as [@daggaz describes](https://github.com/encode/django-rest-framework/issues/2466#issuecomment-344285118).
| 2017-12-14T09:08:55 |
encode/django-rest-framework | 5,689 | encode__django-rest-framework-5689 | [
"5675",
"5675"
] | ea0b3b32ad49d9ac34af8caf49c81b9d8f231b83 | diff --git a/rest_framework/compat.py b/rest_framework/compat.py
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -32,7 +32,7 @@
def get_regex_pattern(urlpattern):
if hasattr(urlpattern, 'pattern'):
# Django 2.0
- return urlpattern.pattern.regex.pattern
+ return str(urlpattern.pattern)
else:
# Django < 2.0
return urlpattern.regex.pattern
@@ -255,6 +255,14 @@ def md_filter_add_syntax_highlight(md):
except ImportError:
InvalidTimeError = Exception
+# Django 1.x url routing syntax. Remove when dropping Django 1.11 support.
+try:
+ from django.urls import include, path, re_path # noqa
+except ImportError:
+ from django.conf.urls import include, url # noqa
+ path = None
+ re_path = url
+
# `separators` argument to `json.dumps()` differs between 2.x and 3.x
# See: http://bugs.python.org/issue22767
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
@@ -3,6 +3,7 @@
See schemas.__init__.py for package overview.
"""
+import re
import warnings
from collections import Counter, OrderedDict
from importlib import import_module
@@ -135,6 +136,11 @@ def endpoint_ordering(endpoint):
return (path, method_priority)
+_PATH_PARAMETER_COMPONENT_RE = re.compile(
+ r'<(?:(?P<converter>[^>:]+):)?(?P<parameter>\w+)>'
+)
+
+
class EndpointEnumerator(object):
"""
A class to determine the available API endpoints that a project exposes.
@@ -189,7 +195,9 @@ def get_path_from_regex(self, path_regex):
Given a URL conf regex, return a URI template string.
"""
path = simplify_regex(path_regex)
- path = path.replace('<', '{').replace('>', '}')
+
+ # Strip Django 2.0 convertors as they are incompatible with uritemplate format
+ path = re.sub(_PATH_PARAMETER_COMPONENT_RE, r'{\g<parameter>}', path)
return path
def should_include_endpoint(self, path, callback):
| diff --git a/tests/test_schemas.py b/tests/test_schemas.py
--- a/tests/test_schemas.py
+++ b/tests/test_schemas.py
@@ -9,7 +9,7 @@
from rest_framework import (
filters, generics, pagination, permissions, serializers
)
-from rest_framework.compat import coreapi, coreschema, get_regex_pattern
+from rest_framework.compat import coreapi, coreschema, get_regex_pattern, path
from rest_framework.decorators import (
api_view, detail_route, list_route, schema
)
@@ -361,6 +361,59 @@ def test_schema_for_regular_views(self):
assert schema == expected
[email protected](coreapi, 'coreapi is not installed')
[email protected](path, 'needs Django 2')
+class TestSchemaGeneratorDjango2(TestCase):
+ def setUp(self):
+ self.patterns = [
+ path('example/', ExampleListView.as_view()),
+ path('example/<int:pk>/', ExampleDetailView.as_view()),
+ path('example/<int:pk>/sub/', ExampleDetailView.as_view()),
+ ]
+
+ def test_schema_for_regular_views(self):
+ """
+ Ensure that schema generation works for APIView classes.
+ """
+ generator = SchemaGenerator(title='Example API', patterns=self.patterns)
+ schema = generator.get_schema()
+ expected = coreapi.Document(
+ url='',
+ title='Example API',
+ content={
+ 'example': {
+ 'create': coreapi.Link(
+ url='/example/',
+ action='post',
+ fields=[]
+ ),
+ 'list': coreapi.Link(
+ url='/example/',
+ action='get',
+ fields=[]
+ ),
+ 'read': coreapi.Link(
+ url='/example/{id}/',
+ action='get',
+ fields=[
+ coreapi.Field('id', required=True, location='path', schema=coreschema.String())
+ ]
+ ),
+ 'sub': {
+ 'list': coreapi.Link(
+ url='/example/{id}/sub/',
+ action='get',
+ fields=[
+ coreapi.Field('id', required=True, location='path', schema=coreschema.String())
+ ]
+ )
+ }
+ }
+ }
+ )
+ assert schema == expected
+
+
@unittest.skipUnless(coreapi, 'coreapi is not installed')
class TestSchemaGeneratorNotAtRoot(TestCase):
def setUp(self):
| Backslashes added to paths at docs from `include_docs_urls`
## 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.)
- [ ] 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
Using DRF installed from github, Django 2.0.
Included the following at `urls.py`:
urlpatterns = [
...
path('^api/token-auth/', authtoken_views.obtain_auth_token)
path('^docs/', include_docs_urls(title='API Docs', authentication_classes=[], permission_classes=[], public=True)),
...
]
## Expected behavior
Urls in docs should `api/endpoint-name/`
## Actual behavior
Urls are `api\/endpoint\-name/`, when using the "interact" button you get a 404 (request URL is `/api%5C/profiles/`)
<img width="619" alt="captura de tela 2017-12-16 as 23 49 05" src="https://user-images.githubusercontent.com/1397214/34075891-fd2cf026-e2bb-11e7-90d0-61d7dc7c7558.png">
Backslashes added to paths at docs from `include_docs_urls`
## 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.)
- [ ] 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
Using DRF installed from github, Django 2.0.
Included the following at `urls.py`:
urlpatterns = [
...
path('^api/token-auth/', authtoken_views.obtain_auth_token)
path('^docs/', include_docs_urls(title='API Docs', authentication_classes=[], permission_classes=[], public=True)),
...
]
## Expected behavior
Urls in docs should `api/endpoint-name/`
## Actual behavior
Urls are `api\/endpoint\-name/`, when using the "interact" button you get a 404 (request URL is `/api%5C/profiles/`)
<img width="619" alt="captura de tela 2017-12-16 as 23 49 05" src="https://user-images.githubusercontent.com/1397214/34075891-fd2cf026-e2bb-11e7-90d0-61d7dc7c7558.png">
| Downgrading to Django 1.11 fixed the problem. Would `tests/test_renderers.py` be the appropriate file to add a test for this issue?
Hi @scardine.
I need to look into this but I'm not sure it is a renderer issue. See @axnsan12's commit referencing this issue and #5672.
#5609 (although distinct) is in a similar ballpark here.
More specifically, I think this should be addressed by Django in `simplify_regex`, which should, quote,
```python
r"""
Clean up urlpattern regexes into something more readable by humans. For
example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
into "/<sport_slug>/athletes/<athlete_slug>/".
"""
```
[get_path_from_regex](https://github.com/encode/django-rest-framework/blob/d12005cf902e3969b5002593eab83bb63feda840/rest_framework/schemas/generators.py#L191) in drf makes use of that function.
I filed a bug in their tracker - https://code.djangoproject.com/ticket/28936
Good follow-up @axnsan12. Thanks.
Thanks, if it is not fixed by next week I will try to submit a patch for `simplify_regex` on my holiday's recess.
Note: Discussion on #5686 has details worth viewing.
I think one should do `str(pattern)` before passing it to `simplify_regex`. In fact, you don't need to pass a `RoutePattern` into `simplify_regex` at all, as it's not a regex (but you may for code simplicity reasons).
The _bigger_ problem here seems not the escaping (can be dealt with calling `str(pattern)`), but that the result may contain type coercion tags.
Before in Django 1.x, the output of `simplify_regex` would always look like: `/example/<id>/`.
Whereas now, it can also be: `/example/<int:id>/`. Which may be unexpected for some follow-up code.
@tiltec I +1 your assessment.
Calling `str(pattern)` in Python 2.7 may trigger UnicodeError. BTW, are there any plans to do the same in DRF now that Django 2.0 dropped support for 2.7? Life is easier when you don't have to think about 2.7 compatibility.
Django 1.11 is the last version supporting 2.7 but it is an LTS version and support ends only in April 2020.
Seems only tangentially related, but I wonder if there's a bug in Django 2.0 when using `str(pattern)` together with [translatable URL patterns](https://docs.djangoproject.com/en/2.0/topics/i18n/translation/#translating-url-patterns).
It clearly returns the gettext_lazy function instead of the translated string. Will set up a more comprehensive testcase for it...
(EDIT) Upstream bug filed: https://code.djangoproject.com/ticket/28947
> In Django 1.x, the output of simplify_regex would always look like: `/example/<id>/`.
Whereas now, it can also be: `/example/<int:id>/`. Which may be unexpected for some follow-up code.
I encountered a follow-up bug.
DRF uses [uritemplate](https://uritemplate.readthedocs.io) to parse the URL variables, but unfortunately the colon means something else there. [RFC 6570](https://tools.ietf.org/html/rfc6570#section-2.4.1) says that `id:5` specifies a parameter with max length of 5.
Doesn't really fit `int:id`, where `int` is the _converter_ and `id` the parameter name. Therefore I get `ValueError: invalid literal for int() with base 10: 'id'` from uritemplate.
Maybe it's easiest to strip the converter part out for SchemaGenerator purposes?
I think the converter part could be useful for the typing information it could provide about the path parameter. Perhaps the most complete solution would be to [try and parse it just like django does](https://github.com/django/django/blob/78247b80a8cbf1ebfb7a54624de7dc92e1a1f888/django/urls/resolvers.py#L193)?
EDIT: or strip it and use the already parsed `converters` on the `RoutePattern`
Downgrading to Django 1.11 fixed the problem. Would `tests/test_renderers.py` be the appropriate file to add a test for this issue?
Hi @scardine.
I need to look into this but I'm not sure it is a renderer issue. See @axnsan12's commit referencing this issue and #5672.
#5609 (although distinct) is in a similar ballpark here.
More specifically, I think this should be addressed by Django in `simplify_regex`, which should, quote,
```python
r"""
Clean up urlpattern regexes into something more readable by humans. For
example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
into "/<sport_slug>/athletes/<athlete_slug>/".
"""
```
[get_path_from_regex](https://github.com/encode/django-rest-framework/blob/d12005cf902e3969b5002593eab83bb63feda840/rest_framework/schemas/generators.py#L191) in drf makes use of that function.
I filed a bug in their tracker - https://code.djangoproject.com/ticket/28936
Good follow-up @axnsan12. Thanks.
Thanks, if it is not fixed by next week I will try to submit a patch for `simplify_regex` on my holiday's recess.
Note: Discussion on #5686 has details worth viewing.
I think one should do `str(pattern)` before passing it to `simplify_regex`. In fact, you don't need to pass a `RoutePattern` into `simplify_regex` at all, as it's not a regex (but you may for code simplicity reasons).
The _bigger_ problem here seems not the escaping (can be dealt with calling `str(pattern)`), but that the result may contain type coercion tags.
Before in Django 1.x, the output of `simplify_regex` would always look like: `/example/<id>/`.
Whereas now, it can also be: `/example/<int:id>/`. Which may be unexpected for some follow-up code.
@tiltec I +1 your assessment.
Calling `str(pattern)` in Python 2.7 may trigger UnicodeError. BTW, are there any plans to do the same in DRF now that Django 2.0 dropped support for 2.7? Life is easier when you don't have to think about 2.7 compatibility.
Django 1.11 is the last version supporting 2.7 but it is an LTS version and support ends only in April 2020.
Seems only tangentially related, but I wonder if there's a bug in Django 2.0 when using `str(pattern)` together with [translatable URL patterns](https://docs.djangoproject.com/en/2.0/topics/i18n/translation/#translating-url-patterns).
It clearly returns the gettext_lazy function instead of the translated string. Will set up a more comprehensive testcase for it...
(EDIT) Upstream bug filed: https://code.djangoproject.com/ticket/28947
> In Django 1.x, the output of simplify_regex would always look like: `/example/<id>/`.
Whereas now, it can also be: `/example/<int:id>/`. Which may be unexpected for some follow-up code.
I encountered a follow-up bug.
DRF uses [uritemplate](https://uritemplate.readthedocs.io) to parse the URL variables, but unfortunately the colon means something else there. [RFC 6570](https://tools.ietf.org/html/rfc6570#section-2.4.1) says that `id:5` specifies a parameter with max length of 5.
Doesn't really fit `int:id`, where `int` is the _converter_ and `id` the parameter name. Therefore I get `ValueError: invalid literal for int() with base 10: 'id'` from uritemplate.
Maybe it's easiest to strip the converter part out for SchemaGenerator purposes?
I think the converter part could be useful for the typing information it could provide about the path parameter. Perhaps the most complete solution would be to [try and parse it just like django does](https://github.com/django/django/blob/78247b80a8cbf1ebfb7a54624de7dc92e1a1f888/django/urls/resolvers.py#L193)?
EDIT: or strip it and use the already parsed `converters` on the `RoutePattern` | 2017-12-19T19:52:10 |
encode/django-rest-framework | 5,691 | encode__django-rest-framework-5691 | [
"5672"
] | cf3929d88dc3d8f311acf4a1179160db4511f658 | diff --git a/rest_framework/compat.py b/rest_framework/compat.py
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -29,7 +29,11 @@
)
-def get_regex_pattern(urlpattern):
+def get_original_route(urlpattern):
+ """
+ Get the original route/regex that was typed in by the user into the path(), re_path() or url() directive. This
+ is in contrast with get_regex_pattern below, which for RoutePattern returns the raw regex generated from the path().
+ """
if hasattr(urlpattern, 'pattern'):
# Django 2.0
return str(urlpattern.pattern)
@@ -38,6 +42,29 @@ def get_regex_pattern(urlpattern):
return urlpattern.regex.pattern
+def get_regex_pattern(urlpattern):
+ """
+ Get the raw regex out of the urlpattern's RegexPattern or RoutePattern. This is always a regular expression,
+ unlike get_original_route above.
+ """
+ if hasattr(urlpattern, 'pattern'):
+ # Django 2.0
+ return urlpattern.pattern.regex.pattern
+ else:
+ # Django < 2.0
+ return urlpattern.regex.pattern
+
+
+def is_route_pattern(urlpattern):
+ if hasattr(urlpattern, 'pattern'):
+ # Django 2.0
+ from django.urls.resolvers import RoutePattern
+ return isinstance(urlpattern.pattern, RoutePattern)
+ else:
+ # Django < 2.0
+ return False
+
+
def make_url_resolver(regex, urlpatterns):
try:
# Django 2.0
@@ -257,10 +284,11 @@ def md_filter_add_syntax_highlight(md):
# Django 1.x url routing syntax. Remove when dropping Django 1.11 support.
try:
- from django.urls import include, path, re_path # noqa
+ from django.urls import include, path, re_path, register_converter # noqa
except ImportError:
from django.conf.urls import include, url # noqa
path = None
+ register_converter = None
re_path = url
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
@@ -16,7 +16,7 @@
from rest_framework import exceptions
from rest_framework.compat import (
- URLPattern, URLResolver, coreapi, coreschema, get_regex_pattern
+ URLPattern, URLResolver, coreapi, coreschema, get_original_route
)
from rest_framework.request import clone_request
from rest_framework.settings import api_settings
@@ -170,7 +170,7 @@ def get_api_endpoints(self, patterns=None, prefix=''):
api_endpoints = []
for pattern in patterns:
- path_regex = prefix + get_regex_pattern(pattern)
+ path_regex = prefix + get_original_route(pattern)
if isinstance(pattern, URLPattern):
path = self.get_path_from_regex(path_regex)
callback = pattern.callback
diff --git a/rest_framework/urlpatterns.py b/rest_framework/urlpatterns.py
--- a/rest_framework/urlpatterns.py
+++ b/rest_framework/urlpatterns.py
@@ -2,11 +2,39 @@
from django.conf.urls import include, url
-from rest_framework.compat import URLResolver, get_regex_pattern
+from rest_framework.compat import (
+ URLResolver, get_regex_pattern, is_route_pattern, path, register_converter
+)
from rest_framework.settings import api_settings
-def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
+def _get_format_path_converter(suffix_kwarg, allowed):
+ if allowed:
+ if len(allowed) == 1:
+ allowed_pattern = allowed[0]
+ else:
+ allowed_pattern = '(?:%s)' % '|'.join(allowed)
+ suffix_pattern = r"\.%s/?" % allowed_pattern
+ else:
+ suffix_pattern = r"\.[a-z0-9]+/?"
+
+ class FormatSuffixConverter:
+ regex = suffix_pattern
+
+ def to_python(self, value):
+ return value.strip('./')
+
+ def to_url(self, value):
+ return '.' + value + '/'
+
+ converter_name = 'drf_format_suffix'
+ if allowed:
+ converter_name += '_' + '_'.join(allowed)
+
+ return converter_name, FormatSuffixConverter
+
+
+def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required, suffix_route=None):
ret = []
for urlpattern in urlpatterns:
if isinstance(urlpattern, URLResolver):
@@ -18,8 +46,18 @@ def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
# Add in the included patterns, after applying the suffixes
patterns = apply_suffix_patterns(urlpattern.url_patterns,
suffix_pattern,
- suffix_required)
- ret.append(url(regex, include((patterns, app_name), namespace), kwargs))
+ suffix_required,
+ suffix_route)
+
+ # if the original pattern was a RoutePattern we need to preserve it
+ if is_route_pattern(urlpattern):
+ assert path is not None
+ route = str(urlpattern.pattern)
+ new_pattern = path(route, include((patterns, app_name), namespace), kwargs)
+ else:
+ new_pattern = url(regex, include((patterns, app_name), namespace), kwargs)
+
+ ret.append(new_pattern)
else:
# Regular URL pattern
regex = get_regex_pattern(urlpattern).rstrip('$').rstrip('/') + suffix_pattern
@@ -29,7 +67,17 @@ def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
# Add in both the existing and the new urlpattern
if not suffix_required:
ret.append(urlpattern)
- ret.append(url(regex, view, kwargs, name))
+
+ # if the original pattern was a RoutePattern we need to preserve it
+ if is_route_pattern(urlpattern):
+ assert path is not None
+ assert suffix_route is not None
+ route = str(urlpattern.pattern).rstrip('$').rstrip('/') + suffix_route
+ new_pattern = path(route, view, kwargs, name)
+ else:
+ new_pattern = url(regex, view, kwargs, name)
+
+ ret.append(new_pattern)
return ret
@@ -60,4 +108,12 @@ def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
else:
suffix_pattern = r'\.(?P<%s>[a-z0-9]+)/?$' % suffix_kwarg
- return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required)
+ if path and register_converter:
+ converter_name, suffix_converter = _get_format_path_converter(suffix_kwarg, allowed)
+ register_converter(suffix_converter, converter_name)
+
+ suffix_route = '<%s:%s>' % (converter_name, suffix_kwarg)
+ else:
+ suffix_route = None
+
+ return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required, suffix_route)
| diff --git a/tests/test_urlpatterns.py b/tests/test_urlpatterns.py
--- a/tests/test_urlpatterns.py
+++ b/tests/test_urlpatterns.py
@@ -1,12 +1,13 @@
from __future__ import unicode_literals
+import unittest
from collections import namedtuple
from django.conf.urls import include, url
from django.test import TestCase
from django.urls import Resolver404
-from rest_framework.compat import make_url_resolver
+from rest_framework.compat import make_url_resolver, path, re_path
from rest_framework.test import APIRequestFactory
from rest_framework.urlpatterns import format_suffix_patterns
@@ -23,52 +24,58 @@ class FormatSuffixTests(TestCase):
Tests `format_suffix_patterns` against different URLPatterns to ensure the
URLs still resolve properly, including any captured parameters.
"""
- def _resolve_urlpatterns(self, urlpatterns, test_paths):
+ def _resolve_urlpatterns(self, urlpatterns, test_paths, allowed=None):
factory = APIRequestFactory()
try:
- urlpatterns = format_suffix_patterns(urlpatterns)
+ urlpatterns = format_suffix_patterns(urlpatterns, allowed=allowed)
except Exception:
self.fail("Failed to apply `format_suffix_patterns` on the supplied urlpatterns")
resolver = make_url_resolver(r'^/', urlpatterns)
for test_path in test_paths:
+ try:
+ test_path, expected_resolved = test_path
+ except (TypeError, ValueError):
+ expected_resolved = True
+
request = factory.get(test_path.path)
try:
callback, callback_args, callback_kwargs = resolver.resolve(request.path_info)
+ except Resolver404:
+ callback, callback_args, callback_kwargs = (None, None, None)
+ if expected_resolved:
+ raise
except Exception:
self.fail("Failed to resolve URL: %s" % request.path_info)
+
+ if not expected_resolved:
+ assert callback is None
+ continue
+
assert callback_args == test_path.args
assert callback_kwargs == test_path.kwargs
- def test_trailing_slash(self):
- factory = APIRequestFactory()
- urlpatterns = format_suffix_patterns([
- url(r'^test/$', dummy_view),
- ])
- resolver = make_url_resolver(r'^/', urlpatterns)
-
+ def _test_trailing_slash(self, urlpatterns):
test_paths = [
(URLTestPath('/test.api', (), {'format': 'api'}), True),
(URLTestPath('/test/.api', (), {'format': 'api'}), False),
(URLTestPath('/test.api/', (), {'format': 'api'}), True),
]
+ self._resolve_urlpatterns(urlpatterns, test_paths)
- for test_path, expected_resolved in test_paths:
- request = factory.get(test_path.path)
- try:
- callback, callback_args, callback_kwargs = resolver.resolve(request.path_info)
- except Resolver404:
- callback, callback_args, callback_kwargs = (None, None, None)
- if not expected_resolved:
- assert callback is None
- continue
-
- assert callback_args == test_path.args
- assert callback_kwargs == test_path.kwargs
+ def test_trailing_slash(self):
+ urlpatterns = [
+ url(r'^test/$', dummy_view),
+ ]
+ self._test_trailing_slash(urlpatterns)
- def test_format_suffix(self):
+ @unittest.skipUnless(path, 'needs Django 2')
+ def test_trailing_slash_django2(self):
urlpatterns = [
- url(r'^test$', dummy_view),
+ path('test/', dummy_view),
]
+ self._test_trailing_slash(urlpatterns)
+
+ def _test_format_suffix(self, urlpatterns):
test_paths = [
URLTestPath('/test', (), {}),
URLTestPath('/test.api', (), {'format': 'api'}),
@@ -76,10 +83,36 @@ def test_format_suffix(self):
]
self._resolve_urlpatterns(urlpatterns, test_paths)
- def test_default_args(self):
+ def test_format_suffix(self):
urlpatterns = [
- url(r'^test$', dummy_view, {'foo': 'bar'}),
+ url(r'^test$', dummy_view),
+ ]
+ self._test_format_suffix(urlpatterns)
+
+ @unittest.skipUnless(path, 'needs Django 2')
+ def test_format_suffix_django2(self):
+ urlpatterns = [
+ path('test', dummy_view),
]
+ self._test_format_suffix(urlpatterns)
+
+ @unittest.skipUnless(path, 'needs Django 2')
+ def test_format_suffix_django2_args(self):
+ urlpatterns = [
+ path('convtest/<int:pk>', dummy_view),
+ re_path(r'^retest/(?P<pk>[0-9]+)$', dummy_view),
+ ]
+ test_paths = [
+ URLTestPath('/convtest/42', (), {'pk': 42}),
+ URLTestPath('/convtest/42.api', (), {'pk': 42, 'format': 'api'}),
+ URLTestPath('/convtest/42.asdf', (), {'pk': 42, 'format': 'asdf'}),
+ URLTestPath('/retest/42', (), {'pk': '42'}),
+ URLTestPath('/retest/42.api', (), {'pk': '42', 'format': 'api'}),
+ URLTestPath('/retest/42.asdf', (), {'pk': '42', 'format': 'asdf'}),
+ ]
+ self._resolve_urlpatterns(urlpatterns, test_paths)
+
+ def _test_default_args(self, urlpatterns):
test_paths = [
URLTestPath('/test', (), {'foo': 'bar', }),
URLTestPath('/test.api', (), {'foo': 'bar', 'format': 'api'}),
@@ -87,6 +120,27 @@ def test_default_args(self):
]
self._resolve_urlpatterns(urlpatterns, test_paths)
+ def test_default_args(self):
+ urlpatterns = [
+ url(r'^test$', dummy_view, {'foo': 'bar'}),
+ ]
+ self._test_default_args(urlpatterns)
+
+ @unittest.skipUnless(path, 'needs Django 2')
+ def test_default_args_django2(self):
+ urlpatterns = [
+ path('test', dummy_view, {'foo': 'bar'}),
+ ]
+ self._test_default_args(urlpatterns)
+
+ def _test_included_urls(self, urlpatterns):
+ test_paths = [
+ URLTestPath('/test/path', (), {'foo': 'bar', }),
+ URLTestPath('/test/path.api', (), {'foo': 'bar', 'format': 'api'}),
+ URLTestPath('/test/path.asdf', (), {'foo': 'bar', 'format': 'asdf'}),
+ ]
+ self._resolve_urlpatterns(urlpatterns, test_paths)
+
def test_included_urls(self):
nested_patterns = [
url(r'^path$', dummy_view)
@@ -94,9 +148,79 @@ def test_included_urls(self):
urlpatterns = [
url(r'^test/', include(nested_patterns), {'foo': 'bar'}),
]
+ self._test_included_urls(urlpatterns)
+
+ @unittest.skipUnless(path, 'needs Django 2')
+ def test_included_urls_django2(self):
+ nested_patterns = [
+ path('path', dummy_view)
+ ]
+ urlpatterns = [
+ path('test/', include(nested_patterns), {'foo': 'bar'}),
+ ]
+ self._test_included_urls(urlpatterns)
+
+ @unittest.skipUnless(path, 'needs Django 2')
+ 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)
+
+ @unittest.skipUnless(path, 'needs Django 2')
+ def test_included_urls_django2_mixed_args(self):
+ nested_patterns = [
+ path('path/<int:child>', dummy_view),
+ url('^url/(?P<child>[0-9]+)$', dummy_view)
+ ]
+ urlpatterns = [
+ url('^purl/(?P<parent>[0-9]+)/', include(nested_patterns), {'foo': 'bar'}),
+ path('ppath/<int:parent>/', include(nested_patterns), {'foo': 'bar'}),
+ ]
test_paths = [
- URLTestPath('/test/path', (), {'foo': 'bar', }),
- URLTestPath('/test/path.api', (), {'foo': 'bar', 'format': 'api'}),
- URLTestPath('/test/path.asdf', (), {'foo': 'bar', 'format': 'asdf'}),
+ # 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 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 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'}),
]
self._resolve_urlpatterns(urlpatterns, test_paths)
+
+ def _test_allowed_formats(self, urlpatterns):
+ allowed_formats = ['good', 'ugly']
+ test_paths = [
+ (URLTestPath('/test.good/', (), {'format': 'good'}), True),
+ (URLTestPath('/test.bad', (), {}), False),
+ (URLTestPath('/test.ugly', (), {'format': 'ugly'}), True),
+ ]
+ self._resolve_urlpatterns(urlpatterns, test_paths, allowed=allowed_formats)
+
+ def test_allowed_formats(self):
+ urlpatterns = [
+ url('^test$', dummy_view),
+ ]
+ self._test_allowed_formats(urlpatterns)
+
+ @unittest.skipUnless(path, 'needs Django 2')
+ def test_allowed_formats_django2(self):
+ urlpatterns = [
+ path('test', dummy_view),
+ ]
+ self._test_allowed_formats(urlpatterns)
| format_suffix_pattern not working with path() in django 2.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
## Expected behavior
when using format_suffix_patterns() from the rest_framwork.urlpatterns class, it should format the url pattern for url() from django.conf.urls as well as the newly introduced path() from django.urls
## Actual behavior
getting an error when using path() in urlpatterns[], and then formatting it using the format_suffix_patterns() method
| Next step on that issue would be to write a failing test case.
I am having the same issue with the following urls.py file:
```
from django.urls import path, re_path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
urlpatterns = [
path('snippets/', views.snippet_list),
re_path('snippets/(?P<pk>[0-9]+)/', views.snippet_detail)
]
urlpatterns = format_suffix_patterns(urlpatterns)
``` | 2017-12-20T09:34:07 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.