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
2,153
encode__django-rest-framework-2153
[ "2151" ]
276a2a52eedb97a15d85e059424870bf2d21854d
diff --git a/rest_framework/authtoken/views.py b/rest_framework/authtoken/views.py --- a/rest_framework/authtoken/views.py +++ b/rest_framework/authtoken/views.py @@ -1,5 +1,4 @@ from rest_framework.views import APIView -from rest_framework import status from rest_framework import parsers from rest_framework import renderers from rest_framework.response import Response @@ -12,16 +11,13 @@ class ObtainAuthToken(APIView): permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) - serializer_class = AuthTokenSerializer - model = Token def post(self, request): - serializer = self.serializer_class(data=request.data) - if serializer.is_valid(): - user = serializer.validated_data['user'] - token, created = Token.objects.get_or_create(user=user) - return Response({'token': token.key}) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + serializer = AuthTokenSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + user = serializer.validated_data['user'] + token, created = Token.objects.get_or_create(user=user) + return Response({'token': token.key}) obtain_auth_token = ObtainAuthToken.as_view()
Makes it easy to change AuthToken model class when overriding built-in O... Makes it easy to change AuthToken model class when overriding built-in ObtainAuthToken view. ObtainAuthToken view has a `model` attribute, but it uses a Token class whatever in `post()` method.
I thought `.model` was deprecated in #1784. Why does Token view even have it? Looks like some tweaks needed if this view (eg let's also use .is_valid(raise_exception=True) You mean something simple like this? ``` class ObtainAuthToken(APIView): throttle_classes = () permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) serializer_class = AuthTokenSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) obtain_auth_token = ObtainAuthToken.as_view() ``` I don't think there's much we can do with the hardcoded `Token` model, as the serializer/view don't know how to create an instance. I read in #399 that you didn't want to use `CreateAPIView`. Still the same thoughts as of today? > You mean something simple like this? Exactly, yes. I would drop the `serializer_class` attribute and instead just use `AuthTokenSerializer` in the `post` method directly. Anyone wanting to customize the view behavior should just do so explicitly. > you didn't want to use CreateAPIView. Probably simplest as it is, yup.
2014-11-28T11:28:12
encode/django-rest-framework
2,195
encode__django-rest-framework-2195
[ "2169" ]
5f2f54b7fb52e35e3f47a677c2c5b9981c7d1f81
diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -102,6 +102,11 @@ def render(self, data, accepted_media_type=None, renderer_context=None): # and may (or may not) be unicode. # On python 3.x json.dumps() returns unicode strings. if isinstance(ret, six.text_type): + # We always fully escape \u2028 and \u2029 to ensure we output JSON + # that is a strict javascript subset. If bytes were returned + # by json.dumps() then we don't have these characters in any case. + # See: http://timelessrepo.com/json-isnt-a-javascript-subset + ret = ret.replace('\u2028', '\\u2028').replace('\u2029', '\\u2029') return bytes(ret.encode('utf-8')) return ret
diff --git a/tests/test_renderers.py b/tests/test_renderers.py --- a/tests/test_renderers.py +++ b/tests/test_renderers.py @@ -384,6 +384,15 @@ def test_proper_encoding(self): content = renderer.render(obj, 'application/json') self.assertEqual(content, '{"countries":["United Kingdom","France","España"]}'.encode('utf-8')) + def test_u2028_u2029(self): + # The \u2028 and \u2029 characters should be escaped, + # even when the non-escaping unicode representation is used. + # Regression test for #2169 + obj = {'should_escape': '\u2028\u2029'} + renderer = JSONRenderer() + content = renderer.render(obj, 'application/json') + self.assertEqual(content, '{"should_escape":"\\u2028\\u2029"}'.encode('utf-8')) + class AsciiJSONRendererTests(TestCase): """
JSONP renderer fails to escape U+2028 and U+2029 When Unicode is enabled for JSON output, the JSONP renderer fails to escape U+2028 and U+2029 which are [valid in JSON but invalid in JavaScript](http://timelessrepo.com/json-isnt-a-javascript-subset). Try adding this simple model to the example app from the README: ``` from django.db import models class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() ``` Create an object like this: ``` from example.models import Post Post.objects.create(title=u'Test\u2028', content=u'example') ``` Then fire up a dev server and make an HTML page with a JSONP request like this: ``` <script type="text/javascript" src="http://127.0.0.1:8000/posts/?format=jsonp"></script> ``` Open the page in your browser and observe the error console. In Chromium, I get: > Uncaught SyntaxError: Unexpected token ILLEGAL
Which version of python is this btw? Should this additionally be added as a Python bug. Appears to be resolved in simplejson - https://github.com/simplejson/simplejson/blob/master/simplejson/encoder.py#L36 But not in CPython - https://hg.python.org/cpython/file/e1afae23dfcd/Lib/json/encoder.py#l26 And I don't see it listed as an issue?... http://bugs.python.org/issue?%40columns=id%2Cactivity%2Ctitle%2Ccreator%2Cassignee%2Cstatus%2Ctype&%40sort=-activity&%40filter=status&%40action=searchid&ignore=file%3Acontent&%40search_text=2028+2029+json&submit=search&status=-1%2C1%2C2%2C3 I run Python 2.7.3. This may be a nice thing to have in the standard `json`, but it’s not a bug, because what `json.dumps()` returns is perfectly valid as JSON, it’s only problematic when you try to interpret it as JavaScript. So unsure whether to resolve this in JSONRenderer (as an enhancement) or in JSONPRenderer (as a bugfix). Aside: Personally I do still class this as a bug in the Python json lib, as there's no good reason why it should just always be escaped. The JSON spec clearly has a bug when it refers to being derived from "a small subset of ECMAScript" http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf Unclear why they don't at least add an ammendment _recommending_ that implementations escape those two characters.
2014-12-03T22:34:38
encode/django-rest-framework
2,196
encode__django-rest-framework-2196
[ "2194" ]
5f2f54b7fb52e35e3f47a677c2c5b9981c7d1f81
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -633,8 +633,8 @@ def create(self, validated_attrs): # If we don't do this explicitly they'd likely get a confusing # error at the point of calling `Model.objects.create()`. assert not any( - isinstance(field, BaseSerializer) and not field.read_only - for field in self.fields.values() + isinstance(field, BaseSerializer) and (key in validated_attrs) + for key, field in self.fields.items() ), ( 'The `.create()` method does not suport nested writable fields ' 'by default. Write an explicit `.create()` method for serializer ' @@ -681,8 +681,8 @@ def create(self, validated_attrs): def update(self, instance, validated_attrs): assert not any( - isinstance(field, BaseSerializer) and not field.read_only - for field in self.fields.values() + isinstance(field, BaseSerializer) and (key in validated_attrs) + for key, field in self.fields.items() ), ( 'The `.update()` method does not suport nested writable fields ' 'by default. Write an explicit `.update()` method for serializer '
Nested writable serializers validation in ModelSerializer.update method seems wrong The `update` method on `ModelSerializer` makes sure that the data doesn't contain nested writable fields of the `BaseSerializer` variety, as per the documentation. However, it doesn't actually assert this by looking at the passed `validated_attrs`. Instead, it does this by looking at `self.fields`: ``` python assert not any( isinstance(field, BaseSerializer) and not field.read_only for field in self.fields.values() ``` This means that even if we pop() the data of the nested serializer (as shown in the changelog example), the assertion still fails. This makes it necessary to call explicitly delete the field from `self.fields`: ``` python def update(self, instance, validated_attrs): try: # Removing user data - not wanted for an update. validated_attrs.pop('user') self.fields.__delitem__('user') # This shouldn't be necessary. except KeyError: pass return super(CustomerSerializer, self).update(instance=instance, validated_attrs=validated_attrs) ``` By the time it gets to `update`, the data has already been validated. So you should be able to assume that any fields not present can be ignored, no? In short, I'd say that it shouldn't trigger the error if the field isn't in the `validated_attrs`.
Okay, didn't consider the case of making a change to `validated_attrs` and then calling into the implementation with `super`. I'm just lazy and wanted to avoid having to write my own update code. Sorry!
2014-12-03T22:47:04
encode/django-rest-framework
2,215
encode__django-rest-framework-2215
[ "2202" ]
59b2ad542580eb93243c4403ded4c2b4dc8518c2
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -561,6 +561,64 @@ def errors(self): # ModelSerializer & HyperlinkedModelSerializer # -------------------------------------------- +def raise_errors_on_nested_writes(method_name, serializer): + """ + Give explicit errors when users attempt to pass writable nested data. + + If we don't do this explicitly they'd get a less helpful error when + calling `.save()` on the serializer. + + We don't *automatically* support these sorts of nested writes brecause + there are too many ambiguities to define a default behavior. + + Eg. Suppose we have a `UserSerializer` with a nested profile. How should + we handle the case of an update, where the `profile` realtionship does + not exist? Any of the following might be valid: + + * Raise an application error. + * Silently ignore the nested part of the update. + * Automatically create a profile instance. + """ + + # Ensure we don't have a writable nested field. For example: + # + # class UserSerializer(ModelSerializer): + # ... + # profile = ProfileSerializer() + assert not any( + isinstance(field, BaseSerializer) and (key in validated_attrs) + 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__ + ) + ) + + # Ensure we don't have a writable dotted-source field. For example: + # + # class UserSerializer(ModelSerializer): + # ... + # address = serializer.CharField('profile.address') + assert not any( + '.' in field.source and (key in validated_attrs) + for key, field in serializer.fields.items() + ), ( + 'The `.{method_name}()` method does not support writable dotted-source ' + 'fields by default.\nWrite an explicit `.{method_name}()` method for ' + 'serializer `{module}.{class_name}`, or set `read_only=True` on ' + 'dotted-source serializer fields.'.format( + method_name=method_name, + module=serializer.__class__.__module__, + class_name=serializer.__class__.__name__ + ) + ) + + class ModelSerializer(Serializer): """ A `ModelSerializer` is just a regular `Serializer`, except that: @@ -624,18 +682,7 @@ def create(self, validated_data): If you want to support writable nested relationships you'll need to write an explicit `.create()` method. """ - # Check that the user isn't trying to handle a writable nested field. - # If we don't do this explicitly they'd likely get a confusing - # error at the point of calling `Model.objects.create()`. - assert not any( - isinstance(field, BaseSerializer) and (key in validated_attrs) - for key, field in self.fields.items() - ), ( - 'The `.create()` method does not support nested writable fields ' - 'by default. Write an explicit `.create()` method for serializer ' - '`%s.%s`, or set `read_only=True` on nested serializer fields.' % - (self.__class__.__module__, self.__class__.__name__) - ) + raise_errors_on_nested_writes('create', self) ModelClass = self.Meta.model @@ -675,19 +722,12 @@ def create(self, validated_data): return instance def update(self, instance, validated_data): - assert not any( - isinstance(field, BaseSerializer) and (key in validated_attrs) - for key, field in self.fields.items() - ), ( - 'The `.update()` method does not support nested writable fields ' - 'by default. Write an explicit `.update()` method for serializer ' - '`%s.%s`, or set `read_only=True` on nested serializer fields.' % - (self.__class__.__module__, self.__class__.__name__) - ) + raise_errors_on_nested_writes('update', self) for attr, value in validated_data.items(): setattr(instance, attr, value) instance.save() + return instance def get_validators(self):
Better catching of error cases in `.update` and `.create`. When I do a PUT through the API browser to a view whose serializer contains a source property: ``` python last_name = serializers.CharField(source='user.last_name') ``` I receive the following error: ``` Cannot assign "{'first_name': u'first', 'last_name': u'last'}": "ContactInfo.user" must be a "User" instance ``` I've created a [bare-bones django project that reproduces the error](https://github.com/brianhv/drfissue). Of particular note are the [serializers](https://github.com/brianhv/drfissue/blob/master/drftest/drftest/readonly/serializers.py) and the [model](https://github.com/brianhv/drfissue/blob/master/drftest/drftest/readonly/models.py). Relevant excerpt of IRC conversation leading to this ticket: ``` <BrianHV> if you clone the repo, install the stuff in the requirements.txt (just django 1.6 and DRF 3), set up a user, and use admin to create a ContactInfo for the user, you should be able to reproduce <BrianHV> I'm testing through the API browser, btw. <kevin-brown> Yeah, I think I know what is happening <kevin-brown> `validated_data` is being (correctly?) generated as a nested dictionary, and that's being assigned to the `user` parameter directly <kevin-brown> If you can open a ticket explaining that it works in DRF 2.4, that'd be helpful <kevin-brown> In DRF 2.4, it would traverse the relation and assign the properties directly ```
Possible that we should make this case raise an explicit error explaining why it can't be dealt with automatically. You need to write an explicit create and/or update method here. Eg. There _isnt_ any way of automatically handling this case: What _are_ you expecting to happen on create? Create a new user instance? If so how would you determine a username? You probably only want to support updates on this serializer and override create to raise 'NotImplemented' but if that's not the case then you'll need to figure out what it is you want to happen instead. I've no doubt that 2.x would present some horrible buggy behaviour here. Incidentally what type was the exception you got? Would be useful to know so we can improve the error messaging. > Incidentally what type was the exception you got? [Pretty sure](http://stackoverflow.com/q/15337636/359284) this is a `ValueError`. We could expand [on the exception handling then](https://github.com/tomchristie/django-rest-framework/blob/f221b737a1c329277ac90b8e2049882e0dde3e6f/rest_framework/serializers.py#L658-673) Yep, ValueError. ``` Environment: Request Method: POST Request URL: http://localhost:8765/api/users/1/ Django Version: 1.6.8 Python Version: 2.7.5 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'drftest.readonly') Installed Middleware: ('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/bhv1/irccode/drfvirt/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 112. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/bhv1/irccode/drfvirt/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 57. return view_func(*args, **kwargs) File "/Users/bhv1/irccode/drfvirt/lib/python2.7/site-packages/rest_framework/viewsets.py" in view 79. return self.dispatch(request, *args, **kwargs) File "/Users/bhv1/irccode/drfvirt/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 406. response = self.handle_exception(exc) File "/Users/bhv1/irccode/drfvirt/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 403. response = handler(request, *args, **kwargs) File "/Users/bhv1/irccode/drfvirt/lib/python2.7/site-packages/rest_framework/mixins.py" in update 68. self.perform_update(serializer) File "/Users/bhv1/irccode/drfvirt/lib/python2.7/site-packages/rest_framework/mixins.py" in perform_update 72. serializer.save() File "/Users/bhv1/irccode/drfvirt/lib/python2.7/site-packages/rest_framework/serializers.py" in save 136. self.instance = self.update(self.instance, validated_data) File "/Users/bhv1/irccode/drfvirt/lib/python2.7/site-packages/rest_framework/serializers.py" in update 669. setattr(instance, attr, value) File "/Users/bhv1/irccode/drfvirt/lib/python2.7/site-packages/django/db/models/fields/related.py" in __set__ 339. self.field.name, self.field.rel.to._meta.object_name)) Exception Type: ValueError at /api/users/1/ Exception Value: Cannot assign "{'first_name': u'asdf', 'last_name': u'asdf'}": "ContactInfo.user" must be a "User" instance. ``` How about the following?... > Got a `ValueError` when calling `%s.objects.create()`. This may be because you have a field on the serializer class that is is returning the incorrect type for '`%s.objects.create()`. You probably need to either change the field type, or override the %s.create() method to handle this correctly.\nOriginal exception text was: %s.' Even more comprehensive would be to check for dotted source notation in the same way we do for writable nested fields. Here's my perspective as a newbie (and assuming `TypeError` was meant to be `ValueError`). My first response to that was similar to my response to the error I got: "Guess I can't do that, then." As I thought about it while finishing breakfast, my response shifted towards: "But if I really wanted to do it maybe that would tell me how if I were more familiar with the framework." At the moment, though, I've settled on, "Why is it trying to create something when I'm trying to update an existing record? I must really not be doing this the right way." If those are reasonable things to think in this situation, then that message would have the correct effect. > Why is it trying to create something Oops my error above is incorrect of course - this is not during `.objects.create()` it's during assignment in `update()`. Anyways, upshot is that we should look into better error reporting here. As it happens for "to one" relationships we _could_ try to handle this automatically _for updates only_ but there would still be error cases to deal with there (eg nullable relationship that does not exist) so not sure if we should try to do it automagically, or if we should force the code to be explicit.
2014-12-05T13:50:59
encode/django-rest-framework
2,232
encode__django-rest-framework-2232
[ "2168" ]
ef89c1566329f723e8a54f58ebe5aef51489f1b9
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -294,31 +294,47 @@ def get_default(self): return self.default() return self.default - def run_validation(self, data=empty): + def validate_empty_values(self, data): """ - Validate a simple representation and return the internal value. - - The provided data may be `empty` if no representation was included - in the input. - - May raise `SkipField` if the field should not be included in the - validated data. + Validate empty values, and either: + + * Raise `ValidationError`, indicating invalid data. + * Raise `SkipField`, indicating that the field should be ignored. + * Return (True, data), indicating an empty value that should be + returned without any furhter validation being applied. + * Return (False, data), indicating a non-empty value, that should + have validation applied as normal. """ if self.read_only: - return self.get_default() + return (True, self.get_default()) if data is empty: if getattr(self.root, 'partial', False): raise SkipField() if self.required: self.fail('required') - return self.get_default() + return (True, self.get_default()) if data is None: if not self.allow_null: self.fail('null') - return None + return (True, None) + + return (False, data) + def run_validation(self, data=empty): + """ + Validate a simple representation and return the internal value. + + The provided data may be `empty` if no representation was included + in the input. + + May raise `SkipField` if the field should not be included in the + validated data. + """ + (is_empty_value, data) = self.validate_empty_values(data) + if is_empty_value: + return data value = self.to_internal_value(data) self.run_validators(value) return value diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -229,6 +229,35 @@ def __new__(cls, name, bases, attrs): return super(SerializerMetaclass, cls).__new__(cls, name, bases, attrs) +def get_validation_error_detail(exc): + assert isinstance(exc, (ValidationError, DjangoValidationError)) + + if isinstance(exc, DjangoValidationError): + # Normally you should raise `serializers.ValidationError` + # inside your codebase, but we handle Django's validation + # exception class as well for simpler compat. + # Eg. Calling Model.clean() explicitly inside Serializer.validate() + return { + api_settings.NON_FIELD_ERRORS_KEY: list(exc.messages) + } + elif isinstance(exc.detail, dict): + # If errors may be a dict we use the standard {key: list of values}. + # Here we ensure that all the values are *lists* of errors. + return dict([ + (key, value if isinstance(value, list) else [value]) + for key, value in exc.detail.items() + ]) + elif isinstance(exc.detail, list): + # Errors raised as a list are non-field errors. + return { + api_settings.NON_FIELD_ERRORS_KEY: exc.detail + } + # Errors raised as a string are non-field errors. + return { + api_settings.NON_FIELD_ERRORS_KEY: [exc.detail] + } + + @six.add_metaclass(SerializerMetaclass) class Serializer(BaseSerializer): default_error_messages = { @@ -293,55 +322,17 @@ def run_validation(self, data=empty): performed by validators and the `.validate()` method should be coerced into an error dictionary with a 'non_fields_error' key. """ - if data is empty: - if getattr(self.root, 'partial', False): - raise SkipField() - if self.required: - self.fail('required') - return self.get_default() - - if data is None: - if not self.allow_null: - self.fail('null') - return None - - if not isinstance(data, dict): - message = self.error_messages['invalid'].format( - datatype=type(data).__name__ - ) - raise ValidationError({ - api_settings.NON_FIELD_ERRORS_KEY: [message] - }) + (is_empty_value, data) = self.validate_empty_values(data) + if is_empty_value: + return data value = self.to_internal_value(data) try: self.run_validators(value) value = self.validate(value) assert value is not None, '.validate() should return the validated data' - except ValidationError as exc: - if isinstance(exc.detail, dict): - # .validate() errors may be a dict, in which case, use - # standard {key: list of values} style. - raise ValidationError(dict([ - (key, value if isinstance(value, list) else [value]) - for key, value in exc.detail.items() - ])) - elif isinstance(exc.detail, list): - raise ValidationError({ - api_settings.NON_FIELD_ERRORS_KEY: exc.detail - }) - else: - raise ValidationError({ - api_settings.NON_FIELD_ERRORS_KEY: [exc.detail] - }) - except DjangoValidationError as exc: - # Normally you should raise `serializers.ValidationError` - # inside your codebase, but we handle Django's validation - # exception class as well for simpler compat. - # Eg. Calling Model.clean() explicitly inside Serializer.validate() - raise ValidationError({ - api_settings.NON_FIELD_ERRORS_KEY: list(exc.messages) - }) + except (ValidationError, DjangoValidationError) as exc: + raise ValidationError(detail=get_validation_error_detail(exc)) return value @@ -349,6 +340,14 @@ def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ + if not isinstance(data, dict): + message = self.error_messages['invalid'].format( + datatype=type(data).__name__ + ) + raise ValidationError({ + api_settings.NON_FIELD_ERRORS_KEY: [message] + }) + ret = OrderedDict() errors = OrderedDict() fields = [ @@ -462,6 +461,26 @@ def get_value(self, dictionary): return html.parse_html_list(dictionary, prefix=self.field_name) return dictionary.get(self.field_name, empty) + def run_validation(self, data=empty): + """ + We override the default `run_validation`, because the validation + performed by validators and the `.validate()` method should + be coerced into an error dictionary with a 'non_fields_error' key. + """ + (is_empty_value, data) = self.validate_empty_values(data) + if is_empty_value: + return data + + value = self.to_internal_value(data) + try: + self.run_validators(value) + value = self.validate(value) + assert value is not None, '.validate() should return the validated data' + except (ValidationError, DjangoValidationError) as exc: + raise ValidationError(detail=get_validation_error_detail(exc)) + + return value + def to_internal_value(self, data): """ List of dicts of native values <- List of dicts of primitive datatypes. @@ -503,6 +522,9 @@ def to_representation(self, data): self.child.to_representation(item) for item in iterable ] + def validate(self, attrs): + return attrs + def update(self, instance, validated_data): raise NotImplementedError( "Serializers with many=True do not support multiple update by "
diff --git a/tests/test_serializer_lists.py b/tests/test_serializer_lists.py --- a/tests/test_serializer_lists.py +++ b/tests/test_serializer_lists.py @@ -272,3 +272,19 @@ def test_validate_html_input(self): serializer = self.Serializer(data=input_data) assert serializer.is_valid() assert serializer.validated_data == expected_output + + +class TestListSerializerClass: + """Tests for a custom list_serializer_class.""" + def test_list_serializer_class_validate(self): + class CustomListSerializer(serializers.ListSerializer): + def validate(self, attrs): + raise serializers.ValidationError('Non field error') + + class TestSerializer(serializers.Serializer): + class Meta: + list_serializer_class = CustomListSerializer + + serializer = TestSerializer(data=[], many=True) + assert not serializer.is_valid() + assert serializer.errors == {'non_field_errors': ['Non field error']}
Add `ListSerializer.validate()` In d2d7e1d `Field.validate` was removed. This means that `ListSerializer.validate` is no longer called in `ListSerializer.run_validation`. I can use `ListSerializer.to_internal_value` instead, but this feels very weird on a serializer.
> Should ListSerializer.validate exist? Yes, I think it should.
2014-12-08T14:59:22
encode/django-rest-framework
2,239
encode__django-rest-framework-2239
[ "2184" ]
cae19f8924c598cea93a546138757ff48eed9f75
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -958,9 +958,14 @@ def __init__(self, choices, **kwargs): (six.text_type(key), key) for key in self.choices.keys() ]) + self.allow_blank = kwargs.pop('allow_blank', False) + super(ChoiceField, self).__init__(**kwargs) def to_internal_value(self, data): + if data == '' and self.allow_blank: + return '' + try: return self.choice_strings_to_values[six.text_type(data)] except KeyError: diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -942,7 +942,7 @@ def get_fields(self): # `ModelField`, which is used when no other typed field # matched to the model field. kwargs.pop('model_field', None) - if not issubclass(field_cls, CharField): + if not issubclass(field_cls, CharField) and not issubclass(field_cls, ChoiceField): # `allow_blank` is only valid for textual fields. kwargs.pop('allow_blank', None) diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -91,18 +91,18 @@ def get_field_kwargs(field_name, model_field): if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False - if model_field.flatchoices: - # If this model field contains choices, then return early. - # Further keyword arguments are not valid. - kwargs['choices'] = model_field.flatchoices - return kwargs - if model_field.null and not isinstance(model_field, models.NullBooleanField): kwargs['allow_null'] = True if model_field.blank: kwargs['allow_blank'] = True + if model_field.flatchoices: + # If this model field contains choices, then return early. + # Further keyword arguments are not valid. + kwargs['choices'] = model_field.flatchoices + return kwargs + # Ensure that max_length is passed explicitly as a keyword arg, # rather than as a validator. max_length = getattr(model_field, 'max_length', None)
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -804,6 +804,21 @@ class TestChoiceField(FieldValues): ] ) + def test_allow_blank(self): + """ + If `allow_blank=True` then '' is a valid input. + """ + field = serializers.ChoiceField( + allow_blank=True, + choices=[ + ('poor', 'Poor quality'), + ('medium', 'Medium quality'), + ('good', 'Good quality'), + ] + ) + output = field.run_validation('') + assert output is '' + class TestChoiceFieldWithType(FieldValues): """
ChoiceField with required=False not optional in HTML view Hello, I have a db model containing: ``` action = models.CharField(max_length=4, null=True, blank=True, choices=PHOTO_ACTION, db_index=True) ``` ModelSerializer I believe turns this into a ChoiceField. Unfortunately the choice list doesn't list an appropriate value to correspond with None. I have tried setting required=False, but it has no affect. Thanks.
Looks like we may currently support this in `allow_null`, but not `allow_blank`. We should probably support both options. https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/templates/rest_framework/horizontal/select.html#L7 Still surprising tho as you do also have `null=True` on that model field. It'd be helpful to see the serializer field it generates - could you do `print(repr(MySerializer))` in the Django shell and include the output for the `action` field on this ticket. Unfortunately, that is not very helpful: ``` In [5]: print(repr(spud.serializers.PhotoSerializer)) <class 'spud.serializers.PhotoSerializer'> ``` Ok, from within the program, did a print(repr(serializer.get_fields())) instead. That gives me: ``` ('action', ChoiceField(choices=[(u'D', u'delete'), (u'S', u'regenerate size'), (u'R', u'regenerate thumbnails'), (u'V', u'regenerate video'), (u'M', u'move photo'), (u'auto', u'rotate automatic'), (u'90', u'rotate 90 degrees clockwise'), (u'180', u'rotate 180 degrees clockwise'), (u'270', u'rotate 270 degrees clockwise')], required=False)), ``` Which lists all the choices except for the None choice. Is this what you where after? > print(repr(spud.serializers.PhotoSerializer())) You were missing the `()` to instantiate the serializer. Above would have worked. > Is this what you where after? Yes, thank you. To do: Add `allow_blank` for ChoiceField, and ensure it gets mapped to from model field -> serializer field. Working on this, but having trouble figuring out what tests should be added.
2014-12-09T13:26:03
encode/django-rest-framework
2,242
encode__django-rest-framework-2242
[ "1872" ]
7d70e56ce378a7876a0fd7f29b52a492e46053b9
diff --git a/rest_framework/relations.py b/rest_framework/relations.py --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -84,9 +84,20 @@ def get_queryset(self): queryset = queryset.all() return queryset - def get_iterable(self, instance, source_attrs): - relationship = get_attribute(instance, source_attrs) - return relationship.all() if (hasattr(relationship, 'all')) else relationship + def use_pk_only_optimization(self): + return False + + def get_attribute(self, instance): + if self.use_pk_only_optimization() and self.source_attrs: + # Optimized case, return a mock object only containing the pk attribute. + try: + instance = get_attribute(instance, self.source_attrs[:-1]) + return PKOnlyObject(pk=instance.serializable_value(self.source_attrs[-1])) + except AttributeError: + pass + + # Standard case, return the object instance. + return get_attribute(instance, self.source_attrs) @property def choices(self): @@ -120,6 +131,9 @@ class PrimaryKeyRelatedField(RelatedField): 'incorrect_type': _('Incorrect type. Expected pk value, received {data_type}.'), } + def use_pk_only_optimization(self): + return True + def to_internal_value(self, data): try: return self.get_queryset().get(pk=data) @@ -128,32 +142,6 @@ def to_internal_value(self, data): except (TypeError, ValueError): self.fail('incorrect_type', data_type=type(data).__name__) - def get_attribute(self, instance): - # We customize `get_attribute` here for performance reasons. - # For relationships the instance will already have the pk of - # the related object. We return this directly instead of returning the - # object itself, which would require a database lookup. - try: - instance = get_attribute(instance, self.source_attrs[:-1]) - return PKOnlyObject(pk=instance.serializable_value(self.source_attrs[-1])) - except AttributeError: - return get_attribute(instance, self.source_attrs) - - def get_iterable(self, instance, source_attrs): - # For consistency with `get_attribute` we're using `serializable_value()` - # here. Typically there won't be any difference, but some custom field - # types might return a non-primitive value for the pk otherwise. - # - # We could try to get smart with `values_list('pk', flat=True)`, which - # would be better in some case, but would actually end up with *more* - # queries if the developer is using `prefetch_related` across the - # relationship. - relationship = super(PrimaryKeyRelatedField, self).get_iterable(instance, source_attrs) - return [ - PKOnlyObject(pk=item.serializable_value('pk')) - for item in relationship - ] - def to_representation(self, value): return value.pk @@ -184,6 +172,9 @@ def __init__(self, view_name=None, **kwargs): super(HyperlinkedRelatedField, self).__init__(**kwargs) + def use_pk_only_optimization(self): + return self.lookup_field == 'pk' + def get_object(self, view_name, view_args, view_kwargs): """ Return the object corresponding to a matched URL. @@ -285,6 +276,11 @@ def __init__(self, view_name=None, **kwargs): kwargs['source'] = '*' super(HyperlinkedIdentityField, self).__init__(view_name, **kwargs) + def use_pk_only_optimization(self): + # We have the complete object instance already. We don't need + # to run the 'only get the pk for this relationship' code. + return False + class SlugRelatedField(RelatedField): """ @@ -349,7 +345,8 @@ def to_internal_value(self, data): ] def get_attribute(self, instance): - return self.child_relation.get_iterable(instance, self.source_attrs) + relationship = get_attribute(instance, self.source_attrs) + return relationship.all() if (hasattr(relationship, 'all')) else relationship def to_representation(self, iterable): return [
diff --git a/tests/test_relations_hyperlink.py b/tests/test_relations_hyperlink.py --- a/tests/test_relations_hyperlink.py +++ b/tests/test_relations_hyperlink.py @@ -89,7 +89,14 @@ def test_many_to_many_retrieve(self): {'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']}, {'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']} ] - self.assertEqual(serializer.data, expected) + with self.assertNumQueries(4): + self.assertEqual(serializer.data, expected) + + def test_many_to_many_retrieve_prefetch_related(self): + queryset = ManyToManySource.objects.all().prefetch_related('targets') + serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) + with self.assertNumQueries(2): + serializer.data def test_reverse_many_to_many_retrieve(self): queryset = ManyToManyTarget.objects.all() @@ -99,7 +106,8 @@ def test_reverse_many_to_many_retrieve(self): {'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']}, {'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']} ] - self.assertEqual(serializer.data, expected) + with self.assertNumQueries(4): + self.assertEqual(serializer.data, expected) def test_many_to_many_update(self): data = {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']} @@ -197,7 +205,8 @@ def test_foreign_key_retrieve(self): {'url': 'http://testserver/foreignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, {'url': 'http://testserver/foreignkeysource/3/', 'name': 'source-3', 'target': 'http://testserver/foreignkeytarget/1/'} ] - self.assertEqual(serializer.data, expected) + with self.assertNumQueries(1): + self.assertEqual(serializer.data, expected) def test_reverse_foreign_key_retrieve(self): queryset = ForeignKeyTarget.objects.all() @@ -206,7 +215,8 @@ def test_reverse_foreign_key_retrieve(self): {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/2/', 'http://testserver/foreignkeysource/3/']}, {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []}, ] - self.assertEqual(serializer.data, expected) + with self.assertNumQueries(3): + self.assertEqual(serializer.data, expected) def test_foreign_key_update(self): data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'} diff --git a/tests/test_relations_pk.py b/tests/test_relations_pk.py --- a/tests/test_relations_pk.py +++ b/tests/test_relations_pk.py @@ -71,6 +71,12 @@ def test_many_to_many_retrieve(self): with self.assertNumQueries(4): self.assertEqual(serializer.data, expected) + def test_many_to_many_retrieve_prefetch_related(self): + queryset = ManyToManySource.objects.all().prefetch_related('targets') + serializer = ManyToManySourceSerializer(queryset, many=True) + with self.assertNumQueries(2): + serializer.data + def test_reverse_many_to_many_retrieve(self): queryset = ManyToManyTarget.objects.all() serializer = ManyToManyTargetSerializer(queryset, many=True) @@ -188,6 +194,12 @@ def test_reverse_foreign_key_retrieve(self): with self.assertNumQueries(3): self.assertEqual(serializer.data, expected) + def test_reverse_foreign_key_retrieve_prefetch_related(self): + queryset = ForeignKeyTarget.objects.all().prefetch_related('sources') + serializer = ForeignKeyTargetSerializer(queryset, many=True) + with self.assertNumQueries(2): + serializer.data + def test_foreign_key_update(self): data = {'id': 1, 'name': 'source-1', 'target': 2} instance = ForeignKeySource.objects.get(pk=1) diff --git a/tests/test_relations_slug.py b/tests/test_relations_slug.py --- a/tests/test_relations_slug.py +++ b/tests/test_relations_slug.py @@ -54,7 +54,14 @@ def test_foreign_key_retrieve(self): {'id': 2, 'name': 'source-2', 'target': 'target-1'}, {'id': 3, 'name': 'source-3', 'target': 'target-1'} ] - self.assertEqual(serializer.data, expected) + with self.assertNumQueries(4): + self.assertEqual(serializer.data, expected) + + def test_foreign_key_retrieve_select_related(self): + queryset = ForeignKeySource.objects.all().select_related('target') + serializer = ForeignKeySourceSerializer(queryset, many=True) + with self.assertNumQueries(1): + serializer.data def test_reverse_foreign_key_retrieve(self): queryset = ForeignKeyTarget.objects.all() @@ -65,6 +72,12 @@ def test_reverse_foreign_key_retrieve(self): ] self.assertEqual(serializer.data, expected) + def test_reverse_foreign_key_retrieve_prefetch_related(self): + queryset = ForeignKeyTarget.objects.all().prefetch_related('sources') + serializer = ForeignKeyTargetSerializer(queryset, many=True) + with self.assertNumQueries(2): + serializer.data + def test_foreign_key_update(self): data = {'id': 1, 'name': 'source-1', 'target': 'target-2'} instance = ForeignKeySource.objects.get(pk=1)
Optimize pk-based hyperlinked relationships. Maybe I'm doing something wrong here. When I ask my application for a list of objects (e.g. /my-objects/) it makes 2 initial database queries (one for the count and one for the list). Then during serialization - using hyperlinked serialization - for each related field on each object another query is fired. So I easily end up with more than 200 database queries for a simple list - that's just unacceptable. Looking into the code it's clear what causes this: in order to create the hyperlinks to the related objects, those objects must be loaded (often the same object is loaded 100 times). So my assumption is that the described behavior is not caused by misconfiguration but by design. I created a kind of hacky solution which uses the _my_related_object_id_ property to generate the url for _my_related_object_ without loading the object (of which only the id is used anyway). Is that valid? Shouldn't this be something that's done by drf? It seems to work, haven't had any problems so far. Even when this is solved the combination with nested routes is a whole new adventure, but that's out of the scope of this project / ticket :)
Let me start off by saying that this is a known issue with Django REST Framework, but it's also _very_ difficult to solve for the general use case. > Shouldn't this be something that's done by drf? While this sounds like a really easy fix that should work for everyone, not everyone links by the `id`, and that is why we don't do this by default. That doesn't make it a bad move though, as there really isn't a general use case here. I have had success working around this issue with combinations of `select_related` and `prefetch_related` when getting the queryset in `get_queryset`. It's not something which DRF can detect and add in automatically, as there are tons of cases to consider. Seconding @kevin-brown, tho it would be great if we could come up with a sensible answer to this. Going to re-review as part of the 3.0 release. Thanks for the explanation, sounds plausible to me. I feel encouraged to go with the solution I have so far - we'll see how far it carries. Also, I'm using `select_related` for the nested routes because they surely need the related objects in order to create the urls for those. In the end the number of models / serializers is limited and the code is not too hard to write. So there is always the option to modify the queryset per model as you suggested. I'll close this issue and check again in version 3.0. In case I come up with something extremely intelligent and generic I'll let you know, but that's kinda unlikely because we only link via id. I haven't checked whether this is fixed in 3.0, but FWIW in 2.x `PrimaryKeyRelatedField` already has some workarounds to avoid unnecessarily querying related objects when all that's needed is their PK, but `HyperlinkedRelatedField` has no such workarounds, even though it also needs only the PK. For now I'm using this workaround in a subclass of `HyperlinkedRelatedField`: ``` + def field_to_native(self, obj, field_name): + """Avoid querying for related objects when all we need is the pk.""" + source = self.source or field_name + if obj is not None and '.' not in source and not self.many: + stub = HyperlinkedRelatedStub( + **{self.lookup_field: getattr(obj, source + '_id')}) + return self.to_native(stub) + return super(HyperlinkedRelatedField, self).field_to_native( + obj, field_name) ``` where `HyperlinkedRelatedStub` is just: ``` class HyperlinkedRelatedStub(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) ``` It's not the prettiest solution, due to the need for that stub object, but the stub avoids the need to change the signature of `HyperlinkedRelatedField.to_native` or `HyperlinkedRelatedField.get_url`, and I haven't dug in to see if those might be called from elsewhere. I'm sure that it would be possible to apply a nicer fix-up to `HyperlinkedRelatedField` that would avoid needless queries on related objects (presuming it hasn't already been done in 3.0). Not yet done for 3.0, but yes planned, and won't be much work at all. Re opening this to ensure it stays tracked.
2014-12-09T17:29:36
encode/django-rest-framework
2,266
encode__django-rest-framework-2266
[ "2263" ]
eb78da4b5441bec1758e7d6db86822b3ea890f5f
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -611,6 +611,7 @@ 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)) for key, field in serializer.fields.items() ), ( 'The `.{method_name}()` method does not support writable nested' @@ -630,6 +631,7 @@ def raise_errors_on_nested_writes(method_name, serializer, validated_data): # address = serializer.CharField('profile.address') assert not any( '.' in field.source and (key in validated_data) + and isinstance(validated_data[key], (list, dict)) for key, field in serializer.fields.items() ), ( 'The `.{method_name}()` method does not support writable dotted-source '
Improve error checking for nested writes. See https://github.com/tomchristie/django-rest-framework/pull/2196#issuecomment-66818050 There are cases indicated as nested writes that actually are not. Typically won't happen but case linked above is an example of how it can. We could additionally only fail if the validated date element is a dict or list. This would improve the robustness of the check.
2014-12-13T14:19:17
encode/django-rest-framework
2,267
encode__django-rest-framework-2267
[ "2262" ]
6158285856b4dee77640883cf3fde3407af9ff2a
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -274,7 +274,23 @@ def get_attribute(self, instance): Given the *outgoing* object instance, return the primitive value that should be used for this field. """ - return get_attribute(instance, self.source_attrs) + try: + return get_attribute(instance, self.source_attrs) + except (KeyError, AttributeError) as exc: + msg = ( + 'Got {exc_type} when attempting to get a value for field ' + '`{field}` on serializer `{serializer}`.\nThe serializer ' + 'field might be named incorrectly and not match ' + 'any attribute or key on the `{instance}` instance.\n' + 'Original exception text was: {exc}.'.format( + exc_type=type(exc).__name__, + field=self.field_name, + serializer=self.parent.__class__.__name__, + instance=instance.__class__.__name__, + exc=exc + ) + ) + raise type(exc)(msg) def get_default(self): """
diff --git a/tests/test_serializer.py b/tests/test_serializer.py --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals from rest_framework import serializers import pytest @@ -175,3 +176,24 @@ def test_nested_serialize(self): instance = {'a': 1, 'b': 2, 'c': 3, 'd': 4} serializer = self.Serializer(instance) assert serializer.data == self.data + + +class TestIncorrectlyConfigured: + def test_incorrect_field_name(self): + class ExampleSerializer(serializers.Serializer): + incorrect_name = serializers.IntegerField() + + class ExampleObject: + def __init__(self): + self.correct_name = 123 + + instance = ExampleObject() + serializer = ExampleSerializer(instance) + with pytest.raises(AttributeError) as exc_info: + serializer.data + msg = str(exc_info.value) + assert msg.startswith( + "Got AttributeError when attempting to get a value for field `incorrect_name` on serializer `ExampleSerializer`.\n" + "The serializer field might be named incorrectly and not match any attribute or key on the `ExampleObject` instance.\n" + "Original exception text was:" + )
Better errors when serializer has incorrectly named field. If I have a mistake in my model serializer where there's a serializer field name that isn't mapped to a field in the model, e.g. ``` class MySerializer(serializers.ModelSerializer): bad_serializer_field_name = MyCustomSerializer() ``` then the serializer fails silently and by returning no no data. It would be nice for debugging if the serialization process would issue a warning.
2014-12-13T15:00:53
encode/django-rest-framework
2,291
encode__django-rest-framework-2291
[ "2289" ]
426547c61c725ca7dc47671c084d1a2805c92305
diff --git a/rest_framework/generics.py b/rest_framework/generics.py --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -79,16 +79,14 @@ def get_serializer_context(self): 'view': self } - def get_serializer(self, instance=None, data=None, many=False, partial=False): + def get_serializer(self, *args, **kwargs): """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializer_class = self.get_serializer_class() - context = self.get_serializer_context() - return serializer_class( - instance, data=data, many=many, partial=partial, context=context - ) + kwargs['context'] = self.get_serializer_context() + return serializer_class(*args, **kwargs) def get_pagination_serializer(self, page): """ diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -544,12 +544,12 @@ def get_rendered_html_form(self, data, view, method, request): # serializer instance, rather than dynamically creating a new one. if request.method == method and serializer is not None: try: - data = request.data + kwargs = {'data': request.data} except ParseError: - data = None + kwargs = {} existing_serializer = serializer else: - data = None + kwargs = {} existing_serializer = None with override_method(view, request, method) as request: @@ -569,11 +569,13 @@ def get_rendered_html_form(self, data, view, method, request): serializer = existing_serializer else: if method in ('PUT', 'PATCH'): - serializer = view.get_serializer(instance=instance, data=data) + serializer = view.get_serializer(instance=instance, **kwargs) else: - serializer = view.get_serializer(data=data) - if data is not None: - serializer.is_valid() + serializer = view.get_serializer(**kwargs) + + if hasattr(serializer, 'initial_data'): + serializer.is_valid() + form_renderer = self.form_renderer_class() return form_renderer.render( serializer.data, diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -58,11 +58,31 @@ class BaseSerializer(Field): """ The BaseSerializer class provides a minimal class which may be used for writing custom serializer implementations. + + Note that we strongly restrict the ordering of operations/properties + that may be used on the serializer in order to enforce correct usage. + + In particular, if a `data=` argument is passed then: + + .is_valid() - Available. + .initial_data - Available. + .validated_data - Only available after calling `is_valid()` + .errors - Only available after calling `is_valid()` + .data - Only available after calling `is_valid()` + + If a `data=` argument is not passed then: + + .is_valid() - Not available. + .initial_data - Not available. + .validated_data - Not available. + .errors - Not available. + .data - Available. """ - def __init__(self, instance=None, data=None, **kwargs): + def __init__(self, instance=None, data=empty, **kwargs): self.instance = instance - self._initial_data = data + if data is not empty: + self.initial_data = data self.partial = kwargs.pop('partial', False) self._context = kwargs.pop('context', {}) kwargs.pop('many', None) @@ -156,9 +176,14 @@ def is_valid(self, raise_exception=False): (self.__class__.__module__, self.__class__.__name__) ) + assert hasattr(self, 'initial_data'), ( + 'Cannot call `.is_valid()` as no `data=` keyword argument was' + 'passed when instantiating the serializer instance.' + ) + if not hasattr(self, '_validated_data'): try: - self._validated_data = self.run_validation(self._initial_data) + self._validated_data = self.run_validation(self.initial_data) except ValidationError as exc: self._validated_data = {} self._errors = exc.detail @@ -172,6 +197,16 @@ def is_valid(self, raise_exception=False): @property def data(self): + if hasattr(self, 'initial_data') and not hasattr(self, '_validated_data'): + msg = ( + 'When a serializer is passed a `data` keyword argument you ' + 'must call `.is_valid()` before attempting to access the ' + 'serialized `.data` representation.\n' + 'You should either call `.is_valid()` first, ' + 'or access `.initial_data` instead.' + ) + raise AssertionError(msg) + if not hasattr(self, '_data'): if self.instance is not None and not getattr(self, '_errors', None): self._data = self.to_representation(self.instance) @@ -295,11 +330,11 @@ def get_validators(self): return getattr(getattr(self, 'Meta', None), 'validators', []) def get_initial(self): - if self._initial_data is not None: + if hasattr(self, 'initial_data'): return OrderedDict([ - (field_name, field.get_value(self._initial_data)) + (field_name, field.get_value(self.initial_data)) for field_name, field in self.fields.items() - if field.get_value(self._initial_data) is not empty + if field.get_value(self.initial_data) is not empty and not field.read_only ]) @@ -447,8 +482,8 @@ def __init__(self, *args, **kwargs): self.child.bind(field_name='', parent=self) def get_initial(self): - if self._initial_data is not None: - return self.to_representation(self._initial_data) + if hasattr(self, 'initial_data'): + return self.to_representation(self.initial_data) return [] def get_value(self, dictionary):
diff --git a/tests/test_bound_fields.py b/tests/test_bound_fields.py --- a/tests/test_bound_fields.py +++ b/tests/test_bound_fields.py @@ -22,7 +22,7 @@ class ExampleSerializer(serializers.Serializer): amount = serializers.IntegerField() serializer = ExampleSerializer(data={'text': 'abc', 'amount': 123}) - + assert serializer.is_valid() assert serializer['text'].value == 'abc' assert serializer['text'].errors is None assert serializer['text'].name == 'text'
When validating input prevent `serializer.data` being accessed until `.is_valid()` is called. See #2276, #2284 for examples of this causing confusion... Folks attempting to access `.data` inside internal methods on serializer. Error should probably mention `.initial_data`.
2014-12-17T14:15:48
encode/django-rest-framework
2,294
encode__django-rest-framework-2294
[ "2280" ]
76cfc5eb8a0a0e34a47020f85e9f4b7a94accf5e
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -185,8 +185,13 @@ def __init__(self, read_only=False, write_only=False, self.allow_null = allow_null if allow_null and self.default_empty_html is empty: + # HTML input cannot represent `None` values, so we need to + # forcibly coerce empty HTML values to `None` if `allow_null=True`. self.default_empty_html = None + if default is not empty: + self.default_empty_html = default + if validators is not None: self.validators = validators[:]
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -215,6 +215,26 @@ class MockHTMLDict(dict): assert serializer.validated_data == {'archived': False} +class TestCharHTMLInput: + def setup(self): + class TestSerializer(serializers.Serializer): + message = serializers.CharField(default='happy') + self.Serializer = TestSerializer + + def test_empty_html_checkbox(self): + """ + HTML checkboxes do not send any value, but should be treated + as `False` by BooleanField. + """ + # This class mocks up a dictionary like object, that behaves + # as if it was returned for multipart or urlencoded data. + class MockHTMLDict(dict): + getlist = None + serializer = self.Serializer(data=MockHTMLDict()) + assert serializer.is_valid() + assert serializer.validated_data == {'message': 'happy'} + + class TestCreateOnlyDefault: def setup(self): default = serializers.CreateOnlyDefault('2001-01-01')
Fix empty HTML values when a default is provided. Attribute 'default_empty_html' by BooleanField/CharField ignores 'default'/'allow_blank'. For example, if we get empty data, all Boolean instance has False, all CharField has ''. ``` for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) ... def get_value(self, dictionary): ... if self.field_name not in dictionary: .... return self.default_empty_html ... ``` I guess 'default_empty_html' should be empty.
2014-12-17T15:14:20
encode/django-rest-framework
2,311
encode__django-rest-framework-2311
[ "1101" ]
e8b46413a769d04ffac2c35bb10a9556d242022c
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -184,13 +184,11 @@ def __init__(self, read_only=False, write_only=False, self.style = {} if style is None else style self.allow_null = allow_null - if allow_null and self.default_empty_html is empty: - # HTML input cannot represent `None` values, so we need to - # forcibly coerce empty HTML values to `None` if `allow_null=True`. - self.default_empty_html = None - - if default is not empty: - self.default_empty_html = default + if self.default_empty_html is not empty: + if not required: + self.default_empty_html = empty + elif default is not empty: + self.default_empty_html = default if validators is not None: self.validators = validators[:] @@ -562,6 +560,11 @@ def __init__(self, **kwargs): message = self.error_messages['min_length'].format(min_length=min_length) self.validators.append(MinLengthValidator(min_length, message=message)) + if self.allow_null and (not self.allow_blank) and (self.default is empty): + # HTML input cannot represent `None` values, so we need to + # forcibly coerce empty HTML values to `None` if `allow_null=True`. + self.default_empty_html = None + def run_validation(self, data=empty): # Test for the empty string here so that it does not get validated, # and so that subclasses do not need to handle it explicitly
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -215,25 +215,47 @@ class MockHTMLDict(dict): assert serializer.validated_data == {'archived': False} +class MockHTMLDict(dict): + """ + This class mocks up a dictionary like object, that behaves + as if it was returned for multipart or urlencoded data. + """ + getlist = None + + class TestCharHTMLInput: - def setup(self): + def test_empty_html_checkbox(self): class TestSerializer(serializers.Serializer): message = serializers.CharField(default='happy') - self.Serializer = TestSerializer - def test_empty_html_checkbox(self): - """ - HTML checkboxes do not send any value, but should be treated - as `False` by BooleanField. - """ - # This class mocks up a dictionary like object, that behaves - # as if it was returned for multipart or urlencoded data. - class MockHTMLDict(dict): - getlist = None - serializer = self.Serializer(data=MockHTMLDict()) + serializer = TestSerializer(data=MockHTMLDict()) assert serializer.is_valid() assert serializer.validated_data == {'message': 'happy'} + def test_empty_html_checkbox_allow_null(self): + class TestSerializer(serializers.Serializer): + message = serializers.CharField(allow_null=True) + + serializer = TestSerializer(data=MockHTMLDict()) + assert serializer.is_valid() + assert serializer.validated_data == {'message': None} + + def test_empty_html_checkbox_allow_null_allow_blank(self): + class TestSerializer(serializers.Serializer): + message = serializers.CharField(allow_null=True, allow_blank=True) + + serializer = TestSerializer(data=MockHTMLDict({})) + assert serializer.is_valid() + assert serializer.validated_data == {'message': ''} + + def test_empty_html_required_false(self): + class TestSerializer(serializers.Serializer): + message = serializers.CharField(required=False) + + serializer = TestSerializer(data=MockHTMLDict()) + assert serializer.is_valid() + assert serializer.validated_data == {} + class TestCreateOnlyDefault: def setup(self):
Model defaults ignored on empty text field or empty boolean field. My tables has boolean fields like below. ``` enabled = models.BooleanField(default=True) ``` and save it using a serializer in a view class without passing the enabled field in the request. ``` serializer = SomeSerializer(data=request.DATA) if serializer.is_valid(): object = serializer.save() ``` the result is `object.enabled == False`. I've updated the framework to version 2.3.8 then the issue started occurring. Everything works fine in 2.3.7. Affected versions >= 2.3.8
this problem have in tests and when open auto generic api web, in section raw data Content: { "is_active": false, "username": "", "email": "", "name": "" } but in models is_active default = True but if send post request via curl or another...everything is working properly, is_active set TRUE This problem hasn't fixed even in 2.3.9. I can't update it from 2.3.7 because of this, breaking numerous test cases. Is there any open pull request associated with this issue? First starting point would be coding a failing test case. I have never submitted a patch or anything before, but would this be a suitable failing test case? Would it work with /tests/test_serializer.py? ``` class DefaultTrueBooleanModel(models.Model): enabled = models.BooleanField(default=True) class SerializerDefaultTrueBoolean(TestCase): def setUp(self): super(SerializerDefaultTrueBoolean, self).setUp() class DefaultTrueBooleanSerializer(serializers.ModelSerializer): class Meta: model = DefaultTrueBooleanModel fields = ('enabled') self.default_true_boolean_serializer = DefaultTrueBooleanSerializer def test_blank_input(self): serializer = self.default_true_boolean_serializer() self.assertEqual(serializer.data['enabled'], True) def test_enabled_as_false(self): serializer = self.default_true_boolean_serializer({'enabled': False}) self.assertEqual(serializer.data['enabled'], False) def test_enabled_as_true(self): serializer = self.default_true_boolean_serializer({'enabled': True}) self.assertEqual(serializer.data['enabled'], True) ``` Hello, I encountered this bug when upgrading from version 2.3.9 to 2.3.12 of django-rest-framework, and eventually narrowed it down to this commit (https://github.com/tomchristie/django-rest-framework/commit/90edcbf938ed8d6f3b783372c17e60bbf0761b61). I think this fix doesn't quite address what the actual issue is: the issue is that if you create an object using the HTML form and leave a checkbox unchecked, it will _leave out_ that value from the form, and that _should_ be interpreted as indicating that the value should be _false_, regardless of its default; whereas if you create an object using some other format (JSON or whatever) and leave out a value, that means the value should be _its default_. In other words, the same data needs to be treated differently depending on whether it came from an HTML form or not. So I think this means that either the HTML form needs to be changed to explicitly represent an unchecked checkbox as meaning false (which I'm not sure whether is possible), or the serializer needs to be changed to check whether its data came from an HTML form or not (which I'm also not sure whether is possible, but maybe it could be done in some pre-serializer step?). Is this a correct assessment? I'm going to put in a fix on my end for the specific case I have, and if I have time I'll try to figure out how to fix it within django-rest-framework. But if someone who's familiar with the code knows of any obvious fixes, that would be great. Avril > if you create an object using the HTML form and leave a checkbox unchecked, it will leave out that value from the form, and that should be interpreted as indicating that the value should be false, regardless of its default; whereas if you create an object using some other format (JSON or whatever) and leave out a value, that means the value should be its default. That all sounds sensible, yeah. > Is this a correct assessment? Not sure. The acid test is - can this be translated into a test case that clearly demonstrates non-expected behaviour? So, I'm not sure exactly what behavior is expected/correct, because I don't know all the use cases. It sounds like the person who originally opened this issue was expecting that unspecified values will always get their default value, but from my point of view that behavior is wrong, because then there is no way to indicate in an HTML form request that you want a value to be false when its default is true. (Does django-rest-framework allow partial-updates to be submitted using HTML forms? That would have the same problem of not being able to specify that a boolean should be false.) I found this solution on the internet to the problem of forms leaving out unchecked checkboxes: http://planetozh.com/blog/2008/09/posting-unchecked-checkboxes-in-html-forms/. But it's a frontend solution, which means it doesn't solve the problem if someone submits form data from some other frontend. In https://github.com/tomchristie/django-rest-framework/commit/90edcbf938ed8d6f3b783372c17e60bbf0761b61#diff-af402f515db75c7c6754453cf15455d9L431, does the data's being a QueryDict indicate that it definitely came from a form? Because if that is the case, then I think it _should_ be the way that it was before that commit, where unspecified means false. The main problem of this issue was not honouring default values specified in models when we run Django's test runner for partial update/create, which was apparently a bug so that had to be fixed. The behaviour of HTML form of Browsable API akenney mentioning seems to me that should be dealt in HTML form in some way instead of reverting the fix and bringing back the bug. I think im seeing another instance of this. The django test client and testing by hand using runserver (or any web interface) yields different results. EG. ``` class MyModel(models.Model): name = models.CharField(max_length=100) is_person = models.BooleanField(default=True) class MyModelViewSet(ModelViewSet): queryset = MyModel.objects.all() class MyModelSerializer(ModelSerializer): is_person = models.BooleanField(default=True) class Meta: model = MyModel class TestCase(TastCase): def test_example_problem(self): self.client.post( viewset_url, { 'name': 'nick' } ) model = MyModel.objects.all()[0] # This will fail. self.assertTrue(model.is_person) ``` That final test shouldn't fail, and doesn't testing using a web client. The response from the post has a 200 status. #1291 doesn't solve the problem, actually @tomwalker 's solution is targeting for the root cause (horouring model default value). I would suggest reopen PR #1248, get the test pass, and merge the fix. Anybody know how to run the rest_framework test? @caogecym it's explained in the documentation. See http://www.django-rest-framework.org/topics/contributing#testing This bug is happening again in version 3.0.1... :( Assuming same as #2280? Unfortunately it was not. I've updated DRF to version 3.0.2 today and tried it again but to no avail. default values defined in models such as default=True, default="text" are still ignored and tuned into False or ''. It can be reproduced with the test client and JSONRenderer. Retitling with what I think may be a more specific wording for the behavior you're seeing. Apologies for the slightly higher than usual churn rate, due to 3.0 just being released - pretty much all settled down now, but this is one of the few remaining outstanding issues. Fix in the meantime, add the following to the serializer to forcibly set the default values... ``` class Meta: extra_kwargs = {'my_field': {'default': True}} ``` @tomchristie Thanks for the swift reply. Yes, the temporal workaround did the trick. Issue here: When a model has a default we simply set `required=False` on the serializer field, and allow the model instance to use it's default when setting the value. Because empty text and boolean fields are coerced to an empty value by the serializer field that doesn't work. Answer is probably that `required=False` serializer fields always have `default_empty_html = empty`.
2014-12-18T10:37:19
encode/django-rest-framework
2,315
encode__django-rest-framework-2315
[ "2283" ]
1e531d20819442a739695df05edeb97f7ab5ef23
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 @@ -7,6 +7,7 @@ from django.utils.encoding import force_text from django.utils.functional import Promise from rest_framework.compat import OrderedDict +from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList import datetime import decimal import types @@ -107,14 +108,14 @@ def represent_mapping(self, tag, mapping, flow_style=None): OrderedDict, yaml.representer.SafeRepresenter.represent_dict ) - # SafeDumper.add_representer( - # DictWithMetadata, - # yaml.representer.SafeRepresenter.represent_dict - # ) - # SafeDumper.add_representer( - # OrderedDictWithMetadata, - # yaml.representer.SafeRepresenter.represent_dict - # ) + SafeDumper.add_representer( + ReturnDict, + yaml.representer.SafeRepresenter.represent_dict + ) + SafeDumper.add_representer( + ReturnList, + yaml.representer.SafeRepresenter.represent_list + ) SafeDumper.add_representer( types.GeneratorType, yaml.representer.SafeRepresenter.represent_list
YAMLRenderer - RepresenterError : cannot represent an object: ReturnDict Tested with django-rest-framework 3.0 dd712a1c2620b5dc9ad8eef5ff78ef232feb12e8 under python 3.4 and with a recent django (1.8+) ``` Environment: Request Method: GET Request URL: http://192.168.56.101/fr/api/v1/media/5604d858-f592-4338-aaa3-73293364c8db?format=yaml Django Version: 1.8.dev20141120151358 Python Version: 3.4.0 Installed Applications: ['django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', ... 'rest_framework', 'debug_toolbar', 'template_timings_panel'] Installed Middleware: ['debug_toolbar.middleware.DebugToolbarMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'project.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/var/project/prod/venv/src/django/django/core/handlers/base.py" in get_response 157. response = response.render() File "/var/project/prod/venv/src/django/django/template/response.py" in render 104. self.content = self.rendered_content File "/var/project/prod/venv/src/django-rest-framework/rest_framework/response.py" in rendered_content 59. ret = renderer.render(self.data, media_type, context) File "/var/project/prod/venv/src/django-rest-framework/rest_framework/renderers.py" in render 218. return yaml.dump(data, stream=None, encoding=self.charset, Dumper=self.encoder, allow_unicode=not self.ensure_ascii) File "/usr/local/lib/python3.4/dist-packages/yaml/__init__.py" in dump 200. return dump_all([data], stream, Dumper=Dumper, **kwds) File "/usr/local/lib/python3.4/dist-packages/yaml/__init__.py" in dump_all 188. dumper.represent(data) File "/usr/local/lib/python3.4/dist-packages/yaml/representer.py" in represent 26. node = self.represent_data(data) File "/usr/local/lib/python3.4/dist-packages/yaml/representer.py" in represent_data 57. node = self.yaml_representers[None](self, data) File "/usr/local/lib/python3.4/dist-packages/yaml/representer.py" in represent_undefined 227. raise RepresenterError("cannot represent an object: %s" % data) Exception Type: RepresenterError at /fr/api/v1/media/5604d858-f592-4338-aaa3-73293364c8db Exception Value: cannot represent an object: ReturnDict([('api_url', 'http://192.168.56.101/fr/api/v1/media/5604d858-f592-4338-aaa3-73293364c8db'), ('uuid', '5604d858-f592-4338-aaa3-73293364c8db'), ('title', 'Divergent 1080p (transcoded)'), ('file', 'http://192.168.56.101/protected/media/5604d858-f592-4338-aaa3-73293364c8db/Divergent%201080p%2000%3A02%3A40-00%3A03%3A40%20transcoded.mkv'), ('url', None), ('md5_checksum', None), ('metadatas', None), ('keyword_set', []), ('state', 'BROKEN'), ('parent', 'http://192.168.56.101/fr/api/v1/media/5ff1ba6f-c7c5-45ff-ae28-29b3621b5d98'), ('created_by', 2), ('created_at', '2014-12-11T08:30:45.052558Z'), ('updated_at', '2014-12-11T08:30:45.254961Z'), ('infos', None), ('is_upload', False), ('meta', OrderedDict([('duration', '0:00:00'), ('framerate', 0.0), ('interlaced', None), ('size', 0), ('width', 0), ('height', 0), ('content_width', 0), ('content_height', 0), ('content_x', 0), ('content_y', 0)]))]) ```
I think we need some more information here. Can you share some code? Was this also happening from the latest released version in PyPI? Verified. Run the quickstart and add `rest_framework.renderers.YAMLRenderer` to your `REST_FRAMEWORK` settings dict.
2014-12-18T12:18:44
encode/django-rest-framework
2,322
encode__django-rest-framework-2322
[ "2287" ]
435aef77384759d5a29129cdb0cbe47b3de6df93
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -327,7 +327,9 @@ def get_validators(self): Returns a list of validator callables. """ # Used by the lazily-evaluated `validators` property. - return getattr(getattr(self, 'Meta', None), 'validators', []) + meta = getattr(self, 'Meta', None) + validators = getattr(meta, 'validators', None) + return validators[:] if validators else [] def get_initial(self): if hasattr(self, 'initial_data'): @@ -696,7 +698,7 @@ class ModelSerializer(Serializer): you need you should either declare the extra/differing fields explicitly on the serializer class, or simply use a `Serializer` class. """ - _field_mapping = ClassLookupDict({ + serializer_field_mapping = { models.AutoField: IntegerField, models.BigIntegerField: IntegerField, models.BooleanField: BooleanField, @@ -719,8 +721,10 @@ class ModelSerializer(Serializer): models.TextField: CharField, models.TimeField: TimeField, models.URLField: URLField, - }) - _related_class = PrimaryKeyRelatedField + } + serializer_related_class = PrimaryKeyRelatedField + + # Default `create` and `update` behavior... def create(self, validated_data): """ @@ -791,69 +795,81 @@ def update(self, instance, validated_data): return instance - def get_validators(self): - # If the validators have been declared explicitly then use that. - validators = getattr(getattr(self, 'Meta', None), 'validators', None) - if validators is not None: - return validators + # Determine the fields to apply... - # Determine the default set of validators. - validators = [] - model_class = self.Meta.model - field_names = set([ - field.source for field in self.fields.values() - if (field.source != '*') and ('.' not in field.source) - ]) + def get_fields(self): + """ + Return the dict of field names -> field instances that should be + used for `self.fields` when instantiating the serializer. + """ + assert hasattr(self, 'Meta'), ( + 'Class {serializer_class} missing "Meta" attribute'.format( + serializer_class=self.__class__.__name__ + ) + ) + assert hasattr(self.Meta, 'model'), ( + 'Class {serializer_class} missing "Meta.model" attribute'.format( + serializer_class=self.__class__.__name__ + ) + ) - # Note that we make sure to check `unique_together` both on the - # base model class, but also on any parent classes. - for parent_class in [model_class] + list(model_class._meta.parents.keys()): - for unique_together in parent_class._meta.unique_together: - if field_names.issuperset(set(unique_together)): - validator = UniqueTogetherValidator( - queryset=parent_class._default_manager, - fields=unique_together - ) - validators.append(validator) + declared_fields = copy.deepcopy(self._declared_fields) + model = getattr(self.Meta, 'model') + depth = getattr(self.Meta, 'depth', 0) - # Add any unique_for_date/unique_for_month/unique_for_year constraints. - info = model_meta.get_field_info(model_class) - for field_name, field in info.fields_and_pk.items(): - if field.unique_for_date and field_name in field_names: - validator = UniqueForDateValidator( - queryset=model_class._default_manager, - field=field_name, - date_field=field.unique_for_date - ) - validators.append(validator) + if depth is not None: + assert depth >= 0, "'depth' may not be negative." + assert depth <= 10, "'depth' may not be greater than 10." - if field.unique_for_month and field_name in field_names: - validator = UniqueForMonthValidator( - queryset=model_class._default_manager, - field=field_name, - date_field=field.unique_for_month - ) - validators.append(validator) + # Retrieve metadata about fields & relationships on the model class. + info = model_meta.get_field_info(model) + field_names = self.get_field_names(declared_fields, info) - if field.unique_for_year and field_name in field_names: - validator = UniqueForYearValidator( - queryset=model_class._default_manager, - field=field_name, - date_field=field.unique_for_year - ) - validators.append(validator) + # Determine any extra field arguments and hidden fields that + # should be included + extra_kwargs = self.get_extra_kwargs() + extra_kwargs, hidden_fields = self.get_uniqueness_extra_kwargs( + field_names, declared_fields, extra_kwargs + ) - return validators + # Determine the fields that should be included on the serializer. + fields = OrderedDict() - def get_fields(self): - declared_fields = copy.deepcopy(self._declared_fields) + for field_name in field_names: + # If the field is explicitly declared on the class then use that. + if field_name in declared_fields: + fields[field_name] = declared_fields[field_name] + continue - ret = OrderedDict() - model = getattr(self.Meta, 'model') + # Determine the serializer field class and keyword arguments. + field_class, field_kwargs = self.build_field( + field_name, info, model, depth + ) + + # Include any kwargs defined in `Meta.extra_kwargs` + field_kwargs = self.build_field_kwargs( + field_kwargs, extra_kwargs, field_name + ) + + # Create the serializer field. + fields[field_name] = field_class(**field_kwargs) + + # Add in any hidden fields. + fields.update(hidden_fields) + + return fields + + # Methods for determining the set of field names to include... + + def get_field_names(self, declared_fields, info): + """ + Returns the list of all field names that should be created when + instantiating this serializer class. This is based on the default + set of fields, but also takes into account the `Meta.fields` or + `Meta.exclude` options if they have been specified. + """ fields = getattr(self.Meta, 'fields', None) exclude = getattr(self.Meta, 'exclude', None) - depth = getattr(self.Meta, 'depth', 0) - extra_kwargs = getattr(self.Meta, 'extra_kwargs', {}) if fields and not isinstance(fields, (list, tuple)): raise TypeError( @@ -867,192 +883,191 @@ def get_fields(self): type(exclude).__name__ ) - assert not (fields and exclude), "Cannot set both 'fields' and 'exclude'." + assert not (fields and exclude), ( + "Cannot set both 'fields' and 'exclude' options on " + "serializer {serializer_class}.".format( + serializer_class=self.__class__.__name__ + ) + ) - extra_kwargs = self._include_additional_options(extra_kwargs) + if fields is not None: + # Ensure that all declared fields have also been included in the + # `Meta.fields` option. + for field_name in declared_fields: + assert field_name in fields, ( + "The field '{field_name}' was declared on serializer " + "{serializer_class}, but has not been included in the " + "'fields' option.".format( + field_name=field_name, + serializer_class=self.__class__.__name__ + ) + ) + return fields + + # Use the default set of field names if `Meta.fields` is not specified. + fields = self.get_default_field_names(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 in fields, ( + "The field '{field_name}' was include on serializer " + "{serializer_class} in the 'exclude' option, but does " + "not match any model field.".format( + field_name=field_name, + serializer_class=self.__class__.__name__ + ) + ) + fields.remove(field_name) - # Retrieve metadata about fields & relationships on the model class. - info = model_meta.get_field_info(model) + return fields - # Use the default set of field names if none is supplied explicitly. - if fields is None: - fields = self._get_default_field_names(declared_fields, info) - exclude = getattr(self.Meta, 'exclude', None) - if exclude is not None: - for field_name in exclude: - assert field_name in fields, ( - 'The field in the `exclude` option must be a model field. Got %s.' % - field_name - ) - fields.remove(field_name) + def get_default_field_names(self, declared_fields, model_info): + """ + Return the default list of field names that will be used if the + `Meta.fields` option is not specified. + """ + return ( + [model_info.pk.name] + + list(declared_fields.keys()) + + list(model_info.fields.keys()) + + list(model_info.forward_relations.keys()) + ) - # Determine the set of model fields, and the fields that they map to. - # We actually only need this to deal with the slightly awkward case - # of supporting `unique_for_date`/`unique_for_month`/`unique_for_year`. - model_field_mapping = {} - for field_name in fields: - if field_name in declared_fields: - field = declared_fields[field_name] - source = field.source or field_name + # Methods for constructing serializer fields... + + def build_field(self, field_name, info, model_class, nested_depth): + """ + Return a two tuple of (cls, kwargs) to build a serializer field with. + """ + if field_name in info.fields_and_pk: + model_field = info.fields_and_pk[field_name] + return self.build_standard_field(field_name, model_field) + + elif field_name in info.relations: + relation_info = info.relations[field_name] + if not nested_depth: + return self.build_relational_field(field_name, relation_info) else: - try: - source = extra_kwargs[field_name]['source'] - except KeyError: - source = field_name - # Model fields will always have a simple source mapping, - # they can't be nested attribute lookups. - if '.' not in source and source != '*': - model_field_mapping[source] = field_name + return self.build_nested_field(field_name, relation_info, nested_depth) - # Determine if we need any additional `HiddenField` or extra keyword - # arguments to deal with `unique_for` dates that are required to - # be in the input data in order to validate it. - hidden_fields = {} - unique_constraint_names = set() + elif hasattr(model_class, field_name): + return self.build_property_field(field_name, model_class) - for model_field_name, field_name in model_field_mapping.items(): - try: - model_field = model._meta.get_field(model_field_name) - except FieldDoesNotExist: - continue + elif field_name == api_settings.URL_FIELD_NAME: + return self.build_url_field(field_name, model_class) - # Include each of the `unique_for_*` field names. - unique_constraint_names |= set([ - model_field.unique_for_date, - model_field.unique_for_month, - model_field.unique_for_year - ]) + return self.build_unknown_field(field_name, model_class) - unique_constraint_names -= set([None]) + def build_standard_field(self, field_name, model_field): + """ + Create regular model fields. + """ + field_mapping = ClassLookupDict(self.serializer_field_mapping) + + field_class = field_mapping[model_field] + field_kwargs = get_field_kwargs(field_name, model_field) + + if 'choices' in field_kwargs: + # Fields with choices get coerced into `ChoiceField` + # instead of using their regular typed field. + field_class = ChoiceField + if not issubclass(field_class, ModelField): + # `model_field` is only valid for the fallback case of + # `ModelField`, which is used when no other typed field + # matched to the model field. + field_kwargs.pop('model_field', None) + if not issubclass(field_class, CharField) and not issubclass(field_class, ChoiceField): + # `allow_blank` is only valid for textual fields. + field_kwargs.pop('allow_blank', None) + + return field_class, field_kwargs + + def build_relational_field(self, field_name, relation_info): + """ + Create fields for forward and reverse relationships. + """ + field_class = self.serializer_related_class + field_kwargs = get_relation_kwargs(field_name, relation_info) - # Include each of the `unique_together` field names, - # so long as all the field names are included on the serializer. - for parent_class in [model] + list(model._meta.parents.keys()): - for unique_together_list in parent_class._meta.unique_together: - if set(fields).issuperset(set(unique_together_list)): - unique_constraint_names |= set(unique_together_list) + # `view_name` is only valid for hyperlinked relationships. + if not issubclass(field_class, HyperlinkedRelatedField): + field_kwargs.pop('view_name', None) - # Now we have all the field names that have uniqueness constraints - # applied, we can add the extra 'required=...' or 'default=...' - # arguments that are appropriate to these fields, or add a `HiddenField` for it. - for unique_constraint_name in unique_constraint_names: - # Get the model field that is referred too. - unique_constraint_field = model._meta.get_field(unique_constraint_name) + return field_class, field_kwargs - if getattr(unique_constraint_field, 'auto_now_add', None): - default = CreateOnlyDefault(timezone.now) - elif getattr(unique_constraint_field, 'auto_now', None): - default = timezone.now - elif unique_constraint_field.has_default(): - default = unique_constraint_field.default - else: - default = empty + def build_nested_field(self, field_name, relation_info, nested_depth): + """ + Create nested fields for forward and reverse relationships. + """ + class NestedSerializer(ModelSerializer): + class Meta: + model = relation_info.related_model + depth = nested_depth - if unique_constraint_name in model_field_mapping: - # The corresponding field is present in the serializer - if unique_constraint_name not in extra_kwargs: - extra_kwargs[unique_constraint_name] = {} - if default is empty: - if 'required' not in extra_kwargs[unique_constraint_name]: - extra_kwargs[unique_constraint_name]['required'] = True - else: - if 'default' not in extra_kwargs[unique_constraint_name]: - extra_kwargs[unique_constraint_name]['default'] = default - elif default is not empty: - # The corresponding field is not present in the, - # serializer. We have a default to use for it, so - # add in a hidden field that populates it. - hidden_fields[unique_constraint_name] = HiddenField(default=default) + field_class = NestedSerializer + field_kwargs = get_nested_relation_kwargs(relation_info) - # Now determine the fields that should be included on the serializer. - for field_name in fields: - if field_name in declared_fields: - # Field is explicitly declared on the class, use that. - ret[field_name] = declared_fields[field_name] - continue + return field_class, field_kwargs - elif field_name in info.fields_and_pk: - # Create regular model fields. - model_field = info.fields_and_pk[field_name] - field_cls = self._field_mapping[model_field] - kwargs = get_field_kwargs(field_name, model_field) - if 'choices' in kwargs: - # Fields with choices get coerced into `ChoiceField` - # instead of using their regular typed field. - field_cls = ChoiceField - if not issubclass(field_cls, ModelField): - # `model_field` is only valid for the fallback case of - # `ModelField`, which is used when no other typed field - # matched to the model field. - kwargs.pop('model_field', None) - if not issubclass(field_cls, CharField) and not issubclass(field_cls, ChoiceField): - # `allow_blank` is only valid for textual fields. - kwargs.pop('allow_blank', None) - - elif field_name in info.relations: - # Create forward and reverse relationships. - relation_info = info.relations[field_name] - if depth: - field_cls = self._get_nested_class(depth, relation_info) - kwargs = get_nested_relation_kwargs(relation_info) - else: - field_cls = self._related_class - kwargs = get_relation_kwargs(field_name, relation_info) - # `view_name` is only valid for hyperlinked relationships. - if not issubclass(field_cls, HyperlinkedRelatedField): - kwargs.pop('view_name', None) - - elif hasattr(model, field_name): - # Create a read only field for model methods and properties. - field_cls = ReadOnlyField - kwargs = {} - - elif field_name == api_settings.URL_FIELD_NAME: - # Create the URL field. - field_cls = HyperlinkedIdentityField - kwargs = get_url_kwargs(model) + def build_property_field(self, field_name, model_class): + """ + Create a read only field for model methods and properties. + """ + field_class = ReadOnlyField + field_kwargs = {} - else: - raise ImproperlyConfigured( - 'Field name `%s` is not valid for model `%s`.' % - (field_name, model.__class__.__name__) - ) + return field_class, field_kwargs - # Check that any fields declared on the class are - # also explicitly included in `Meta.fields`. - missing_fields = set(declared_fields.keys()) - set(fields) - if missing_fields: - missing_field = list(missing_fields)[0] - raise ImproperlyConfigured( - 'Field `%s` has been declared on serializer `%s`, but ' - 'is missing from `Meta.fields`.' % - (missing_field, self.__class__.__name__) - ) + def build_url_field(self, field_name, model_class): + """ + Create a field representing the object's own URL. + """ + field_class = HyperlinkedIdentityField + field_kwargs = get_url_kwargs(model_class) - # Populate any kwargs defined in `Meta.extra_kwargs` - extras = extra_kwargs.get(field_name, {}) - if extras.get('read_only', False): - for attr in [ - 'required', 'default', 'allow_blank', 'allow_null', - 'min_length', 'max_length', 'min_value', 'max_value', - 'validators', 'queryset' - ]: - kwargs.pop(attr, None) + return field_class, field_kwargs - if extras.get('default') and kwargs.get('required') is False: - kwargs.pop('required') + def build_unknown_field(self, field_name, model_class): + """ + Raise an error on any unknown fields. + """ + raise ImproperlyConfigured( + 'Field name `%s` is not valid for model `%s`.' % + (field_name, model_class.__name__) + ) + + def build_field_kwargs(self, kwargs, extra_kwargs, field_name): + """ + Include an 'extra_kwargs' that have been included for this field, + possibly removing any incompatible existing keyword arguments. + """ + extras = extra_kwargs.get(field_name, {}) - kwargs.update(extras) + if extras.get('read_only', False): + for attr in [ + 'required', 'default', 'allow_blank', 'allow_null', + 'min_length', 'max_length', 'min_value', 'max_value', + 'validators', 'queryset' + ]: + kwargs.pop(attr, None) - # Create the serializer field. - ret[field_name] = field_cls(**kwargs) + if extras.get('default') and kwargs.get('required') is False: + kwargs.pop('required') - for field_name, field in hidden_fields.items(): - ret[field_name] = field + kwargs.update(extras) - return ret + return kwargs + + # Methods for determining additional keyword arguments to apply... + + def get_extra_kwargs(self): + """ + Return a dictionary mapping field names to a dictionary of + additional keyword arguments. + """ + extra_kwargs = getattr(self.Meta, 'extra_kwargs', {}) - def _include_additional_options(self, extra_kwargs): read_only_fields = getattr(self.Meta, 'read_only_fields', None) if read_only_fields is not None: for field_name in read_only_fields: @@ -1100,21 +1115,202 @@ def _include_additional_options(self, extra_kwargs): return extra_kwargs - def _get_default_field_names(self, declared_fields, model_info): + def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs): + """ + Return any additional field options that need to be included as a + result of uniqueness constraints on the model. This is returned as + a two-tuple of: + + ('dict of updated extra kwargs', 'mapping of hidden fields') + """ + model = getattr(self.Meta, 'model') + model_fields = self._get_model_fields( + field_names, declared_fields, extra_kwargs + ) + + # Determine if we need any additional `HiddenField` or extra keyword + # arguments to deal with `unique_for` dates that are required to + # be in the input data in order to validate it. + unique_constraint_names = set() + + for model_field in model_fields.values(): + # Include each of the `unique_for_*` field names. + unique_constraint_names |= set([ + model_field.unique_for_date, + model_field.unique_for_month, + model_field.unique_for_year + ]) + + unique_constraint_names -= set([None]) + + # Include each of the `unique_together` field names, + # so long as all the field names are included on the serializer. + for parent_class in [model] + list(model._meta.parents.keys()): + for unique_together_list in parent_class._meta.unique_together: + if set(field_names).issuperset(set(unique_together_list)): + unique_constraint_names |= set(unique_together_list) + + # Now we have all the field names that have uniqueness constraints + # applied, we can add the extra 'required=...' or 'default=...' + # arguments that are appropriate to these fields, or add a `HiddenField` for it. + hidden_fields = {} + uniqueness_extra_kwargs = {} + + for unique_constraint_name in unique_constraint_names: + # Get the model field that is referred too. + unique_constraint_field = model._meta.get_field(unique_constraint_name) + + if getattr(unique_constraint_field, 'auto_now_add', None): + default = CreateOnlyDefault(timezone.now) + elif getattr(unique_constraint_field, 'auto_now', None): + default = timezone.now + elif unique_constraint_field.has_default(): + default = unique_constraint_field.default + else: + default = empty + + if unique_constraint_name in model_fields: + # The corresponding field is present in the serializer + if default is empty: + uniqueness_extra_kwargs[unique_constraint_name] = {'required': True} + else: + uniqueness_extra_kwargs[unique_constraint_name] = {'default': default} + elif default is not empty: + # The corresponding field is not present in the, + # serializer. We have a default to use for it, so + # add in a hidden field that populates it. + hidden_fields[unique_constraint_name] = HiddenField(default=default) + + # 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 + + return extra_kwargs, hidden_fields + + def _get_model_fields(self, field_names, declared_fields, extra_kwargs): + """ + Returns all the model fields that are being mapped to by fields + on the serializer class. + Returned as a dict of 'model field name' -> 'model field'. + Used internally by `get_uniqueness_field_options`. + """ + model = getattr(self.Meta, 'model') + model_fields = {} + + for field_name in field_names: + if field_name in declared_fields: + # If the field is declared on the serializer + field = declared_fields[field_name] + source = field.source or field_name + else: + try: + source = extra_kwargs[field_name]['source'] + except KeyError: + source = field_name + + if '.' in source or source == '*': + # Model fields will always have a simple source mapping, + # they can't be nested attribute lookups. + continue + + try: + model_fields[source] = model._meta.get_field(source) + except FieldDoesNotExist: + pass + + return model_fields + + # Determine the validators to apply... + + def get_validators(self): + """ + Determine the set of validators to use when instantiating serializer. + """ + # If the validators have been declared explicitly then use that. + validators = getattr(getattr(self, 'Meta', None), 'validators', None) + if validators is not None: + return validators[:] + + # Otherwise use the default set of validators. return ( - [model_info.pk.name] + - list(declared_fields.keys()) + - list(model_info.fields.keys()) + - list(model_info.forward_relations.keys()) + self.get_unique_together_validators() + + self.get_unique_for_date_validators() ) - def _get_nested_class(self, nested_depth, relation_info): - class NestedSerializer(ModelSerializer): - class Meta: - model = relation_info.related - depth = nested_depth + def get_unique_together_validators(self): + """ + Determine a default set of validators for any unique_together contraints. + """ + model_class_inheritance_tree = ( + [self.Meta.model] + + list(self.Meta.model._meta.parents.keys()) + ) - return NestedSerializer + # The field names we're passing though here only include fields + # which may map onto a model field. Any dotted field name lookups + # cannot map to a field, and must be a traversal, so we're not + # including those. + field_names = set([ + field.source for field in self.fields.values() + if (field.source != '*') and ('.' not in field.source) + ]) + + # Note that we make sure to check `unique_together` both on the + # base model class, but also on any parent classes. + validators = [] + for parent_class in model_class_inheritance_tree: + for unique_together in parent_class._meta.unique_together: + if field_names.issuperset(set(unique_together)): + validator = UniqueTogetherValidator( + queryset=parent_class._default_manager, + fields=unique_together + ) + validators.append(validator) + return validators + + def get_unique_for_date_validators(self): + """ + Determine a default set of validators for the following contraints: + + * unique_for_date + * unique_for_month + * unique_for_year + """ + info = model_meta.get_field_info(self.Meta.model) + default_manager = self.Meta.model._default_manager + field_names = [field.source for field in self.fields.values()] + + validators = [] + + for field_name, field in info.fields_and_pk.items(): + if field.unique_for_date and field_name in field_names: + validator = UniqueForDateValidator( + queryset=default_manager, + field=field_name, + date_field=field.unique_for_date + ) + validators.append(validator) + + if field.unique_for_month and field_name in field_names: + validator = UniqueForMonthValidator( + queryset=default_manager, + field=field_name, + date_field=field.unique_for_month + ) + validators.append(validator) + + if field.unique_for_year and field_name in field_names: + validator = UniqueForYearValidator( + queryset=default_manager, + field=field_name, + date_field=field.unique_for_year + ) + validators.append(validator) + + return validators class HyperlinkedModelSerializer(ModelSerializer): @@ -1125,9 +1321,13 @@ class HyperlinkedModelSerializer(ModelSerializer): * A 'url' field is included instead of the 'id' field. * Relationships to other instances are hyperlinks, instead of primary keys. """ - _related_class = HyperlinkedRelatedField + serializer_related_class = HyperlinkedRelatedField - def _get_default_field_names(self, declared_fields, model_info): + def get_default_field_names(self, declared_fields, model_info): + """ + Return the default list of field names that will be used if the + `Meta.fields` option is not specified. + """ return ( [api_settings.URL_FIELD_NAME] + list(declared_fields.keys()) + @@ -1135,10 +1335,16 @@ def _get_default_field_names(self, declared_fields, model_info): list(model_info.forward_relations.keys()) ) - def _get_nested_class(self, nested_depth, relation_info): + def build_nested_field(self, field_name, relation_info, nested_depth): + """ + Create nested fields for forward and reverse relationships. + """ class NestedSerializer(HyperlinkedModelSerializer): class Meta: - model = relation_info.related - depth = nested_depth + model = relation_info.related_model + depth = nested_depth - 1 + + field_class = NestedSerializer + field_kwargs = get_nested_relation_kwargs(relation_info) - return NestedSerializer + return field_class, field_kwargs 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 @@ -24,7 +24,7 @@ RelationInfo = namedtuple('RelationInfo', [ 'model_field', - 'related', + 'related_model', 'to_many', 'has_through_model' ]) @@ -77,7 +77,7 @@ def get_field_info(model): for field in [field for field in opts.fields if field.serialize and field.rel]: forward_relations[field.name] = RelationInfo( model_field=field, - related=_resolve_model(field.rel.to), + related_model=_resolve_model(field.rel.to), to_many=False, has_through_model=False ) @@ -86,7 +86,7 @@ def get_field_info(model): for field in [field for field in opts.many_to_many if field.serialize]: forward_relations[field.name] = RelationInfo( model_field=field, - related=_resolve_model(field.rel.to), + related_model=_resolve_model(field.rel.to), to_many=True, has_through_model=( not field.rel.through._meta.auto_created @@ -99,7 +99,7 @@ def get_field_info(model): accessor_name = relation.get_accessor_name() reverse_relations[accessor_name] = RelationInfo( model_field=None, - related=relation.model, + related_model=relation.model, to_many=relation.field.rel.multiple, has_through_model=False ) @@ -109,7 +109,7 @@ def get_field_info(model): accessor_name = relation.get_accessor_name() reverse_relations[accessor_name] = RelationInfo( model_field=None, - related=relation.model, + related_model=relation.model, to_many=True, has_through_model=( (getattr(relation.field.rel, 'through', None) is not None)
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 @@ -206,7 +206,7 @@ class Meta: with self.assertRaises(ImproperlyConfigured) as excinfo: TestSerializer().fields - expected = 'Field name `invalid` is not valid for model `ModelBase`.' + expected = 'Field name `invalid` is not valid for model `RegularFieldsModel`.' assert str(excinfo.exception) == expected def test_missing_field(self): @@ -221,11 +221,11 @@ class Meta: model = RegularFieldsModel fields = ('auto_field',) - with self.assertRaises(ImproperlyConfigured) as excinfo: + with self.assertRaises(AssertionError) as excinfo: TestSerializer().fields expected = ( - 'Field `missing` has been declared on serializer ' - '`TestSerializer`, but is missing from `Meta.fields`.' + "The field 'missing' was declared on serializer TestSerializer, " + "but has not been included in the 'fields' option." ) assert str(excinfo.exception) == expected @@ -607,5 +607,5 @@ class Meta: exception = result.exception self.assertEqual( str(exception), - "Cannot set both 'fields' and 'exclude'." + "Cannot set both 'fields' and 'exclude' options on serializer ExampleSerializer." )
Metaclass attribute depth ignores fields attribute Hello ! I'm having some trouble using nested serialization with drf 3.0.1: I found out that the depth argument ignores what is set in the fields argument and if I remove it, I can't have any nested serialization. I'm a bit stuck at this point, if I remove it I lose the nested serialization but if I let it, it will put everything it encounters in the nested until throwing errors like `AssertionError: May not set both 'read_only' and 'required'`. Here's my code : ``` #models.py class Profile(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=80) avatar = models.ImageField(storage=protected_media, upload_to=to_user_dir) class Adventure(models.Model): name = models.CharField(max_length=50) user_profile = models.ForeignKey(Profile) #serializers.py class ProfileSerializer(serializers.HyperlinkedModelSerializer): avatar = serializers.ImageField(max_length=None, allow_empty_file=False) class Meta: model = Profile fields = ("url", "avatar", "name") #user field is not present class NestedAdventureSerializer(serializers.HyperlinkedModelSerializer): levels = NestedLevelSerializer(source="level_set"), #some uninteresting serializer nested_url = serializers.HyperlinkedIdentityField(view_name='nested_adventure-detail') url = serializers.HyperlinkedIdentityField(view_name='adventure-detail') class Meta: model = Adventure fields = ("url", "nested_url", "name", "level_set") #user_profile field is not present depth = 2 ``` Here's what I get when I print a NestedAdventureSerializer's instance: ``` NestedSerializer(read_only=True, required=True): url = HyperlinkedIdentityField(view_name='contenttype-detail') name = CharField(max_length=100) app_label = CharField(max_length=100, required=True) model = CharField(label='Python model class name', max_length=100, required=True) class Meta: validators = [<UniqueTogetherValidator(queryset=ContentType.objects.all(), fields=(u'app_label', u'model'))>] None NestedSerializer(read_only=True, required=True): url = HyperlinkedIdentityField(view_name='contenttype-detail') name = CharField(max_length=100) app_label = CharField(max_length=100, required=True) model = CharField(label='Python model class name', max_length=100, required=True) class Meta: validators = [<UniqueTogetherValidator(queryset=ContentType.objects.all(), fields=(u'app_label', u'model'))>] None NestedSerializer(read_only=True, required=True): url = HyperlinkedIdentityField(view_name='adventure-detail') name = CharField(max_length=50) user_profile = NestedSerializer(read_only=True): url = HyperlinkedIdentityField(view_name='profile-detail') name = CharField(max_length=80) avatar = ImageField(max_length=100) user = NestedSerializer(read_only=True): # and it goes on with django's User model until throwing assertions NestedAdventureSerializer(): url = HyperlinkedIdentityField(view_name='adventure-detail') nested_url = HyperlinkedIdentityField(view_name='nested_adventure-detail') name = CharField(max_length=50) level_set = ListSerializer(child=NestedSerializer(read_only=True):, read_only=True) ``` Thank you in advance for your help !
Hi @PhilipGarnero, thanks for raising the issue. I'm going to be slightly unhelpful at this point and close the issue because it's not sufficiently broken down into an easily actionable ticket - there's simply too much stuff there that's specific to your application and I can't really see what I'm supposed to be looking at. What I'd suggest is that you break this down to the _simplest_ possible case that you can find that demonstrates the issue your seeing. (Eg. a couple of models each with one or two fields.) That process will help nail down if it's actually a bug requiring action, or a usage issue. Once you've got a simple reviewable example I'd be very happy to reopen the ticket and give it further consideration. Apologies for not being more help at this point, but we do need to see tickets presented in a way that makes it easy for us to assess if they are valid issues or not. Thanks for your understanding.
2014-12-19T12:28:58
encode/django-rest-framework
2,331
encode__django-rest-framework-2331
[ "2327" ]
d109ae0a2e78551977d93e2507267e43a685fafd
diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -68,7 +68,12 @@ def __init__(self, *args, **kwargs): except AttributeError: object_serializer = DefaultObjectSerializer - self.fields[results_field] = serializers.ListSerializer( + try: + list_serializer_class = object_serializer.Meta.list_serializer_class + except AttributeError: + list_serializer_class = serializers.ListSerializer + + self.fields[results_field] = list_serializer_class( child=object_serializer(), source='object_list' )
PaginationSerializer hardcoded to use ListSerializer To me it feels like it should use Meta.list_serializer_class of the object serializer if it is defined instead. ``` patch diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index fb45128..94c2f2d 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -68,7 +68,12 @@ class BasePaginationSerializer(serializers.Serializer): except AttributeError: object_serializer = DefaultObjectSerializer - self.fields[results_field] = serializers.ListSerializer( + try: + list_serializer = object_serializer.Meta.list_serializer_class + except AttributeError: + list_serializer = serializers.ListSerializer + + self.fields[results_field] = list_serializer( child=object_serializer(), source='object_list' ) ```
Improvements to the pagination API will come in 3.1. Tracking against https://github.com/tomchristie/django-rest-framework/issues/1169 Actually this could still be valid in the meantime. It seems to solve my immediate problem anyway.
2014-12-20T16:33:04
encode/django-rest-framework
2,448
encode__django-rest-framework-2448
[ "2432" ]
4201c9fb01beae84fc34a5b74e138e721de42de1
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -23,6 +23,7 @@ import decimal import inspect import re +import uuid class empty: @@ -632,6 +633,23 @@ def __init__(self, **kwargs): self.validators.append(validator) +class UUIDField(Field): + default_error_messages = { + 'invalid': _('"{value}" is not a valid UUID.'), + } + + def to_internal_value(self, data): + if not isinstance(data, uuid.UUID): + try: + return uuid.UUID(data) + except (ValueError, TypeError): + self.fail('invalid', value=data) + return data + + def to_representation(self, value): + return str(value) + + # Number types... class IntegerField(Field): diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -702,6 +702,7 @@ class ModelSerializer(Serializer): you need you should either declare the extra/differing fields explicitly on the serializer class, or simply use a `Serializer` class. """ + _field_mapping = ClassLookupDict({ models.AutoField: IntegerField, models.BigIntegerField: IntegerField, @@ -724,7 +725,8 @@ class ModelSerializer(Serializer): models.SmallIntegerField: IntegerField, models.TextField: CharField, models.TimeField: TimeField, - models.URLField: URLField, + models.URLField: URLField + # Note: Some version-specific mappings also defined below. }) _related_class = PrimaryKeyRelatedField @@ -1132,6 +1134,10 @@ class Meta: return NestedSerializer +if hasattr(models, 'UUIDField'): + ModelSerializer._field_mapping[models.UUIDField] = UUIDField + + class HyperlinkedModelSerializer(ModelSerializer): """ A type of `ModelSerializer` that uses hyperlinked relationships instead 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 @@ -38,6 +38,9 @@ def __getitem__(self, key): return self.mapping[cls] raise KeyError('Class %s not found in lookup.', cls.__name__) + def __setitem__(self, key, value): + self.mapping[key] = value + def needs_label(model_field, field_name): """
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -4,6 +4,7 @@ import datetime import django import pytest +import uuid # Tests for field keyword arguments and core functionality. @@ -467,6 +468,23 @@ class TestURLField(FieldValues): field = serializers.URLField() +class TestUUIDField(FieldValues): + """ + Valid and invalid values for `UUIDField`. + """ + valid_inputs = { + '825d7aeb-05a9-45b5-a5b7-05df87923cda': uuid.UUID('825d7aeb-05a9-45b5-a5b7-05df87923cda'), + '825d7aeb05a945b5a5b705df87923cda': uuid.UUID('825d7aeb-05a9-45b5-a5b7-05df87923cda') + } + invalid_inputs = { + '825d7aeb-05a9-45b5-a5b7': ['"825d7aeb-05a9-45b5-a5b7" is not a valid UUID.'] + } + outputs = { + uuid.UUID('825d7aeb-05a9-45b5-a5b7-05df87923cda'): '825d7aeb-05a9-45b5-a5b7-05df87923cda' + } + field = serializers.UUIDField() + + # Number types... class TestIntegerField(FieldValues):
Support 1.8's UUIDField As per comment here: https://github.com/tomchristie/django-rest-framework/issues/2426#issuecomment-70484022 Current str field would result in... ``` File "/Users/tomjaster/DevFolder/master/airyengine/airy/lib/rest_framework/utils/encoders.py", line 60, in default return super(JSONEncoder, self).default(obj) File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: UUID('335680b8-0f20-4e25-a0e2-3caa052a3e83') is not JSON serializable ``` We should validate UUID values, and handle str() of them in both the encoder, and in the serializer field.
2015-01-23T15:24:41
encode/django-rest-framework
2,451
encode__django-rest-framework-2451
[ "2106" ]
b07d931261c2e9f722fb2de63ab17f088142b6f1
diff --git a/rest_framework/compat.py b/rest_framework/compat.py --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -58,6 +58,13 @@ def total_seconds(timedelta): from django.http import HttpResponse as HttpResponseBase +# contrib.postgres only supported from 1.8 onwards. +try: + from django.contrib.postgres import fields as postgres_fields +except ImportError: + postgres_fields = None + + # request only provides `resolver_match` from 1.5 onwards. def get_resolver_match(request): try: diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1132,8 +1132,21 @@ def to_internal_value(self, data): # Composite field types... +class _UnvalidatedField(Field): + def __init__(self, *args, **kwargs): + super(_UnvalidatedField, self).__init__(*args, **kwargs) + self.allow_blank = True + self.allow_null = True + + def to_internal_value(self, data): + return data + + def to_representation(self, value): + return value + + class ListField(Field): - child = None + child = _UnvalidatedField() initial = [] default_error_messages = { 'not_a_list': _('Expected a list of items but got type `{input_type}`') @@ -1141,7 +1154,6 @@ class ListField(Field): def __init__(self, *args, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) - assert self.child is not None, '`child` is a required argument.' assert not inspect.isclass(self.child), '`child` has not been instantiated.' super(ListField, self).__init__(*args, **kwargs) self.child.bind(field_name='', parent=self) @@ -1170,6 +1182,49 @@ def to_representation(self, data): return [self.child.to_representation(item) for item in data] +class DictField(Field): + child = _UnvalidatedField() + initial = [] + default_error_messages = { + 'not_a_dict': _('Expected a dictionary of items but got type `{input_type}`') + } + + def __init__(self, *args, **kwargs): + self.child = kwargs.pop('child', copy.deepcopy(self.child)) + assert not inspect.isclass(self.child), '`child` has not been instantiated.' + super(DictField, self).__init__(*args, **kwargs) + self.child.bind(field_name='', parent=self) + + def get_value(self, dictionary): + # We override the default field access in order to support + # lists in HTML forms. + if html.is_html_input(dictionary): + return html.parse_html_list(dictionary, prefix=self.field_name) + return dictionary.get(self.field_name, empty) + + def to_internal_value(self, data): + """ + Dicts of native values <- Dicts of primitive datatypes. + """ + if html.is_html_input(data): + data = html.parse_html_dict(data) + if not isinstance(data, dict): + self.fail('not_a_dict', input_type=type(data).__name__) + return dict([ + (six.text_type(key), self.child.run_validation(value)) + for key, value in data.items() + ]) + + def to_representation(self, value): + """ + List of object instances -> List of dicts of primitive datatypes. + """ + return dict([ + (six.text_type(key), self.child.to_representation(val)) + for key, val in value.items() + ]) + + # Miscellaneous field types... class ReadOnlyField(Field): diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -14,7 +14,7 @@ from django.db import models from django.db.models.fields import FieldDoesNotExist, Field as DjangoField from django.utils.translation import ugettext_lazy as _ -from rest_framework.compat import unicode_to_repr +from rest_framework.compat import postgres_fields, unicode_to_repr from rest_framework.utils import model_meta from rest_framework.utils.field_mapping import ( get_url_kwargs, get_field_kwargs, @@ -1137,6 +1137,12 @@ class Meta: if hasattr(models, 'UUIDField'): ModelSerializer._field_mapping[models.UUIDField] = UUIDField +if postgres_fields: + class CharMappingField(DictField): + child = CharField() + + ModelSerializer._field_mapping[postgres_fields.HStoreField] = CharMappingField + class HyperlinkedModelSerializer(ModelSerializer): """
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1047,7 +1047,7 @@ class TestValidImageField(FieldValues): class TestListField(FieldValues): """ - Values for `ListField`. + Values for `ListField` with IntegerField as child. """ valid_inputs = [ ([1, 2, 3], [1, 2, 3]), @@ -1064,6 +1064,55 @@ class TestListField(FieldValues): field = serializers.ListField(child=serializers.IntegerField()) +class TestUnvalidatedListField(FieldValues): + """ + Values for `ListField` with no `child` argument. + """ + valid_inputs = [ + ([1, '2', True, [4, 5, 6]], [1, '2', True, [4, 5, 6]]), + ] + invalid_inputs = [ + ('not a list', ['Expected a list of items but got type `str`']), + ] + outputs = [ + ([1, '2', True, [4, 5, 6]], [1, '2', True, [4, 5, 6]]), + ] + field = serializers.ListField() + + +class TestDictField(FieldValues): + """ + Values for `ListField` 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.']), + ('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.DictField(child=serializers.CharField()) + + +class TestUnvalidatedDictField(FieldValues): + """ + Values for `ListField` with no `child` argument. + """ + valid_inputs = [ + ({'a': 1, 'b': [4, 5, 6], 1: 123}, {'a': 1, 'b': [4, 5, 6], '1': 123}), + ] + invalid_inputs = [ + ('not a dict', ['Expected a dictionary of items but got type `str`']), + ] + outputs = [ + ({'a': 1, 'b': [4, 5, 6]}, {'a': 1, 'b': [4, 5, 6]}), + ] + field = serializers.DictField() + + # Tests for FieldField. # ---------------------
Add DictField (Which should support 1.8's HStore field) We should include a `MappingField` or `DictField` and automatically map to this from Django 1.8's `HStoreField`.
2015-01-23T16:28:09
encode/django-rest-framework
2,456
encode__django-rest-framework-2456
[ "2455", "2455" ]
8f25c0c53c24c88afc86d99bbb3ca4edc3a4e0a2
diff --git a/rest_framework/request.py b/rest_framework/request.py --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -107,6 +107,8 @@ def clone_request(request, method): ret.accepted_renderer = request.accepted_renderer if hasattr(request, 'accepted_media_type'): ret.accepted_media_type = request.accepted_media_type + if hasattr(request, 'version'): + ret.version = request.version return ret
diff --git a/tests/browsable_api/auth_urls.py b/tests/browsable_api/auth_urls.py --- a/tests/browsable_api/auth_urls.py +++ b/tests/browsable_api/auth_urls.py @@ -3,6 +3,7 @@ from .views import MockView + urlpatterns = patterns( '', (r'^$', MockView.as_view()), diff --git a/tests/test_metadata.py b/tests/test_metadata.py --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -1,6 +1,7 @@ from __future__ import unicode_literals from rest_framework import exceptions, serializers, status, views from rest_framework.request import Request +from rest_framework.renderers import BrowsableAPIRenderer from rest_framework.test import APIRequestFactory request = Request(APIRequestFactory().options('/')) @@ -168,3 +169,17 @@ def get_object(self): response = view(request=request) assert response.status_code == status.HTTP_200_OK assert list(response.data['actions'].keys()) == ['POST'] + + def test_bug_2455_clone_request(self): + class ExampleView(views.APIView): + renderer_classes = (BrowsableAPIRenderer,) + + def post(self, request): + pass + + def get_serializer(self): + assert hasattr(self.request, 'version') + return serializers.Serializer() + + view = ExampleView.as_view() + view(request=request)
Checking for request.version raises AttributeError with BrowsableAPIRenderer I've encountered the following exception when using the Browsable API in conjunction with the new namespace versioning and HyperlinkedModelSerializers: ``` python AttributeError: 'WSGIRequest' object has no attribute 'version' ``` I've implemented `get_serializer_class()` as specified in the documentation: ``` python def get_serializer_class(self): if self.request.version == 'v1': return AccountSerializerVersion1 return AccountSerializer ``` I'm also using drf-nested-routers, and this is occurring on endpoints like /api/v1/car/1/tires/ where the Tire model has a ForeignKey to Car. This only happens on the Browsable API; I can perform a GET request to the same endpoint using the JSONRenderer without exceptions. Checking for request.version raises AttributeError with BrowsableAPIRenderer I've encountered the following exception when using the Browsable API in conjunction with the new namespace versioning and HyperlinkedModelSerializers: ``` python AttributeError: 'WSGIRequest' object has no attribute 'version' ``` I've implemented `get_serializer_class()` as specified in the documentation: ``` python def get_serializer_class(self): if self.request.version == 'v1': return AccountSerializerVersion1 return AccountSerializer ``` I'm also using drf-nested-routers, and this is occurring on endpoints like /api/v1/car/1/tires/ where the Tire model has a ForeignKey to Car. This only happens on the Browsable API; I can perform a GET request to the same endpoint using the JSONRenderer without exceptions.
2015-01-24T09:51:16
encode/django-rest-framework
2,473
encode__django-rest-framework-2473
[ "2466" ]
fc70c0862ff3e6183b79adc4675a63874261ddf0
diff --git a/rest_framework/settings.py b/rest_framework/settings.py --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -18,6 +18,7 @@ back to the defaults. """ from __future__ import unicode_literals +from django.test.signals import setting_changed from django.conf import settings from django.utils import importlib, six from rest_framework import ISO_8601 @@ -198,3 +199,13 @@ def __getattr__(self, attr): api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS) + + +def reload_api_settings(*args, **kwargs): + global api_settings + setting, value = kwargs['setting'], kwargs['value'] + if setting == 'REST_FRAMEWORK': + api_settings = APISettings(value, DEFAULTS, IMPORT_STRINGS) + + +setting_changed.connect(reload_api_settings)
diff --git a/tests/test_filters.py b/tests/test_filters.py --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -5,13 +5,15 @@ from django.conf.urls import patterns, url from django.core.urlresolvers import reverse from django.test import TestCase +from django.test.utils import override_settings from django.utils import unittest from django.utils.dateparse import parse_date +from django.utils.six.moves import reload_module from rest_framework import generics, serializers, status, filters from rest_framework.compat import django_filters from rest_framework.test import APIRequestFactory from .models import BaseFilterableItem, FilterableItem, BasicModel -from .utils import temporary_setting + factory = APIRequestFactory() @@ -404,7 +406,9 @@ class SearchListView(generics.ListAPIView): ) def test_search_with_nonstandard_search_param(self): - with temporary_setting('SEARCH_PARAM', 'query', module=filters): + with override_settings(REST_FRAMEWORK={'SEARCH_PARAM': 'query'}): + reload_module(filters) + class SearchListView(generics.ListAPIView): queryset = SearchFilterModel.objects.all() serializer_class = SearchFilterSerializer @@ -422,6 +426,8 @@ class SearchListView(generics.ListAPIView): ] ) + reload_module(filters) + class OrderingFilterModel(models.Model): title = models.CharField(max_length=20) @@ -642,7 +648,9 @@ class OrderingListView(generics.ListAPIView): ) def test_ordering_with_nonstandard_ordering_param(self): - with temporary_setting('ORDERING_PARAM', 'order', filters): + with override_settings(REST_FRAMEWORK={'ORDERING_PARAM': 'order'}): + reload_module(filters) + class OrderingListView(generics.ListAPIView): queryset = OrderingFilterModel.objects.all() serializer_class = OrderingFilterSerializer @@ -662,6 +670,8 @@ class OrderingListView(generics.ListAPIView): ] ) + reload_module(filters) + class SensitiveOrderingFilterModel(models.Model): username = models.CharField(max_length=20) diff --git a/tests/utils.py b/tests/utils.py --- a/tests/utils.py +++ b/tests/utils.py @@ -1,30 +1,5 @@ -from contextlib import contextmanager from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import NoReverseMatch -from django.utils import six -from rest_framework.settings import api_settings - - -@contextmanager -def temporary_setting(setting, value, module=None): - """ - Temporarily change value of setting for test. - - Optionally reload given module, useful when module uses value of setting on - import. - """ - original_value = getattr(api_settings, setting) - setattr(api_settings, setting, value) - - if module is not None: - six.moves.reload_module(module) - - yield - - setattr(api_settings, setting, original_value) - - if module is not None: - six.moves.reload_module(module) class MockObject(object):
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
2015-01-27T14:00:50
encode/django-rest-framework
2,478
encode__django-rest-framework-2478
[ "2477" ]
107198af943aadba686ceeac0976b09366983007
diff --git a/rest_framework/request.py b/rest_framework/request.py --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -109,6 +109,8 @@ def clone_request(request, method): ret.accepted_media_type = request.accepted_media_type if hasattr(request, 'version'): ret.version = request.version + if hasattr(request, 'versioning_scheme'): + ret.versioning_scheme = request.versioning_scheme return ret
diff --git a/tests/test_metadata.py b/tests/test_metadata.py --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -1,5 +1,5 @@ from __future__ import unicode_literals -from rest_framework import exceptions, serializers, status, views +from rest_framework import exceptions, serializers, status, views, versioning from rest_framework.request import Request from rest_framework.renderers import BrowsableAPIRenderer from rest_framework.test import APIRequestFactory @@ -183,3 +183,18 @@ def get_serializer(self): view = ExampleView.as_view() view(request=request) + + def test_bug_2477_clone_request(self): + class ExampleView(views.APIView): + renderer_classes = (BrowsableAPIRenderer,) + + def post(self, request): + pass + + def get_serializer(self): + assert hasattr(self.request, 'versioning_scheme') + return serializers.Serializer() + + scheme = versioning.QueryParameterVersioning + view = ExampleView.as_view(versioning_class=scheme) + view(request=request)
Browsable API can't resolve URLs for HyperlinkedRelatedFields when using versioning Very similar to #2455. When the Browsable API clones requests to check the permissions on other methods, it doesn't clone the `versioning_scheme` attribute and this causes reverse lookups to fail. ``` ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "aggregator-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. ```
2015-01-28T01:12:21
encode/django-rest-framework
2,505
encode__django-rest-framework-2505
[ "2489" ]
e63f49bd1d55501f766ca2e3f9c0c9fa3cfa19ab
diff --git a/rest_framework/relations.py b/rest_framework/relations.py --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -1,7 +1,7 @@ # coding: utf-8 from __future__ import unicode_literals from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured -from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch, Resolver404 +from django.core.urlresolvers import get_script_prefix, NoReverseMatch, Resolver404 from django.db.models.query import QuerySet from django.utils import six from django.utils.encoding import smart_text @@ -9,7 +9,7 @@ from django.utils.translation import ugettext_lazy as _ from rest_framework.compat import OrderedDict from rest_framework.fields import get_attribute, empty, Field -from rest_framework.reverse import reverse +from rest_framework.reverse import reverse, resolve from rest_framework.utils import html @@ -205,6 +205,7 @@ def get_url(self, obj, view_name, request, format): return self.reverse(view_name, kwargs=kwargs, request=request, format=format) def to_internal_value(self, data): + request = self.context.get('request', None) try: http_prefix = data.startswith(('http:', 'https:')) except AttributeError: @@ -218,7 +219,7 @@ def to_internal_value(self, data): data = '/' + data[len(prefix):] try: - match = self.resolve(data) + match = self.resolve(data, request=request) except Resolver404: self.fail('no_match') diff --git a/rest_framework/reverse.py b/rest_framework/reverse.py --- a/rest_framework/reverse.py +++ b/rest_framework/reverse.py @@ -1,12 +1,25 @@ """ -Provide reverse functions that return fully qualified URLs +Provide urlresolver functions that return fully qualified URLs or view names """ from __future__ import unicode_literals from django.core.urlresolvers import reverse as django_reverse +from django.core.urlresolvers import resolve as django_resolve from django.utils import six from django.utils.functional import lazy +def resolve(path, urlconf=None, request=None): + """ + If versioning is being used then we pass any `resolve` calls through + to the versioning scheme instance, so that the resulting view name + can be modified if needed. + """ + scheme = getattr(request, 'versioning_scheme', None) + if scheme is not None: + return scheme.resolve(path, urlconf, request) + return django_resolve(path, urlconf) + + def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra): """ If versioning is being used then we pass any `reverse` calls through diff --git a/rest_framework/versioning.py b/rest_framework/versioning.py --- a/rest_framework/versioning.py +++ b/rest_framework/versioning.py @@ -1,6 +1,8 @@ # coding: utf-8 from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ +from django.core.urlresolvers import resolve as django_resolve +from django.core.urlresolvers import ResolverMatch from rest_framework import exceptions from rest_framework.compat import unicode_http_header from rest_framework.reverse import _reverse @@ -24,6 +26,9 @@ def determine_version(self, request, *args, **kwargs): def reverse(self, viewname, args=None, kwargs=None, request=None, format=None, **extra): return _reverse(viewname, args, kwargs, request, format, **extra) + def resolve(self, path, urlconf=None): + return django_resolve(path, urlconf) + def is_allowed_version(self, version): if not self.allowed_versions: return True @@ -127,6 +132,17 @@ def reverse(self, viewname, args=None, kwargs=None, request=None, format=None, * viewname, args, kwargs, request, format, **extra ) + def resolve(self, path, urlconf=None, request=None): + match = django_resolve(path, urlconf) + if match.namespace: + _, view_name = match.view_name.split(':') + return ResolverMatch(func=match.func, + args=match.args, + kwargs=match.kwargs, + url_name=view_name, + app_name=match.app_name) + return match + class HostNameVersioning(BaseVersioning): """
diff --git a/tests/test_versioning.py b/tests/test_versioning.py --- a/tests/test_versioning.py +++ b/tests/test_versioning.py @@ -1,9 +1,13 @@ +from .utils import MockObject, MockQueryset from django.conf.urls import include, url +from django.core.exceptions import ObjectDoesNotExist +from rest_framework import serializers from rest_framework import status, versioning from rest_framework.decorators import APIView from rest_framework.response import Response from rest_framework.reverse import reverse -from rest_framework.test import APIRequestFactory, APITestCase +from rest_framework.test import APIRequestFactory, APITestCase, APISimpleTestCase +from rest_framework.versioning import NamespaceVersioning class RequestVersionView(APIView): @@ -29,15 +33,18 @@ def get(self, request, *args, **kwargs): factory = APIRequestFactory() mock_view = lambda request: None +dummy_view = lambda request, pk: None included_patterns = [ url(r'^namespaced/$', mock_view, name='another'), + url(r'^example/(?P<pk>\d+)/$', dummy_view, name='example-detail') ] urlpatterns = [ url(r'^v1/', include(included_patterns, namespace='v1')), url(r'^another/$', mock_view, name='another'), - url(r'^(?P<version>[^/]+)/another/$', mock_view, name='another') + url(r'^(?P<version>[^/]+)/another/$', mock_view, name='another'), + url(r'^example/(?P<pk>\d+)/$', dummy_view, name='example-detail') ] @@ -221,3 +228,33 @@ class FakeResolverMatch: request.resolver_match = FakeResolverMatch response = view(request, version='v3') assert response.status_code == status.HTTP_404_NOT_FOUND + + +class TestHyperlinkedRelatedField(APISimpleTestCase): + urls = 'tests.test_versioning' + + def setUp(self): + + class HyperlinkedMockQueryset(MockQueryset): + def get(self, **lookup): + for item in self.items: + if item.pk == int(lookup.get('pk', -1)): + return item + raise ObjectDoesNotExist() + + self.queryset = HyperlinkedMockQueryset([ + MockObject(pk=1, name='foo'), + MockObject(pk=2, name='bar'), + MockObject(pk=3, name='baz') + ]) + self.field = serializers.HyperlinkedRelatedField( + view_name='example-detail', + queryset=self.queryset + ) + request = factory.post('/', urlconf='tests.test_versioning') + request.versioning_scheme = NamespaceVersioning() + self.field._context = {'request': request} + + def test_bug_2489(self): + self.field.to_internal_value('/example/3/') + self.field.to_internal_value('/v1/example/3/')
Browsable API can't resolve URLs for HyperlinkedRelatedFields when using namespaced versioning My POST requests to a ModelViewSet using a HyperlinkedModelSerializer don't work due to `HyperlinkedRelatedField.to_internal_value()` failing with ``` python ValidationError: [u'Invalid hyperlink - Incorrect URL match.'] ``` This is using NamespaceVersioning, and the failure originates at [line 225](https://github.com/tomchristie/django-rest-framework/blob/version-3.1/rest_framework/relations.py#L225) of relations.py since `match.view_name = 'v1:snippet-detail'` but `self.view_name = 'snippet-detail'`. I have a failing unit test for this but can't decide how to best solve it. When we reverse URLs, if a versioning scheme is in place then the scheme's reverse function handles it (in particular, `NamespaceVersioning.reverse()` adds on the version to the view name). Is there a way to get at the request from the HyperlinkedRelatedField? If I can get pointed in the right direction then I'll make up a pull request for this. Thanks!
2015-02-03T04:45:57
encode/django-rest-framework
2,530
encode__django-rest-framework-2530
[ "2108" ]
235b98e427e2bae2b52fb386a42c8045724de251
diff --git a/rest_framework/request.py b/rest_framework/request.py --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -12,12 +12,13 @@ from django.conf import settings from django.http import QueryDict from django.http.multipartparser import parse_header +from django.utils import six from django.utils.datastructures import MultiValueDict from django.utils.datastructures import MergeDict as DjangoMergeDict -from django.utils.six import BytesIO from rest_framework import HTTP_HEADER_ENCODING from rest_framework import exceptions from rest_framework.settings import api_settings +import sys import warnings @@ -362,7 +363,7 @@ def _load_stream(self): elif hasattr(self._request, 'read'): self._stream = self._request else: - self._stream = BytesIO(self.raw_post_data) + self._stream = six.BytesIO(self.raw_post_data) def _perform_form_overloading(self): """ @@ -404,7 +405,7 @@ def _perform_form_overloading(self): self._CONTENTTYPE_PARAM in self._data ): self._content_type = self._data[self._CONTENTTYPE_PARAM] - self._stream = BytesIO(self._data[self._CONTENT_PARAM].encode(self.parser_context['encoding'])) + self._stream = six.BytesIO(self._data[self._CONTENT_PARAM].encode(self.parser_context['encoding'])) self._data, self._files, self._full_data = (Empty, Empty, Empty) def _parse(self): @@ -485,8 +486,16 @@ def _not_authenticated(self): else: self.auth = None - def __getattr__(self, attr): + def __getattribute__(self, attr): """ - Proxy other attributes to the underlying HttpRequest object. + If an attribute does not exist on this instance, then we also attempt + to proxy it to the underlying HttpRequest object. """ - return getattr(self._request, attr) + try: + return super(Request, self).__getattribute__(attr) + except AttributeError: + info = sys.exc_info() + try: + return getattr(self._request, attr) + except AttributeError: + six.reraise(info[0], info[1], info[2].tb_next) 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 @@ -154,7 +154,9 @@ def urlize_quoted_links(text, trim_url_limit=None, nofollow=True, autoescape=Tru If autoescape is True, the link text and URLs will get autoescaped. """ - trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x + def trim_url(x, limit=trim_url_limit): + return limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x + safe_input = isinstance(text, SafeData) words = word_split_re.split(force_text(text)) for i, word in enumerate(words):
diff --git a/tests/test_authentication.py b/tests/test_authentication.py --- a/tests/test_authentication.py +++ b/tests/test_authentication.py @@ -205,7 +205,10 @@ def test_post_json_passing_token_auth(self): def test_post_json_makes_one_db_query(self): """Ensure that authenticating a user using a token performs only one DB query""" auth = "Token " + self.key - func_to_test = lambda: self.csrf_client.post('/token/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth) + + def func_to_test(): + return self.csrf_client.post('/token/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth) + self.assertNumQueries(1, func_to_test) def test_post_form_failing_token_auth(self): diff --git a/tests/test_relations_hyperlink.py b/tests/test_relations_hyperlink.py --- a/tests/test_relations_hyperlink.py +++ b/tests/test_relations_hyperlink.py @@ -12,7 +12,9 @@ request = factory.get('/') # Just to ensure we have a request in the serializer context -dummy_view = lambda request, pk: None +def dummy_view(request, pk): + pass + urlpatterns = patterns( '', diff --git a/tests/test_renderers.py b/tests/test_renderers.py --- a/tests/test_renderers.py +++ b/tests/test_renderers.py @@ -28,8 +28,13 @@ DUMMYSTATUS = status.HTTP_200_OK DUMMYCONTENT = 'dummycontent' -RENDERER_A_SERIALIZER = lambda x: ('Renderer A: %s' % x).encode('ascii') -RENDERER_B_SERIALIZER = lambda x: ('Renderer B: %s' % x).encode('ascii') + +def RENDERER_A_SERIALIZER(x): + return ('Renderer A: %s' % x).encode('ascii') + + +def RENDERER_B_SERIALIZER(x): + return ('Renderer B: %s' % x).encode('ascii') expected_results = [ diff --git a/tests/test_request.py b/tests/test_request.py --- a/tests/test_request.py +++ b/tests/test_request.py @@ -249,9 +249,29 @@ def test_logged_in_user_is_set_on_wrapped_request(self): login(self.request, self.user) self.assertEqual(self.wrapped_request.user, self.user) + def test_calling_user_fails_when_attribute_error_is_raised(self): + """ + This proves that when an AttributeError is raised inside of the request.user + property, that we can handle this and report the true, underlying error. + """ + class AuthRaisesAttributeError(object): + def authenticate(self, request): + import rest_framework + rest_framework.MISSPELLED_NAME_THAT_DOESNT_EXIST -class TestAuthSetter(TestCase): + self.request = Request(factory.get('/'), authenticators=(AuthRaisesAttributeError(),)) + SessionMiddleware().process_request(self.request) + login(self.request, self.user) + try: + self.request.user + except AttributeError as error: + self.assertEqual(str(error), "'module' object has no attribute 'MISSPELLED_NAME_THAT_DOESNT_EXIST'") + else: + assert False, 'AttributeError not raised' + + +class TestAuthSetter(TestCase): def test_auth_can_be_set(self): request = Request(factory.get('/')) request.auth = 'DUMMY' diff --git a/tests/test_response.py b/tests/test_response.py --- a/tests/test_response.py +++ b/tests/test_response.py @@ -38,8 +38,13 @@ class MockTextMediaRenderer(BaseRenderer): DUMMYSTATUS = status.HTTP_200_OK DUMMYCONTENT = 'dummycontent' -RENDERER_A_SERIALIZER = lambda x: ('Renderer A: %s' % x).encode('ascii') -RENDERER_B_SERIALIZER = lambda x: ('Renderer B: %s' % x).encode('ascii') + +def RENDERER_A_SERIALIZER(x): + return ('Renderer A: %s' % x).encode('ascii') + + +def RENDERER_B_SERIALIZER(x): + return ('Renderer B: %s' % x).encode('ascii') class RendererA(BaseRenderer): diff --git a/tests/test_throttling.py b/tests/test_throttling.py --- a/tests/test_throttling.py +++ b/tests/test_throttling.py @@ -188,7 +188,9 @@ def setUp(self): class XYScopedRateThrottle(ScopedRateThrottle): TIMER_SECONDS = 0 THROTTLE_RATES = {'x': '3/min', 'y': '1/min'} - timer = lambda self: self.TIMER_SECONDS + + def timer(self): + return self.TIMER_SECONDS class XView(APIView): throttle_classes = (XYScopedRateThrottle,) @@ -290,7 +292,9 @@ def setUp(self): class Throttle(ScopedRateThrottle): THROTTLE_RATES = {'test_limit': '1/day'} TIMER_SECONDS = 0 - timer = lambda self: self.TIMER_SECONDS + + def timer(self): + return self.TIMER_SECONDS class View(APIView): throttle_classes = (Throttle,)
Usage of both @property and __getattr__ can lead to obscure and hard to debug errors Encountered this error when accessing request.DATA in a view: ``` python File "views.py", line 146, in put if request.DATA is not None: File "/usr/local/lib/python2.7/dist-packages/rest_framework/request.py", line 453, in __getattr__ return getattr(self._request, attr) AttributeError: 'WSGIRequest' object has no attribute 'DATA' ``` This was mind-boggling. I couldn't understand why `__getattr__` was ever called on the request object, since a property called DATA already exists (confirmed this via dir(request) before accessing DATA), and as we all know, getattr is only used for undefined properties. After an intense debugging session it turned out that this is caused by a "feature" in python. This may be common knowledge, but it definitely was new news to me: if a property getter raises an AttributeError, python (`__getattribute__`) falls back to using `__getattr__`. The issue is that the traceback is lost, which makes it extremely hard to debug, since the actual exception raised isn't shown anywhere. So, the **actual** error was: ``` AttributeError: 'TemporaryFileUploadHandler' object has no attribute 'file' ``` Further explanation/discussion: https://groups.google.com/forum/#!topic/comp.lang.python/BZf-d0rLP8U I'm not sure if this is an issue that you can/want to address, but I wanted to make people aware of it since it was a pain to track down and others might stumble into the same situation.
Assuming related to #1939. Not clear if something similar to #1938 would fix. Yes, definitely the same error. Pretty sure the same solution applied in #1938 would fix it. Probably needs fixing in all getters/setters in classes with custom properties and getattr defined. Another option might be to override `__getattribute__` instead of `__getattr__` and handle it there instead as that'd be more DRY. Any update on this issue? Not yet. Plenty of other things going on, but anyone's welcome to dig into this and come up with clear proposal/example pull request etc. Dang, I'm having the same problem but I can't trace it. One route someone to start on this would be to demonstrate the most minimal possible python example that demonstates the issue (ie forget about REST framework at all to start with) That'd give us a much better point to work towards a fix from, as it'd narrow things down to the core issue. ``` python class Test(object): @property def foo(self): # This will raise an AttributeError, after which # __getattr__ will be used as a fallback. return self.doesntexist def __getattr__(self, name): raise AttributeError('No attribute ' + name) t = Test() t.foo ``` The output will be ``` Traceback (most recent call last): File "2108.py", line 12, in <module> t.foo File "2108.py", line 9, in __getattr__ raise AttributeError('No attribute ' + name) AttributeError: No attribute foo ``` As you can see, the original exception and traceback is lost (from trying to access self.doesntexist).
2015-02-09T17:04:18
encode/django-rest-framework
2,535
encode__django-rest-framework-2535
[ "1488" ]
7b639c0cd0676172cc8502e833f5b708f39f9a83
diff --git a/rest_framework/filters.py b/rest_framework/filters.py --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -104,7 +104,7 @@ def filter_queryset(self, request, queryset, view): for search_term in self.get_search_terms(request): or_queries = [models.Q(**{orm_lookup: search_term}) for orm_lookup in orm_lookups] - queryset = queryset.filter(reduce(operator.or_, or_queries)) + queryset = queryset.filter(reduce(operator.or_, or_queries)).distinct() return queryset
diff --git a/tests/test_filters.py b/tests/test_filters.py --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -429,6 +429,56 @@ class SearchListView(generics.ListAPIView): reload_module(filters) +class AttributeModel(models.Model): + label = models.CharField(max_length=32) + + +class SearchFilterModelM2M(models.Model): + title = models.CharField(max_length=20) + text = models.CharField(max_length=100) + attributes = models.ManyToManyField(AttributeModel) + + +class SearchFilterM2MSerializer(serializers.ModelSerializer): + class Meta: + model = SearchFilterModelM2M + + +class SearchFilterM2MTests(TestCase): + def setUp(self): + # Sequence of title/text/attributes is: + # + # z abc [1, 2, 3] + # zz bcd [1, 2, 3] + # zzz cde [1, 2, 3] + # ... + for idx in range(3): + label = 'w' * (idx + 1) + AttributeModel(label=label) + + for idx in range(10): + title = 'z' * (idx + 1) + text = ( + chr(idx + ord('a')) + + chr(idx + ord('b')) + + chr(idx + ord('c')) + ) + SearchFilterModelM2M(title=title, text=text).save() + SearchFilterModelM2M.objects.get(title='zz').attributes.add(1, 2, 3) + + def test_m2m_search(self): + class SearchListView(generics.ListAPIView): + queryset = SearchFilterModelM2M.objects.all() + serializer_class = SearchFilterM2MSerializer + filter_backends = (filters.SearchFilter,) + search_fields = ('=title', 'text', 'attributes__label') + + view = SearchListView.as_view() + request = factory.get('/', {'search': 'zz'}) + response = view(request) + self.assertEqual(len(response.data), 1) + + class OrderingFilterModel(models.Model): title = models.CharField(max_length=20) text = models.CharField(max_length=100)
Duplicate results of `ManyToManyField` when using `SearchFilter`. I have two models: <pre> class Course(models.Model): name = models.CharField(max_length=255) class Teacher(models.Model): name = models.CharField(max_length=255) courses = models.ManyToManyField('schools.Course') </pre> The serializer are: <pre> class CourseSerializer(serializers.ModelSerializer): teacher_set = serializers.PrimaryKeyRelatedField(many=True) class Meta: model = Course class TeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher </pre> and the views for courses and teachers: <pre> class TeacherViewSet(ModelViewSet): serializer_class = TeacherSerializer queryset = Teacher.objects.all() filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('courses',) class CourseViewSet(StaffRequiredMixin, ModelViewSet): serializer_class = CourseSerializer queryset = Course.objects.all() </pre> After I create a course and a teacher, when I am adding the teacher to that course and do get list of teachers, it is returning me two exactly same teacher objects. I found that is because filter in the TeacherViewSet. If I remove filter, it is giving me correct result. I was using django-filter version 0.7. When I changed to django-filter version 0.5.4. It is working fine then. Is that a bug of version 0.7? Edit: What I did was: I created two courses (c1 and c2), then created a teacher (t1). Then I added t1 into c1. When do <code>GET /api/teachers</code>, I get t1 object, that's right. If add t1 into c2 and <code>GET /api/teachers</code> again, I will get two t1 objects. That won't happen if I put in OrderingFilter and set ordering I am not a native English speaker, and the question I posted was not that clear. Hopefully this update can make more sense
I found after I put ordering into TeacherViewSet, the duplicates gone. Is that I suppose to do ? Hi I'am having the same problem, downgraded django-filter to 0.5.4 now there's no duplicates results but filter_fields = ('field', 'field2') is not working. @yuxuan Filtering through many to many can sometime be misleading. Did you filter on 2 or more courses when this happened ? @xordoquy I updated the question. I didn't filter on 2 or more courses. I guess when add filter, the query will be base on the intermediate table. So if there is no filter parameters passed in, it will give duplicate results. I didn't read the source code, could be something else. @netoxico Is the updated situation same as you got? There are some other issues in the old version. I think you would be better to use the latest version, and put in OrderingFilter as well, as what I did in the update question. That may solve your problem This could do with a failing test case or example in order to help progress it. DjangoCon sprint guidance - does the ticket make sense as expressed here? Can you replicate it? Can you write a failing test case for it? Does the fix look like it needs to be in django-filter or in REST framework? Are you able to submit a pull request with the fix? Gonna try and write some failing tests for this. So I just created this test case for this, but was not able to recreate. https://gist.github.com/jpadilla/b493d98e9cd4ecf523bd Any thoughts? > was not able to recreate Okay, going to close this off then. Happy to reopen, but ideally would like someone to supply an example failing test case or confirm with more details on how to replicate. I ran into this issue yesterday and have written a failing test case for it. ``` class AttributeModel(models.Model): label = models.CharField(max_length=32) class SearchFilterModelM2M(models.Model): title = models.CharField(max_length=20) text = models.CharField(max_length=100) attributes = models.ManyToManyField(AttributeModel) class SearchFilterM2MTests(TestCase): def setUp(self): # Sequence of title/text/attributes is: # # z abc [1, 2, 3] # zz bcd [1, 2, 3] # zzz cde [1, 2, 3] # ... for idx in range(3): label = 'w' * (idx + 1) AttributeModel(label=label) for idx in range(10): title = 'z' * (idx + 1) text = ( chr(idx + ord('a')) + chr(idx + ord('b')) + chr(idx + ord('c')) ) SearchFilterModelM2M(title=title, text=text).save() SearchFilterModelM2M.objects.get(title='zz').attributes.add(1, 2, 3) def test_m2m_search(self): class SearchListView(generics.ListAPIView): model = SearchFilterModelM2M filter_backends = (filters.SearchFilter,) search_fields = ('=title', 'text', 'attributes__label') view = SearchListView.as_view() request = factory.get('/', {'search': 'zz'}) response = view(request) self.assertEqual(len(response.data), 1) ``` The simplest solution would be the inclusion of distinct() in [SearchFilter](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/filters.py#L107), which makes this test pass. This is in DRF 2.4.x @mmedal thanks for the test case ! No prob! Let me know if you want a pull request for this one. Can this issue be reopened? If you could supply a pull request for a failing test case that'd be great, yes. Actually, I think I already got this kind of things with pure Django application. I won't have time to dig that until next week but it's likely an issue with django filters. Retitled as this is an issue with `SearchFilter`, not `DjangoFilterBackend`
2015-02-10T10:00:46
encode/django-rest-framework
2,595
encode__django-rest-framework-2595
[ "2583" ]
b69032f3a794bbc45974a6b362b186c494373ae1
diff --git a/rest_framework/routers.py b/rest_framework/routers.py --- a/rest_framework/routers.py +++ b/rest_framework/routers.py @@ -171,9 +171,9 @@ def get_routes(self, viewset): # Dynamic detail routes (@detail_route decorator) for httpmethods, methodname in detail_routes: method_kwargs = getattr(viewset, methodname).kwargs - url_path = method_kwargs.pop("url_path", None) or methodname initkwargs = route.initkwargs.copy() initkwargs.update(method_kwargs) + url_path = initkwargs.pop("url_path", None) or methodname ret.append(Route( url=replace_methodname(route.url, url_path), mapping=dict((httpmethod, methodname) for httpmethod in httpmethods), @@ -184,9 +184,9 @@ def get_routes(self, viewset): # Dynamic list routes (@list_route decorator) for httpmethods, methodname in list_routes: method_kwargs = getattr(viewset, methodname).kwargs - url_path = method_kwargs.pop("url_path", None) or methodname initkwargs = route.initkwargs.copy() initkwargs.update(method_kwargs) + url_path = initkwargs.pop("url_path", None) or methodname ret.append(Route( url=replace_methodname(route.url, url_path), mapping=dict((httpmethod, methodname) for httpmethod in httpmethods),
diff --git a/tests/test_routers.py b/tests/test_routers.py --- a/tests/test_routers.py +++ b/tests/test_routers.py @@ -302,12 +302,16 @@ def detail_custom_route_get(self, request, *args, **kwargs): return Response({'method': 'link2'}) +class SubDynamicListAndDetailViewSet(DynamicListAndDetailViewSet): + pass + + class TestDynamicListAndDetailRouter(TestCase): def setUp(self): self.router = SimpleRouter() - def test_list_and_detail_route_decorators(self): - routes = self.router.get_routes(DynamicListAndDetailViewSet) + def _test_list_and_detail_route_decorators(self, viewset): + routes = self.router.get_routes(viewset) decorator_routes = [r for r in routes if not (r.name.endswith('-list') or r.name.endswith('-detail'))] MethodNamesMap = namedtuple('MethodNamesMap', 'method_name url_path') @@ -336,3 +340,9 @@ def test_list_and_detail_route_decorators(self): else: method_map = 'get' self.assertEqual(route.mapping[method_map], method_name) + + def test_list_and_detail_route_decorators(self): + self._test_list_and_detail_route_decorators(DynamicListAndDetailViewSet) + + def test_inherited_list_and_detail_route_decorators(self): + self._test_list_and_detail_route_decorators(SubDynamicListAndDetailViewSet)
url_path feature does not work for nested routes As per discussion on IRC with @tomchristie and chibisov/drf-extensions#70, the current <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/routers.py#L174">popping out</a> of the `url_path` kwarg does not work for downstream packages that reuse the same viewset for constructing nested routes. The reason for that is `get_routes()` being called multiple times (our router only calls it once) for each subsequent nested route, and therefore only the first route will know that `url_path` argument was set. P.S. As an adhoc example solution, <a href="https://gist.github.com/maryokhin/8765b07aa335b4d4bbcd#file-routers-py-L60">popping back in</a> `url_path` if it diverges from the method name on subsequent routes.
As a side note, why is the code in the `if` blocks duplicated and not i.e. a private method? ``` python if isinstance(route, DynamicDetailRoute): ... elif isinstance(route, DynamicListRoute): ... ``` This is also an issue if one has a mixin with a `list_route` or a `detail_route` that is used in several place. I'm working on a PR.
2015-02-24T16:21:24
encode/django-rest-framework
2,613
encode__django-rest-framework-2613
[ "2612" ]
cda74b59971f85da873b0e15da8b4afb4411a026
diff --git a/rest_framework/validators.py b/rest_framework/validators.py --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -13,7 +13,7 @@ from rest_framework.utils.representation import smart_repr -class UniqueValidator: +class UniqueValidator(object): """ Validator that corresponds to `unique=True` on a model field. @@ -67,7 +67,7 @@ def __repr__(self): )) -class UniqueTogetherValidator: +class UniqueTogetherValidator(object): """ Validator that corresponds to `unique_together = (...)` on a model class. @@ -155,7 +155,7 @@ def __repr__(self): )) -class BaseUniqueForValidator: +class BaseUniqueForValidator(object): message = None missing_message = _('This field is required.')
Validators are old-style classes. This means `super` cannot be used in a subclassed `Valdiator` in python 2.
Sure. Feel free to pull request it.
2015-02-27T15:23:09
encode/django-rest-framework
2,685
encode__django-rest-framework-2685
[ "2591" ]
a02098b855aad0847cddacc4bed2d280017b46c5
diff --git a/rest_framework/routers.py b/rest_framework/routers.py --- a/rest_framework/routers.py +++ b/rest_framework/routers.py @@ -218,14 +218,15 @@ def get_lookup_regex(self, viewset, lookup_prefix=''): https://github.com/alanjds/drf-nested-routers """ - base_regex = '(?P<{lookup_prefix}{lookup_field}>{lookup_value})' + base_regex = '(?P<{lookup_prefix}{lookup_url_kwarg}>{lookup_value})' # Use `pk` as default field, unset set. Default regex should not # consume `.json` style suffixes and should break at '/' boundaries. lookup_field = getattr(viewset, 'lookup_field', 'pk') + lookup_url_kwarg = getattr(viewset, 'lookup_url_kwarg', None) or lookup_field lookup_value = getattr(viewset, 'lookup_value_regex', '[^/.]+') return base_regex.format( lookup_prefix=lookup_prefix, - lookup_field=lookup_field, + lookup_url_kwarg=lookup_url_kwarg, lookup_value=lookup_value )
diff --git a/tests/test_routers.py b/tests/test_routers.py --- a/tests/test_routers.py +++ b/tests/test_routers.py @@ -32,6 +32,13 @@ class NoteViewSet(viewsets.ModelViewSet): lookup_field = 'uuid' +class KWargedNoteViewSet(viewsets.ModelViewSet): + queryset = RouterTestModel.objects.all() + serializer_class = NoteSerializer + lookup_field = 'text__contains' + lookup_url_kwarg = 'text' + + class MockViewSet(viewsets.ModelViewSet): queryset = None serializer_class = None @@ -40,6 +47,9 @@ class MockViewSet(viewsets.ModelViewSet): notes_router = SimpleRouter() notes_router.register(r'notes', NoteViewSet) +kwarged_notes_router = SimpleRouter() +kwarged_notes_router.register(r'notes', KWargedNoteViewSet) + namespaced_router = DefaultRouter() namespaced_router.register(r'example', MockViewSet, base_name='example') @@ -47,6 +57,7 @@ class MockViewSet(viewsets.ModelViewSet): url(r'^non-namespaced/', include(namespaced_router.urls)), url(r'^namespaced/', include(namespaced_router.urls, namespace='example')), url(r'^example/', include(notes_router.urls)), + url(r'^example2/', include(kwarged_notes_router.urls)), ] @@ -177,6 +188,33 @@ def test_urls_limited_by_lookup_value_regex(self): self.assertEqual(expected[idx], self.urls[idx].regex.pattern) +class TestLookupUrlKwargs(TestCase): + """ + Ensure the router honors lookup_url_kwarg. + + Setup a deep lookup_field, but map it to a simple URL kwarg. + """ + urls = 'tests.test_routers' + + def setUp(self): + RouterTestModel.objects.create(uuid='123', text='foo bar') + + def test_custom_lookup_url_kwarg_route(self): + detail_route = kwarged_notes_router.urls[-1] + detail_url_pattern = detail_route.regex.pattern + self.assertIn('^notes/(?P<text>', detail_url_pattern) + + def test_retrieve_lookup_url_kwarg_detail_view(self): + response = self.client.get('/example2/notes/fo/') + self.assertEqual( + response.data, + { + "url": "http://testserver/example/notes/123/", + "uuid": "123", "text": "foo bar" + } + ) + + class TestTrailingSlashIncluded(TestCase): def setUp(self): class NoteViewSet(viewsets.ModelViewSet):
lookup_url_kwarg not correctly used by Router [`lookup_url_kwarg`](https://github.com/tomchristie/django-rest-framework/blob/8b0f25aa0a91cb7b56f9ce4dde4330fe5daaad9b/rest_framework/generics.py#L85) does not appear to be used by the router when generating URLs. See: https://github.com/tomchristie/django-rest-framework/blob/ba7dca893cd55a1d5ee928c4b10878c92c44c4f5/rest_framework/routers.py#L228
Does look like a defect, yes. If anyone's able to together a minimal failing test case that's probable the next thing needed to progress this issue.
2015-03-13T00:13:14
encode/django-rest-framework
2,700
encode__django-rest-framework-2700
[ "2667" ]
4cd49d5de38b860e4b2260d7fa82dbdf9256c6e8
diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -388,6 +388,9 @@ class LimitOffsetPagination(BasePagination): def paginate_queryset(self, queryset, request, view=None): self.limit = self.get_limit(request) + if self.limit is None: + return None + self.offset = self.get_offset(request) self.count = _get_count(queryset) self.request = request @@ -491,6 +494,9 @@ class CursorPagination(BasePagination): template = 'rest_framework/pagination/previous_and_next.html' def paginate_queryset(self, queryset, request, view=None): + if self.page_size is None: + return None + self.base_url = request.build_absolute_uri() self.ordering = self.get_ordering(request, queryset, view)
LimitOffsetPagination raises Type error if PAGE_SIZE not set In 3.1.0 if you do not have PAGE_SIZE set you get a TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'. I believe a friendlier message would be useful in this case. I was going to submit a patch but was not sure exactly how you would like to handle this. Exception Type: TypeError Exception Value: unsupported operand type(s) for +: 'int' and 'NoneType' Exception Location: /work/virtual/skysql_upgrade/local/lib/python2.7/site-packages/rest_framework/pagination.py in paginate_queryset, line 396
2015-03-16T12:06:02
encode/django-rest-framework
2,724
encode__django-rest-framework-2724
[ "2711" ]
e34e0536b16cf89e6e3858c74c4ae66b01f89609
diff --git a/rest_framework/reverse.py b/rest_framework/reverse.py --- a/rest_framework/reverse.py +++ b/rest_framework/reverse.py @@ -3,6 +3,7 @@ """ from __future__ import unicode_literals from django.core.urlresolvers import reverse as django_reverse +from django.core.urlresolvers import NoReverseMatch from django.utils import six from django.utils.functional import lazy @@ -15,7 +16,13 @@ def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra """ scheme = getattr(request, 'versioning_scheme', None) if scheme is not None: - return scheme.reverse(viewname, args, kwargs, request, format, **extra) + try: + return scheme.reverse(viewname, args, kwargs, request, format, **extra) + except NoReverseMatch: + # In case the versioning scheme reversal fails, fallback to the + # default implementation + pass + return _reverse(viewname, args, kwargs, request, format, **extra)
diff --git a/tests/test_reverse.py b/tests/test_reverse.py --- a/tests/test_reverse.py +++ b/tests/test_reverse.py @@ -1,5 +1,6 @@ from __future__ import unicode_literals from django.conf.urls import patterns, url +from django.core.urlresolvers import NoReverseMatch from django.test import TestCase from rest_framework.reverse import reverse from rest_framework.test import APIRequestFactory @@ -16,6 +17,18 @@ def null_view(request): ) +class MockVersioningScheme(object): + + def __init__(self, raise_error=False): + self.raise_error = raise_error + + def reverse(self, *args, **kwargs): + if self.raise_error: + raise NoReverseMatch() + + return 'http://scheme-reversed/view' + + class ReverseTests(TestCase): """ Tests for fully qualified URLs when using `reverse`. @@ -26,3 +39,17 @@ def test_reversed_urls_are_fully_qualified(self): request = factory.get('/view') url = reverse('view', request=request) self.assertEqual(url, 'http://testserver/view') + + def test_reverse_with_versioning_scheme(self): + request = factory.get('/view') + request.versioning_scheme = MockVersioningScheme() + + url = reverse('view', request=request) + self.assertEqual(url, 'http://scheme-reversed/view') + + def test_reverse_with_versioning_scheme_fallback_to_default_on_error(self): + request = factory.get('/view') + request.versioning_scheme = MockVersioningScheme(raise_error=True) + + url = reverse('view', request=request) + self.assertEqual(url, 'http://testserver/view') diff --git a/tests/test_versioning.py b/tests/test_versioning.py --- a/tests/test_versioning.py +++ b/tests/test_versioning.py @@ -7,6 +7,7 @@ from rest_framework.reverse import reverse from rest_framework.test import APIRequestFactory, APITestCase from rest_framework.versioning import NamespaceVersioning +from rest_framework.relations import PKOnlyObject import pytest @@ -234,7 +235,7 @@ class FakeResolverMatch: class TestHyperlinkedRelatedField(UsingURLPatterns, APITestCase): included = [ - url(r'^namespaced/(?P<pk>\d+)/$', dummy_view, name='namespaced'), + url(r'^namespaced/(?P<pk>\d+)/$', dummy_pk_view, name='namespaced'), ] urlpatterns = [ @@ -262,3 +263,44 @@ def test_bug_2489(self): assert self.field.to_internal_value('/v1/namespaced/3/') == 'object 3' with pytest.raises(serializers.ValidationError): self.field.to_internal_value('/v2/namespaced/3/') + + +class TestNamespaceVersioningHyperlinkedRelatedFieldScheme(UsingURLPatterns, APITestCase): + included = [ + url(r'^namespaced/(?P<pk>\d+)/$', dummy_pk_view, name='namespaced'), + ] + + urlpatterns = [ + url(r'^v1/', include(included, namespace='v1')), + url(r'^v2/', include(included, namespace='v2')), + url(r'^non-api/(?P<pk>\d+)/$', dummy_pk_view, name='non-api-view') + ] + + def _create_field(self, view_name, version): + request = factory.get("/") + request.versioning_scheme = NamespaceVersioning() + request.version = version + + field = serializers.HyperlinkedRelatedField( + view_name=view_name, + read_only=True) + field._context = {'request': request} + return field + + def test_api_url_is_properly_reversed_with_v1(self): + field = self._create_field('namespaced', 'v1') + assert field.to_representation(PKOnlyObject(3)) == 'http://testserver/v1/namespaced/3/' + + def test_api_url_is_properly_reversed_with_v2(self): + field = self._create_field('namespaced', 'v2') + assert field.to_representation(PKOnlyObject(5)) == 'http://testserver/v2/namespaced/5/' + + def test_non_api_url_is_properly_reversed_regardless_of_the_version(self): + """ + Regression test for #2711 + """ + field = self._create_field('non-api-view', 'v1') + assert field.to_representation(PKOnlyObject(10)) == 'http://testserver/non-api/10/' + + field = self._create_field('non-api-view', 'v2') + assert field.to_representation(PKOnlyObject(10)) == 'http://testserver/non-api/10/'
Can't reverse non-API URLs with NamespaceVersioning Hello, I'm trying to setup a versioning mechanism using NamespaceVersioning as the method. Everything is fine except for the serializer fields that are using non-API views. The `reverse` function shipped with DRF will raise an exception because it's trying to reverse the non-API views from the same namespace as in `request.version`. Here's an example: ``` python class ConversationSerializer(serializers.Serializer): url = serializers.HyperlinkedIdentityField( view_name='conversation-detail', # This is an API view under v2 or v3 namespace lookup_url_kwargs='conversation_id') web_url = serializers.HyperlinkedIdentityField( view_name='account-conversation-detail', # This is a non-API view, without a namespace lookup_url_kwargs='conversation_id') ``` I feel we should do something about this in DRF itself, but I'm not sure how to tackle the issue (at least to document this behavior). One idea would be to automatically fallback to default reversal if the namespaced one fails. Any thoughts?
> One idea would be to automatically fallback to default reversal if the namespaced one fails. That sounds okay, yes. Maybe consider having a look at making that change in the `NamespacedVersioning` scheme and issuing a pull request with that plus a test. Sure, I'll do that!
2015-03-19T21:19:37
encode/django-rest-framework
2,764
encode__django-rest-framework-2764
[ "2763" ]
ac77a56e43ede7ff7dcb165e80e806ac72359f6c
diff --git a/rest_framework/response.py b/rest_framework/response.py --- a/rest_framework/response.py +++ b/rest_framework/response.py @@ -5,7 +5,7 @@ The appropriate renderer is called during Django's template response rendering. """ from __future__ import unicode_literals -from django.core.handlers.wsgi import STATUS_CODE_TEXT +from django.utils.six.moves.http_client import responses from django.template.response import SimpleTemplateResponse from django.utils import six @@ -77,7 +77,7 @@ def status_text(self): """ # TODO: Deprecate and use a template tag instead # TODO: Status code text for RFC 6585 status codes - return STATUS_CODE_TEXT.get(self.status_code, '') + return responses.get(self.status_code, '') def __getstate__(self): """
STATUS_CODE_TEXT was removed from django in trac ticket #24137 I'm getting an `ImportError` when using django 1.8 beta and rest framework 3.1.0 ``` File "/<omitted>/rest_framework/response.py", line 8, in <module> from django.core.handlers.wsgi import STATUS_CODE_TEXT ImportError: cannot import name 'STATUS_CODE_TEXT' ```
Link to relevant ticket https://code.djangoproject.com/ticket/24137. In summary we should probably be able to do something like in [response.py](https://github.com/tomchristie/django-rest-framework/blob/a89e05dc73e2c532372b1f9c51f38100f7f795f6/rest_framework/response.py#L80): ``` python from django.utils.six.moves.http_client import responses return responses.get(self.status_code, '') ```
2015-03-25T17:30:06
encode/django-rest-framework
2,766
encode__django-rest-framework-2766
[ "2673" ]
bdeb28944f3d4d2631871882b48ef08047fc3289
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -50,7 +50,7 @@ LIST_SERIALIZER_KWARGS = ( 'read_only', 'write_only', 'required', 'default', 'initial', 'source', 'label', 'help_text', 'style', 'error_messages', 'allow_empty', - 'instance', 'data', 'partial', 'context' + 'instance', 'data', 'partial', 'context', 'allow_null' )
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 @@ -69,3 +69,59 @@ def test_multipart_validate(self): input_data = QueryDict('nested[one]=1') serializer = self.Serializer(data=input_data) assert serializer.is_valid() + + +class TestNestedSerializerWithMany: + def setup(self): + class NestedSerializer(serializers.Serializer): + example = serializers.IntegerField(max_value=10) + + class TestSerializer(serializers.Serializer): + allow_null = NestedSerializer(many=True, allow_null=True) + not_allow_null = NestedSerializer(many=True) + + self.Serializer = TestSerializer + + def test_null_allowed_if_allow_null_is_set(self): + input_data = { + 'allow_null': None, + 'not_allow_null': [{'example': '2'}, {'example': '3'}] + } + expected_data = { + 'allow_null': None, + 'not_allow_null': [{'example': 2}, {'example': 3}] + } + serializer = self.Serializer(data=input_data) + + assert serializer.is_valid(), serializer.errors + assert serializer.validated_data == expected_data + + def test_null_is_not_allowed_if_allow_null_is_not_set(self): + input_data = { + 'allow_null': None, + 'not_allow_null': None + } + serializer = self.Serializer(data=input_data) + + assert not serializer.is_valid() + + expected_errors = {'not_allow_null': [serializer.error_messages['null']]} + assert serializer.errors == expected_errors + + def test_run_the_field_validation_even_if_the_field_is_null(self): + class TestSerializer(self.Serializer): + validation_was_run = False + + def validate_allow_null(self, value): + TestSerializer.validation_was_run = True + return value + + input_data = { + 'allow_null': None, + 'not_allow_null': [{'example': 2}] + } + serializer = TestSerializer(data=input_data) + + assert serializer.is_valid() + assert serializer.validated_data == input_data + assert TestSerializer.validation_was_run
allow_null=True is not being passed to ListSerializer constructor in many_init Hello, We have a use case where we accept either a list of objects or null. The problem is that `BaseSerializer.many_init` is not passing the `allow_null` argument to the `ListSerializer` constructor. because of that I have validation errors even if the field was specified with `allow_null=True`. He's an example: ``` python class PaymentInfoSerializer(serializers.Serializer): url = serializer.CharField() amount = serializers.DecimalField() def validate(self, attrs): """ This is never being called """ class Request(serializers.Serializer): payment_info = PaymentInfoSerializer( many=True, required=False, allow_null=True) ``` Basically `LIST_SERIALIZER_KWARGS` (defined [here](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L48)) does not include `allow_null` and therefore the arguments is not passed to the `ListSerializer` constructor (details [here](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L118)). Is there a reason why `allow_null` should not be sent to the list serializer? Thanks!
Our current fix is to create a custom `ListSerializer` that passes `allow_null=True` to the default constructor: ``` python class NullableListSerializer(serializers.ListSerializer): def __init__(self, *args, **kwargs): kwargs['allow_null'] = True super(NullableListSerializer, self).__init__(*args, **kwargs) class PaymentInfoSerializer(serializers.Serializer): class Meta: list_serializer_class = NullableListSerializer ``` It just feels hacky, since the default implementation of `ListSerializer` work well if you pass it the `allow_null=True` keyword argument, and this is the only required changed to make it work. Not convinced that we should be supporting this by default. I'd assume the current behavior will be to allow this: ``` [{'child': 'object'}, {'child': 'object'}, None, {'child': 'object'}] ``` Which I think is reasonable. If you want an empty list, use an empty list `[]` rather than `None`, or use a custom list serializer as you've done. We could discuss this further and might be open to a change, but for now I'm going to consider this as closed. I'm not saying it's necessarily a bug that needs to be addressed. You point regarding empty lists is perfectly valid. I'm not sure though that a list containing a `null` value at some index is more plausible use-case than specifying a `null` as an input for the `many` field. But there are a few aspects that make sense regarding this: 1. It costs almost nothing to support this functionality (just add the `allow_null` value to `LIST_SERIALIZER_KWARGS`). It will not break backwards compatibility and whoever will want to use this behavior will have to just define the field as `WhateverSerializer(many=True, allow_null=True)`. This will also be consistent with the other serializer usage `OtherSerializer(allow_null=True)`. 2. There might be cases when an empty list might mean something and a null value might means something else for the same field and the API needs to handle that. 3. In my case (and it's possible in other cases) I'm not building a new API, I'm upgrading a DRF 2.x API to the latest version and I need to keep backwards compatibility with my mobile apps If you don't consider this important enough, and I understand if you don't, we should at least document that this is not support, or even raise an exception if someone tries to use `WhateverSerializer(many=True, allow_null=True)`. Currently it just silently drops the keyword arguments that are not supported and it's somehow confusing (it took me a while to understand why the null value is not being passed to the serializer) Thanks for the great work you are doing! > if someone tries to use WhateverSerializer(many=True, allow_null=True) I think it's probably more a case of trying to figure out which of [{}, None, {}, {}] vs None is more intuitive - perhaps worth taking to the discussion group? Sounds good to me. I posted a question to the discussion group. :+1: @tomchristie There was not much of a discussion on the forum about this issue. The only comment was in favor of supporting None as a value for a list serializer field (instead of [{}, None, {}]). Did you get a chance to think about this more throughly? Perhaps the best thing to move this forward would be to write the _most minimal possible_ test case that demonstrates the behavior change that you're suggesting. Then submit that as a pull request, along with the suggested fix. Not a garuntee that it'll get pulled in, but that'd remove any blockers aside from the design decision. Sounds good. I'll have a PR in the next day or two.
2015-03-25T23:59:52
encode/django-rest-framework
2,836
encode__django-rest-framework-2836
[ "2835" ]
ecb37f518e7ec82b7b4124e8b6e829bc63aeb2ce
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -682,7 +682,7 @@ def to_internal_value(self, data): self.fail('max_string_length') try: - data = int(data) + data = int(re.compile(r'\.0*\s*$').sub('', str(data))) except (ValueError, TypeError): self.fail('invalid') return data
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -549,10 +549,13 @@ class TestIntegerField(FieldValues): 1: 1, 0: 0, 1.0: 1, - 0.0: 0 + 0.0: 0, + '1.0': 1 } invalid_inputs = { - 'abc': ['A valid integer is required.'] + 0.5: ['A valid integer is required.'], + 'abc': ['A valid integer is required.'], + '0.5': ['A valid integer is required.'] } outputs = { '1': 1,
IntegerField.to_internal_value coerces decimal to integer; should fail The to_internal_value method coerces data to an int, so when a float/decimal is passed, the int value is saved, rather than raising an exception.
2015-04-17T18:41:13
encode/django-rest-framework
2,869
encode__django-rest-framework-2869
[ "2656" ]
3113e8e5f010ecb0a6ac199adbbf56ffb38d2dbd
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -925,6 +925,9 @@ def to_internal_value(self, value): self.fail('invalid', format=humanized_format) def to_representation(self, value): + if not value: + return None + if self.format is None: return value @@ -938,7 +941,10 @@ def to_representation(self, value): ) if self.format.lower() == ISO_8601: + if (isinstance(value, str)): + value = datetime.datetime.strptime(value, '%Y-%m-%d').date() return value.isoformat() + return value.strftime(self.format)
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -726,7 +726,10 @@ class TestDateField(FieldValues): datetime.datetime(2001, 1, 1, 12, 00): ['Expected a date but got a datetime.'], } outputs = { - datetime.date(2001, 1, 1): '2001-01-01' + datetime.date(2001, 1, 1): '2001-01-01', + '2001-01-01': '2001-01-01', + None: None, + '': None, } field = serializers.DateField()
allow DateTimeFields to accept strings as input I found an interesting "bug" with Django Rest Framework along with how Django's DateTimeField works. Given the following TestCase: ``` class ReadOnlyDateTimeModel(models.Model): date = models.DateTimeField() def save(self, *args, **kwargs): self.date = '2015-02-03 00:00:00' return super(ReadOnlyDateTimeModel, self).save(*args, **kwargs) class ReadOnlyDateTimeSerializer(serializers.ModelSerializer): date = serializers.DateTimeField(read_only=True) class Meta: model = ReadOnlyDateTimeModel class ReadOnlyDateTimeView(generics.ListCreateAPIView): queryset = ReadOnlyDateTimeModel.objects.all() serializer_class = ReadOnlyDateTimeSerializer class TestReadOnlyFieldSerializer(TestCase): def setUp(self): self.view = ReadOnlyDateTimeView.as_view() def test_model_save_works(self): obj = ReadOnlyDateTimeModel.objects.create() assert obj.date == '2015-02-03 00:00:00' def test_post_root_view(self): """ POST requests to ListCreateAPIView should create a new object. """ data = {'price': 1} request = factory.post('/', data, format='json') response = self.view(request).render() self.assertEqual(response.status_code, status.HTTP_201_CREATED) ``` I see this error: ``` tests/test_generics.py:544: in test_post_root_view response = self.view(request).render() /usr/local/lib/python2.7/site-packages/django/views/decorators/csrf.py:57: in wrapped_view return view_func(*args, **kwargs) /usr/local/lib/python2.7/site-packages/django/views/generic/base.py:69: in view return self.dispatch(request, *args, **kwargs) rest_framework/views.py:452: in dispatch response = self.handle_exception(exc) rest_framework/views.py:449: in dispatch response = handler(request, *args, **kwargs) rest_framework/generics.py:244: in post return self.create(request, *args, **kwargs) rest_framework/mixins.py:21: in create headers = self.get_success_headers(serializer.data) rest_framework/serializers.py:466: in data ret = super(Serializer, self).data rest_framework/serializers.py:213: in data self._data = self.to_representation(self.instance) rest_framework/serializers.py:435: in to_representation ret[field.field_name] = field.to_representation(attribute) rest_framework/fields.py:879: in to_representation value = value.isoformat() E AttributeError: 'unicode' object has no attribute 'isoformat' ``` It seems like Django will accept a formatted string as input, however DRF tries to format the field as a datetime rather than a string, causing the above failure case. If I change `self.date = '2015-02-03 00:00:00'` to `self.date = datetime.datetime.now()`, it all works as expected.
Yup, we probably should correctly coerce string values too. Really the internal value _ought_ to be a `datetime` instance rather than a raw string, but we should still adopt the more graceful stance.
2015-04-24T00:35:53
encode/django-rest-framework
2,873
encode__django-rest-framework-2873
[ "2872" ]
3113e8e5f010ecb0a6ac199adbbf56ffb38d2dbd
diff --git a/rest_framework/views.py b/rest_framework/views.py --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -54,8 +54,7 @@ def exception_handler(exc, context): Returns the response that should be used for any given exception. By default we handle the REST framework `APIException`, and also - Django's built-in `ValidationError`, `Http404` and `PermissionDenied` - exceptions. + Django's built-in `Http404` and `PermissionDenied` exceptions. Any unhandled exceptions may return `None`, which will cause a 500 error to be raised.
exception_handler does not actually handle Django's built-in ValidationError Unlike the documentation suggests, the function `exception_handler` does not actually handle Django's built-in ValidationError. https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/views.py#L52
The docstring should be changed there, yes. We handle django's built-in validation error in serializers, but not here. Would you like a patch for the docstring? ``` We handle django's built-in validation error in serializers, but not here. ``` I am calling `Model.clean` in the serializer `update` and `create` functions but it does not catch django's validation errors. I had to resort to a custom exception handler. Am I missing something obvious? The documentation speaks of having to code it yourself, but does not elaborate on how to do it. > Would you like a patch for the docstring? That'd be great - I'm happy for us just to drop any mention of Django's validation error there. > I am calling Model.clean in the serializer update and create functions but it does not catch django's validation errors. I had to resort to a custom exception handler. Am I missing something obvious? Typically you'd want to handle validation _prior_ to update or create. In the case that you're using, yes you'll either need to catch and re-raise the exceptions as a handled type, or override the handler to deal with them itself. Sadly, validation is also needed in the Django Admin panel. There is currently no easy way to share validation. There was, in DRF 2.4.4 :wink: So we are stuck with validation-heavy models for a while. Sure. :smile: There's some background info on _why_ we've taken a slightly different approach now here https://www.youtube.com/watch?v=3cSsbe-tA0E - and yes that does mean a little more work if you're using both Django's validation style and REST framework together.
2015-04-24T13:38:18
encode/django-rest-framework
2,887
encode__django-rest-framework-2887
[ "2034" ]
f8eacc5bc02e700bf5fc149fc23cb8cdf71b1028
diff --git a/rest_framework/compat.py b/rest_framework/compat.py --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -7,6 +7,7 @@ from __future__ import unicode_literals from django.core.exceptions import ImproperlyConfigured from django.conf import settings +from django.db import connection, transaction from django.utils.encoding import force_text from django.utils.six.moves.urllib.parse import urlparse as _urlparse from django.utils import six @@ -266,3 +267,19 @@ def apply_markdown(text): from django.utils.duration import duration_string else: DurationField = duration_string = parse_duration = None + + +def set_rollback(): + if hasattr(transaction, 'set_rollback'): + if connection.settings_dict.get('ATOMIC_REQUESTS', False): + # If running in >=1.6 then mark a rollback as required, + # and allow it to be handled by Django. + transaction.set_rollback(True) + elif transaction.is_managed(): + # Otherwise handle it explicitly if in managed mode. + if transaction.is_dirty(): + transaction.rollback() + transaction.leave_transaction_management() + else: + # transaction not managed + pass diff --git a/rest_framework/views.py b/rest_framework/views.py --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -9,7 +9,7 @@ from django.utils.translation import ugettext_lazy as _ from django.views.decorators.csrf import csrf_exempt from rest_framework import status, exceptions -from rest_framework.compat import HttpResponseBase, View +from rest_framework.compat import HttpResponseBase, View, set_rollback from rest_framework.request import Request from rest_framework.response import Response from rest_framework.settings import api_settings @@ -71,16 +71,21 @@ def exception_handler(exc, context): else: data = {'detail': exc.detail} + set_rollback() return Response(data, status=exc.status_code, headers=headers) elif isinstance(exc, Http404): msg = _('Not found.') data = {'detail': six.text_type(msg)} + + set_rollback() return Response(data, status=status.HTTP_404_NOT_FOUND) elif isinstance(exc, PermissionDenied): msg = _('Permission denied.') data = {'detail': six.text_type(msg)} + + set_rollback() return Response(data, status=status.HTTP_403_FORBIDDEN) # Note: Unhandled exceptions will raise a 500 error.
diff --git a/tests/test_atomic_requests.py b/tests/test_atomic_requests.py new file mode 100644 --- /dev/null +++ b/tests/test_atomic_requests.py @@ -0,0 +1,110 @@ +from __future__ import unicode_literals + +from django.db import connection, connections, transaction +from django.test import TestCase +from django.utils.unittest import skipUnless +from rest_framework import status +from rest_framework.exceptions import APIException +from rest_framework.response import Response +from rest_framework.test import APIRequestFactory +from rest_framework.views import APIView +from tests.models import BasicModel + + +factory = APIRequestFactory() + + +class BasicView(APIView): + def post(self, request, *args, **kwargs): + BasicModel.objects.create() + return Response({'method': 'GET'}) + + +class ErrorView(APIView): + def post(self, request, *args, **kwargs): + BasicModel.objects.create() + raise Exception + + +class APIExceptionView(APIView): + def post(self, request, *args, **kwargs): + BasicModel.objects.create() + raise APIException + + +@skipUnless(connection.features.uses_savepoints, + "'atomic' requires transactions and savepoints.") +class DBTransactionTests(TestCase): + def setUp(self): + self.view = BasicView.as_view() + connections.databases['default']['ATOMIC_REQUESTS'] = True + + def tearDown(self): + connections.databases['default']['ATOMIC_REQUESTS'] = False + + def test_no_exception_conmmit_transaction(self): + request = factory.post('/') + + with self.assertNumQueries(1): + response = self.view(request) + self.assertFalse(transaction.get_rollback()) + self.assertEqual(response.status_code, status.HTTP_200_OK) + assert BasicModel.objects.count() == 1 + + +@skipUnless(connection.features.uses_savepoints, + "'atomic' requires transactions and savepoints.") +class DBTransactionErrorTests(TestCase): + def setUp(self): + self.view = ErrorView.as_view() + connections.databases['default']['ATOMIC_REQUESTS'] = True + + def tearDown(self): + connections.databases['default']['ATOMIC_REQUESTS'] = False + + def test_generic_exception_delegate_transaction_management(self): + """ + Transaction is eventually managed by outer-most transaction atomic + block. DRF do not try to interfere here. + + We let django deal with the transaction when it will catch the Exception. + """ + request = factory.post('/') + with self.assertNumQueries(3): + # 1 - begin savepoint + # 2 - insert + # 3 - release savepoint + with transaction.atomic(): + self.assertRaises(Exception, self.view, request) + self.assertFalse(transaction.get_rollback()) + assert BasicModel.objects.count() == 1 + + +@skipUnless(connection.features.uses_savepoints, + "'atomic' requires transactions and savepoints.") +class DBTransactionAPIExceptionTests(TestCase): + def setUp(self): + self.view = APIExceptionView.as_view() + connections.databases['default']['ATOMIC_REQUESTS'] = True + + def tearDown(self): + connections.databases['default']['ATOMIC_REQUESTS'] = False + + def test_api_exception_rollback_transaction(self): + """ + Transaction is rollbacked by our transaction atomic block. + """ + request = factory.post('/') + num_queries = (4 if getattr(connection.features, + 'can_release_savepoints', False) else 3) + with self.assertNumQueries(num_queries): + # 1 - begin savepoint + # 2 - insert + # 3 - rollback savepoint + # 4 - release savepoint (django>=1.8 only) + with transaction.atomic(): + response = self.view(request) + self.assertTrue(transaction.get_rollback()) + self.assertEqual(response.status_code, + status.HTTP_500_INTERNAL_SERVER_ERROR) + assert BasicModel.objects.count() == 0
Handle ATOMIC_REQUESTS correctly. We should include some documentation around sensible ways to deal with atomicity in transactions, and also deal properly with `ATOMIC_REQUESTS` correctly. This needs both documentation, and probably also enhancements for handling `ATOMIC_REQUESTS = True`, which is complicated by the fact that we use a custom exception handler. PR #1787 was an attempt at this but doesn't take the right approach, unsure how to resolve currently.
@tomchristie this question may seem dull but this point isn't clear to me: Does it mean that DRF do not support `ATOMIC_REQUESTS = True`? Because we're just trying to use it in our project and it does not seem to be working. I even posted a [question on StackOverflow](http://stackoverflow.com/questions/29652511/django-atomic-requests-not-working). @alvarocavalcanti This is confirmed. I'll try to see if I can get a test case for this. Edit: Longer answer is that ATOMIC_REQUESTS will fail if you have a custom exception handler in DRF and your exception is a APIException one. Pure Python exception will not break the ATOMIC_REQUESTS. @tomchristie can you be more specific about why #1787 doesn't take the right approach ? Well, stupidly I don't recall - so let's put it another way around. We need to be able to write tests that verify any proposed fix. Until and unless we've done that we shouldn't accept something. (including #1787) @tomchristie fair enough (Or if not tests, then at least a process by which we can verify the proposed fix.)
2015-04-29T13:14:08
encode/django-rest-framework
2,940
encode__django-rest-framework-2940
[ "2839" ]
6add1acc4e5f701b99e9bf59bc7484fb9126ce49
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1045,7 +1045,7 @@ def to_internal_value(self, data): def to_representation(self, value): if value in ('', None): return value - return self.choice_strings_to_values[six.text_type(value)] + return self.choice_strings_to_values.get(six.text_type(value), value) class MultipleChoiceField(ChoiceField): @@ -1073,7 +1073,7 @@ def to_internal_value(self, data): def to_representation(self, value): return set([ - self.choice_strings_to_values[six.text_type(item)] for item in value + self.choice_strings_to_values.get(six.text_type(item), item) for item in value ])
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -920,7 +920,8 @@ class TestChoiceField(FieldValues): } outputs = { 'good': 'good', - '': '' + '': '', + 'amazing': 'amazing', } field = serializers.ChoiceField( choices=[ @@ -1005,7 +1006,7 @@ class TestMultipleChoiceField(FieldValues): ('aircon', 'incorrect'): ['"incorrect" is not a valid choice.'] } outputs = [ - (['aircon', 'manual'], set(['aircon', 'manual'])) + (['aircon', 'manual', 'incorrect'], set(['aircon', 'manual', 'incorrect'])) ] field = serializers.MultipleChoiceField( choices=[
Allow unexpected values for `ChoiceField`/`MultipleChoiceField` representations. When an invalid value is present in the database that isn't part of the list of choices (perhaps dealing with a legacy database) a KeyError will be raised in to_representation() of ChoiceField/MultipleChoiceField. Personally I'd like to see the behaviour more in line with the Django ORM's choices behaviour where the invalid value is still readable, perhaps by simply returning it from to_representation() In case this is disagreeable, I think the KeyError should be caught and a new exception raised with a more easily debuggable error message explaining which field has the invalid value.
Totally agree! It breaks down the system in such cases. I think simply returning "invalid" value would be the best. Additionally, the current behaviour does not allow to have one set of fields for the output and another for input. Eg. we have a 3 different values possible on the model layer, but I only want to accept 2 of them in the input of a specific serializer (yet return all 3 of them in the output if they're there). Solvable with a custom field, but still a pain. > I think the KeyError should be caught and a new exception raised with a more easily debuggable error message explaining which field has the invalid value. Happy to accept an issue for this if it's presented as an example with: - The current behavior. - The suggested behavior. As far as the remainder of the ticket - it's unclear to me what's being suggested, but it sounds like a case for a custom field, as does @maryokhin's different input and output requirement. The key of the current behaviour is difference from Django ORM behaviour. Using Django ORM you can have in db field values that not presents in field choices. And this is not rare case! Your db can be legacy or in the middle of the data migrations or smth else. But this is not rare. Using Django you can safety deal with this case - those field still readable. You just get value as-is. Using DRF you get not operational api with strange and useless for the first time KeyError exception. Ah, misunderstood the ticket here I think - so the request is that unexpected values should be passed through as-is to the representation. Sure I've no great problem with that. Happy to accept a pull request modifying the behavior there, and including an example test case. Exactly! Accepted.
2015-05-15T09:02:59
encode/django-rest-framework
2,948
encode__django-rest-framework-2948
[ "2947" ]
e33fed70d65303627ea4ee8292dd28a6a1f9f617
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -782,7 +782,8 @@ def to_internal_value(self, data): self.fail('invalid') sign, digittuple, exponent = value.as_tuple() - decimals = abs(exponent) + decimals = exponent * decimal.Decimal(-1) if exponent < 0 else 0 + # digittuple doesn't include any leading zeros. digits = len(digittuple) if decimals > digits:
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -647,6 +647,7 @@ class TestDecimalField(FieldValues): 0: Decimal('0'), 12.3: Decimal('12.3'), 0.1: Decimal('0.1'), + '2E+2': Decimal('200'), } invalid_inputs = ( ('abc', ["A valid number is required."]),
`max_decimal_places` in Decimal field are wrong calculated We got an issue when number is formatted as `decimal.Decimal('2E+9')`. How `DecimalField` counts decimals: ``` sign, digittuple, exponent = value.as_tuple() decimals = abs(exponent) ``` However result of `decimal.Decimal('2E+9').as_tuple()[2]` is **9**, which is ok, but there are no decimal places in this number. My solution is to not do `abs` and instead multiply by `-1`. I can prepare PR tonight if you think it is valid.
So things that would help here: - Any comparisons between what happens in Django core and what we do (if that's possible/relevant?) - One or two example cases (In particular pull requests with failing test cases), and expected input/output values.
2015-05-18T14:44:05
encode/django-rest-framework
2,981
encode__django-rest-framework-2981
[ "2811" ]
d4dd22ff1c1c8b1540fb039cfecab127b017f457
diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py --- a/rest_framework/metadata.py +++ b/rest_framework/metadata.py @@ -127,7 +127,7 @@ def get_field_info(self, field): if value is not None and value != '': field_info[attr] = force_text(value, strings_only=True) - if hasattr(field, 'choices'): + if not field_info.get('read_only') and hasattr(field, 'choices'): field_info['choices'] = [ { 'value': choice_value,
diff --git a/tests/test_metadata.py b/tests/test_metadata.py --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -1,4 +1,7 @@ from __future__ import unicode_literals +from django.db import models +from django.test import TestCase +from django.core.validators import MinValueValidator, MaxValueValidator from rest_framework import exceptions, metadata, serializers, status, views, versioning from rest_framework.request import Request from rest_framework.renderers import BrowsableAPIRenderer @@ -212,3 +215,83 @@ def test_null_boolean_field_info_type(self): options = metadata.SimpleMetadata() field_info = options.get_field_info(serializers.NullBooleanField()) assert field_info['type'] == 'boolean' + + +class TestModelSerializerMetadata(TestCase): + def test_read_only_primary_key_related_field(self): + """ + On generic views OPTIONS should return an 'actions' key with metadata + on the fields that may be supplied to PUT and POST requests. It should + not fail when a read_only PrimaryKeyRelatedField is present + """ + class Parent(models.Model): + integer_field = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(1000)]) + children = models.ManyToManyField('Child') + name = models.CharField(max_length=100, blank=True, null=True) + + class Child(models.Model): + name = models.CharField(max_length=100) + + class ExampleSerializer(serializers.ModelSerializer): + children = serializers.PrimaryKeyRelatedField(read_only=True, many=True) + + class Meta: + model = Parent + + class ExampleView(views.APIView): + """Example view.""" + def post(self, request): + pass + + def get_serializer(self): + return ExampleSerializer() + + view = ExampleView.as_view() + response = view(request=request) + expected = { + 'name': 'Example', + 'description': 'Example view.', + 'renders': [ + 'application/json', + 'text/html' + ], + 'parses': [ + 'application/json', + 'application/x-www-form-urlencoded', + 'multipart/form-data' + ], + 'actions': { + 'POST': { + 'id': { + 'type': 'integer', + 'required': False, + 'read_only': True, + 'label': 'ID' + }, + 'children': { + 'type': 'field', + 'required': False, + 'read_only': True, + 'label': 'Children' + }, + 'integer_field': { + 'type': 'integer', + 'required': True, + 'read_only': False, + 'label': 'Integer field', + 'min_value': 1, + 'max_value': 1000 + }, + 'name': { + 'type': 'string', + 'required': False, + 'read_only': False, + 'label': 'Name', + 'max_length': 100 + } + } + } + } + + assert response.status_code == status.HTTP_200_OK + assert response.data == expected
ManyRelatedField.choices tries to iterate over None `ManyRelatedField.choices` is a `property` which [iterates over](https://github.com/tomchristie/django-rest-framework/blob/311cad64c998a89b8e8e2394140e0265ff98f53d/rest_framework/relations.py#L376-L383) `self.child_relation.queryset`. This can be `None` if `self.child_relation` is read-only. I found this when `SimpleMetadata.get_field_info` tried to [check if `field.choices` exists](https://github.com/tomchristie/django-rest-framework/blob/311cad64c998a89b8e8e2394140e0265ff98f53d/rest_framework/metadata.py#L130) and raised `TypeError`.
I'm not sure where the best place to fix this is. A simple fix for my direct issue would be to catch the `TypeError` in `SimpleMetadata.get_field_info`, but I'm not sure `ManyRelatedField.choices` should be raising it in the first place. I went into similar issue a few days ago. I got this when making an OPTIONS request and it seems the response tries to iterate over field choices, even if field is `read only` (which a simple GET resquest doesn't do). I fixed this by adding (file: relations.py, line:380) ``` python iterable = queryset.all() if (hasattr(queryset, 'all')) else queryset + if not iterable: + return { } ``` This is perhaps a bad behaviour of the OPTION request that could check if field is not read_only before calling `choices()`. But, on the other hand, the `choice` method is not robust... Best regards.
2015-05-28T20:29:50
encode/django-rest-framework
3,006
encode__django-rest-framework-3006
[ "2928" ]
0c66c7cfa6df065eab89bb3b88db49012ae06d60
diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py --- a/rest_framework/authentication.py +++ b/rest_framework/authentication.py @@ -170,7 +170,13 @@ def authenticate(self, request): msg = _('Invalid token header. Token string should not contain spaces.') raise exceptions.AuthenticationFailed(msg) - return self.authenticate_credentials(auth[1]) + try: + token = auth[1].decode() + except UnicodeError: + msg = _('Invalid token header. Token string should not contain invalid characters.') + raise exceptions.AuthenticationFailed(msg) + + return self.authenticate_credentials(token) def authenticate_credentials(self, key): try:
diff --git a/tests/test_authentication.py b/tests/test_authentication.py --- a/tests/test_authentication.py +++ b/tests/test_authentication.py @@ -1,3 +1,5 @@ +# coding: utf-8 + from __future__ import unicode_literals from django.conf.urls import patterns, url, include from django.contrib.auth.models import User @@ -162,6 +164,12 @@ def test_post_form_passing_token_auth(self): response = self.csrf_client.post('/token/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, status.HTTP_200_OK) + def test_fail_post_form_passing_invalid_token_auth(self): + # add an 'invalid' unicode character + auth = 'Token ' + self.key + "¸" + response = self.csrf_client.post('/token/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + def test_post_json_passing_token_auth(self): """Ensure POSTing form over token auth with correct credentials passes and does not require CSRF""" auth = "Token " + self.key
Invalid Unicode byte in Authorization token raises an DjangoUnicodeDecodeError When we sent an invalid/unicode byte in token authentication we got a `500 Internal Server Error` (`DjangoUnicodeDecodeError`) instead of a `401 Unauthorized`: ``` python headers = {'Authorization':'token cfbcf941f2fa06a0647b7dc4cb7839199b495c2b¸'} # <-- last char is an invalid unicode char ``` Raises the following traceback: ``` Stacktrace (most recent call last): File "django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "python3.4/contextlib.py", line 30, in inner return func(*args, **kwds) File "django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "rest_framework/viewsets.py", line 85, in view return self.dispatch(request, *args, **kwargs) File "rest_framework/views.py", line 452, in dispatch response = self.handle_exception(exc) File "rest_framework/views.py", line 440, in dispatch self.initial(request, *args, **kwargs) File "rest_framework/views.py", line 354, in initial self.perform_authentication(request) File "rest_framework/views.py", line 292, in perform_authentication request.user File "rest_framework/request.py", line 491, in __getattribute__ return super(Request, self).__getattribute__(attr) File "rest_framework/request.py", line 266, in user self._authenticate() File "rest_framework/request.py", line 454, in _authenticate user_auth_tuple = authenticator.authenticate(self) File "rest_framework/authentication.py", line 167, in authenticate return self.authenticate_credentials(auth[1]) File "rest_framework/authentication.py", line 171, in authenticate_credentials token = self.model.objects.select_related('user').get(key=key) File "django/db/models/query.py", line 325, in get clone = self.filter(*args, **kwargs) File "django/db/models/query.py", line 679, in filter return self._filter_or_exclude(False, *args, **kwargs) File "django/db/models/query.py", line 697, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "django/db/models/sql/query.py", line 1304, in add_q clause, require_inner = self._add_q(where_part, self.used_aliases) File "django/db/models/sql/query.py", line 1331, in _add_q current_negated=current_negated, connector=connector, allow_joins=allow_joins) File "django/db/models/sql/query.py", line 1203, in build_filter condition = self.build_lookup(lookups, col, value) File "django/db/models/sql/query.py", line 1096, in build_lookup return final_lookup(lhs, rhs) File "django/db/models/lookups.py", line 96, in __init__ self.rhs = self.get_prep_lookup() File "django/db/models/lookups.py", line 134, in get_prep_lookup return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs) File "django/db/models/fields/__init__.py", line 727, in get_prep_lookup return self.get_prep_value(value) File "django/db/models/fields/__init__.py", line 1125, in get_prep_value return self.to_python(value) File "django/db/models/fields/__init__.py", line 1121, in to_python return smart_text(value) File "django/utils/encoding.py", line 56, in smart_text return force_text(s, encoding, strings_only, errors) File "django/utils/encoding.py", line 102, in force_text raise DjangoUnicodeDecodeError(s, *e.args) ```
Does this happen if the extra bytes are encoded ahead of time? And is that character allowed in the `Authorization` header? [Related httpie ticket.](https://github.com/jakubroztocil/httpie/issues/212) @kevin-brown even though we should gracefully return the issue. @osantana do you have a test case for this issue or was it discovered on a running server ? I've a testcase but it's an application that we're developing/deploying privately for a company, so, we did not have a public API to provide. But I can reproduce this issue and send you more information about it. The stacktrace provided is the full stacktrace and we don't use any custom Authentication method. ``` python # settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'apps.core.permissions.ModelPermission', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',) } ``` @osantana I gave it a try to reproduce the issue but so far I've not been able to do it within a testcase. If we can't replicate this, there's no way we'll be able to progress the issue. Going to close the ticket off for now, but if there's a demonstrable way to replicate it, then we'll reopen. Sorry, I forgot to mention a _very_ important thing: this project runs with Python 3.4 (and this exception raises only in Py3). Besides that I've forked DRF-tutorial project and created a test to reproduce this issue: https://github.com/osantana/rest-framework-tutorial/blob/master/snippets/tests.py You can just clone this repository, install requirements and run `./manage.py tests`. @osantana will give it a try tonight and reopen if I can reproduce it. Thanks for the details. News about this issue? @osantana at the moment no. I unsuccessfully tried to reproduce it. Even with the tests that I created for [rest-framework-tutorial](https://github.com/osantana/rest-framework-tutorial/blob/master/snippets/tests.py)? Have you tried with Python 3.4? This is a Py3-related issue... Sorry, I missed that part and didn't have the to test against your test case yet. @osantana here's the result on my box: ``` bash-3.2$ pip freeze -l You are using pip version 6.1.1, however version 7.0.3 is available. You should consider upgrading via the 'pip install --upgrade pip' command. Django==1.8.2 djangorestframework==3.1.2 Markdown==2.6.2 Pygments==2.0.2 requests==2.7.0 bash-3.2$ python --version Python 3.4.3 bash-3.2$ python manage.py test Creating test database for alias 'default'... .... ---------------------------------------------------------------------- Ran 4 tests in 0.790s OK Destroying test database for alias 'default'... bash-3.2$ ``` What OS are you using and what are your locals ? I'm using Ubuntu 14.04 and locale(?) is set with en_US.UTF-8 but I've other language packs installed and generated. **Edited**: I'm using 14.04! :) But I can try to reproduce this issue on other environment... (I've a Mac OS X 10.10 to make tests) @osantana I'm not saying this issue doesn't exist or is void. I'm simply pointing out that it doesn't look like a simple py3 related issue - at least not an obvious one at all. Ok, I understand this... What I'm trying to do is to know _if_ you managed to reproduce the issue or if I need provide more information to help you :) It's don't even know if it's a "big issue" but I believe that people can use it to generate a DoS attack in affected APIs... @osantana At this point I think there might be more involved that needs to be looked at. If you can replicate the test within the DRF repository and create a (failing) pull request, that might be better than trying to reproduce it outside of the repository.
2015-06-03T17:58:49
encode/django-rest-framework
3,026
encode__django-rest-framework-3026
[ "1516" ]
2749b12eaf20402d4a98437c0374660ded855b3e
diff --git a/rest_framework/urlpatterns.py b/rest_framework/urlpatterns.py --- a/rest_framework/urlpatterns.py +++ b/rest_framework/urlpatterns.py @@ -21,7 +21,7 @@ def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required): else: # Regular URL pattern - regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern + regex = urlpattern.regex.pattern.rstrip('$').rstrip('/') + suffix_pattern view = urlpattern._callback or urlpattern._callback_str kwargs = urlpattern.default_args name = urlpattern.name @@ -55,8 +55,8 @@ def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None): allowed_pattern = allowed[0] else: allowed_pattern = '(%s)' % '|'.join(allowed) - suffix_pattern = r'\.(?P<%s>%s)$' % (suffix_kwarg, allowed_pattern) + suffix_pattern = r'\.(?P<%s>%s)/?$' % (suffix_kwarg, allowed_pattern) else: - suffix_pattern = r'\.(?P<%s>[a-z0-9]+)$' % suffix_kwarg + suffix_pattern = r'\.(?P<%s>[a-z0-9]+)/?$' % suffix_kwarg return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required)
diff --git a/tests/test_urlpatterns.py b/tests/test_urlpatterns.py --- a/tests/test_urlpatterns.py +++ b/tests/test_urlpatterns.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals from collections import namedtuple -from django.conf.urls import patterns, url, include +from django.conf.urls import url, include from django.core import urlresolvers from django.test import TestCase from rest_framework.test import APIRequestFactory @@ -17,7 +17,8 @@ def dummy_view(request, *args, **kwargs): class FormatSuffixTests(TestCase): """ - Tests `format_suffix_patterns` against different URLPatterns to ensure the URLs still resolve properly, including any captured parameters. + 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): factory = APIRequestFactory() @@ -35,11 +36,37 @@ def _resolve_urlpatterns(self, urlpatterns, test_paths): self.assertEqual(callback_args, test_path.args) self.assertEqual(callback_kwargs, test_path.kwargs) + def test_trailing_slash(self): + factory = APIRequestFactory() + urlpatterns = format_suffix_patterns([ + url(r'^test/$', dummy_view), + ]) + resolver = urlresolvers.RegexURLResolver(r'^/', urlpatterns) + + test_paths = [ + (URLTestPath('/test.api', (), {'format': 'api'}), True), + (URLTestPath('/test/.api', (), {'format': 'api'}), False), + (URLTestPath('/test.api/', (), {'format': 'api'}), True), + ] + + 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 urlresolvers.Resolver404: + callback, callback_args, callback_kwargs = (None, None, None) + if not expected_resolved: + assert callback is None + continue + + print(test_path, callback, callback_args, callback_kwargs) + assert callback_args == test_path.args + assert callback_kwargs == test_path.kwargs + def test_format_suffix(self): - urlpatterns = patterns( - '', + urlpatterns = [ url(r'^test$', dummy_view), - ) + ] test_paths = [ URLTestPath('/test', (), {}), URLTestPath('/test.api', (), {'format': 'api'}), @@ -48,10 +75,9 @@ def test_format_suffix(self): self._resolve_urlpatterns(urlpatterns, test_paths) def test_default_args(self): - urlpatterns = patterns( - '', + urlpatterns = [ url(r'^test$', dummy_view, {'foo': 'bar'}), - ) + ] test_paths = [ URLTestPath('/test', (), {'foo': 'bar', }), URLTestPath('/test.api', (), {'foo': 'bar', 'format': 'api'}), @@ -60,14 +86,12 @@ def test_default_args(self): self._resolve_urlpatterns(urlpatterns, test_paths) def test_included_urls(self): - nested_patterns = patterns( - '', + nested_patterns = [ url(r'^path$', dummy_view) - ) - urlpatterns = patterns( - '', + ] + urlpatterns = [ url(r'^test/', include(nested_patterns), {'foo': 'bar'}), - ) + ] test_paths = [ URLTestPath('/test/path', (), {'foo': 'bar', }), URLTestPath('/test/path.api', (), {'foo': 'bar', 'format': 'api'}),
format_suffix_patterns applies them after trailing slash. According to http://www.django-rest-framework.org/api-guide/format-suffixes the suffices should be used directly after the resource name like http://example.com/api/users.json but format_suffix_patterns applies them after the trailing slash if one is used in the urlpatterns it gets (like the DefaultRouter does) This results in 404 when trying to use them in the tutorial app for example: http://restframework.herokuapp.com/users.json
Agree that that docs are misleading as to the current behavior there, but not sure if that's a docs fix, or if we need to change the default behavior. Assuming this is a duplicate of #1319, but not clear to me that it really was properly addressed, or if #1333 (available in the upcoming 2.4.0) only addressed a subset of the problem. DjangoCon sprint guidance - review current behaviour, summarise what you would expect desired behaviour to be. My expectations for the behavior would be the following: ``` # should work example.com/test.json # should NOT work example.com/test/.json ``` I have mixed thoughts on the following: example.com/test.json/ I kind of like the idea of requiring the specification of a data format to be the very end of an address. This would mean not allowing a trailing slash. However, others may have use cases that would disagree with this approach. Our group specifies content type via the HTTP Accept Header; however, I agree with the support for specifying the data format via an address. Lastly, I think the documentation should at least be updated to include samples as to which addresses are expected to work based on the usage of the format_suffix_patterns functionality. Seems reasonable. I've always found that `comments/.json` is just plain weird and confusing. Expected for me is: ``` http://localhost:8000/comments.json # perhaps this too http://localhost:8000/comments.json/ http://localhost:8000/comments/?format=json ``` If behavior doesn't change for now, updating docs might be a good idea. I agree with this. This is coming from someone completely new to the framework and going through the tutorial, so take that as you wish. However, the tutorial even gives the example that using `format_suffix_patterns` should make it so the API `will be able to handle URLs such as http://example.com/api/items/4.json` See here: http://www.django-rest-framework.org/tutorial/2-requests-and-responses/#adding-optional-format-suffixes-to-our-urls Edit: The example HTTP requests later on the same page show the proper request with the trailing forward slash. So maybe this should just be a doc change higher up. However, I would still agree that without a forward slash makes more sense.
2015-06-10T22:32:47
encode/django-rest-framework
3,073
encode__django-rest-framework-3073
[ "2710" ]
d5609979cab403ea79c39ea8a4aeec9de1b1ff38
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -580,7 +580,7 @@ def run_validation(self, data=empty): # Test for the empty string here so that it does not get validated, # and so that subclasses do not need to handle it explicitly # inside the `to_internal_value()` method. - if data == '': + if data == '' or (self.trim_whitespace and six.text_type(data).strip() == ''): if not self.allow_blank: self.fail('blank') return ''
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -461,6 +461,13 @@ def test_trim_whitespace_disabled(self): field = serializers.CharField(trim_whitespace=False) assert field.to_internal_value(' abc ') == ' abc ' + def test_disallow_blank_with_trim_whitespace(self): + field = serializers.CharField(allow_blank=False, trim_whitespace=True) + + with pytest.raises(serializers.ValidationError) as exc_info: + field.run_validation(' ') + assert exc_info.value.detail == ['This field may not be blank.'] + class TestEmailField(FieldValues): """
CharField: allow_blank=False in combination with trim_whitespace=True does not behave as expected The two options can not be used in combination to raise a validation error if the incoming data purely consists of whitespace because `to_internal_value` is not applied before validation. Is this something that could be changed? And is there a way for me to achieve this behaviour currently without writing custom validation?
Sounds like a totally valid improvement to make, to me.
2015-06-24T12:34:25
encode/django-rest-framework
3,099
encode__django-rest-framework-3099
[ "3091" ]
5bb02cc7b9652cc6ce9aac00ea2041ae0e8f9b1c
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -1105,8 +1105,8 @@ def include_extra_kwargs(self, kwargs, extra_kwargs): if extra_kwargs.get('default') and kwargs.get('required') is False: kwargs.pop('required') - if kwargs.get('read_only', False): - extra_kwargs.pop('required', None) + if extra_kwargs.get('read_only', kwargs.get('read_only', False)): + extra_kwargs.pop('required', None) # Read only fields should always omit the 'required' argument. kwargs.update(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 @@ -235,6 +235,23 @@ class Meta: """) self.assertEqual(repr(TestSerializer()), expected) + def test_extra_field_kwargs_required(self): + """ + Ensure `extra_kwargs` are passed to generated fields. + """ + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = RegularFieldsModel + fields = ('auto_field', 'char_field') + extra_kwargs = {'auto_field': {'required': False, 'read_only': False}} + + expected = dedent(""" + TestSerializer(): + auto_field = IntegerField(read_only=False, required=False) + char_field = CharField(max_length=100) + """) + self.assertEqual(repr(TestSerializer()), expected) + def test_invalid_field(self): """ Field names that do not map to a model field or relationship should
Unable to override required argument on a read_only field in extra_kwargs Fields that are set to `"read_only": True` are not passed to `update()` on a serializer. A work around to this was to add `"read_only": False` to `extra_kwargs` for that field. This would pass the value to update and allow us to use it. One problem then is with required fields. In `create()`, these fields must be supplied by default. However, for something like an auto-generated UUID or primary key, we cannot provide it. To work around this, we set `"required": False` in the extra_kwargs for that field as well. In 3.1.2, this behavior allowed creation without that field provided and update was passed it's value. In 3.1.3, this isn't possible because the field is now required and validation fails. This behavior seems to be changed due to #2975. In #2975, if `read_only` is set to `True` in the model or serializer fields, it drops the `required` value in `extra_kwargs` and defaults to the model or serializer field values. However, we've set the value for `read_only` to `False` in `extra_kwargs`. The problem is that the serializer is still assuming the value is `True` since it is pulling from the model or serializer fields and not `extra_kwargs`, overriding the behavior we want. Here is an example usage: #### serializers.py ``` python class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album fields = ( 'id', 'artist', 'producer', 'year', 'price' ) extra_kwargs = { "id": { "required": False, "read_only": False } } ```
Should [this line](https://github.com/tomchristie/django-rest-framework/pull/2975/files#diff-80f43677c94659fbd60c8687cce68eafR1091) instead be like so?... ``` if extra_kwargs.get('read_only', kwargs.get('read_only', False)): extra_kwargs.pop('required', None) # Read only fields should always omit the 'required' argument. ``` Assume that would resolve your issue? @tomchristie Yes, that fixes the issue I'm experiencing.
2015-07-01T14:19:18
encode/django-rest-framework
3,147
encode__django-rest-framework-3147
[ "3068" ]
209bcb90879c7373787fb1201854e06adb3cc729
diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -455,7 +455,8 @@ class CursorPagination(BasePagination): template = 'rest_framework/pagination/previous_and_next.html' def paginate_queryset(self, queryset, request, view=None): - if self.page_size is None: + page_size = self.get_page_size(request) + if not page_size: return None self.base_url = request.build_absolute_uri() @@ -490,8 +491,8 @@ def paginate_queryset(self, queryset, request, view=None): # If we have an offset cursor then offset the entire page by that amount. # We also always fetch an extra item in order to determine if there is a # page following on from this one. - results = list(queryset[offset:offset + self.page_size + 1]) - self.page = list(results[:self.page_size]) + results = list(queryset[offset:offset + page_size + 1]) + self.page = list(results[:page_size]) # Determine the position of the final item following the page. if len(results) > len(self.page): @@ -530,6 +531,9 @@ def paginate_queryset(self, queryset, request, view=None): return self.page + def get_page_size(self, request): + return self.page_size + def get_next_link(self): if not self.has_next: return None
Cursor pagination page size `page_size` customization on per query basis through `page_size_query_param` and `max_page_size` parameters. Spin-off of #3033
2015-07-14T10:42:09
encode/django-rest-framework
3,161
encode__django-rest-framework-3161
[ "2250" ]
81709a2c73790868e0e75a9e9092b82e94aa0221
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1141,10 +1141,15 @@ def to_representation(self, value): class MultipleChoiceField(ChoiceField): default_error_messages = { 'invalid_choice': _('"{input}" is not a valid choice.'), - 'not_a_list': _('Expected a list of items but got type "{input_type}".') + 'not_a_list': _('Expected a list of items but got type "{input_type}".'), + 'empty': _('This selection may not be empty.') } default_empty_html = [] + def __init__(self, *args, **kwargs): + self.allow_empty = kwargs.pop('allow_empty', True) + super(MultipleChoiceField, self).__init__(*args, **kwargs) + def get_value(self, dictionary): # We override the default field access in order to support # lists in HTML forms. @@ -1159,6 +1164,8 @@ def get_value(self, dictionary): def to_internal_value(self, data): if isinstance(data, type('')) or not hasattr(data, '__iter__'): self.fail('not_a_list', input_type=type(data).__name__) + if not self.allow_empty and len(data) == 0: + self.fail('empty') return set([ super(MultipleChoiceField, self).to_internal_value(item) @@ -1263,11 +1270,13 @@ class ListField(Field): child = _UnvalidatedField() initial = [] default_error_messages = { - 'not_a_list': _('Expected a list of items but got type "{input_type}".') + 'not_a_list': _('Expected a list of items but got type "{input_type}".'), + 'empty': _('This list may not be empty.') } def __init__(self, *args, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) + self.allow_empty = kwargs.pop('allow_empty', True) assert not inspect.isclass(self.child), '`child` has not been instantiated.' super(ListField, self).__init__(*args, **kwargs) self.child.bind(field_name='', parent=self) @@ -1287,6 +1296,8 @@ def to_internal_value(self, data): data = html.parse_html_list(data) if isinstance(data, type('')) or not hasattr(data, '__iter__'): 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] def to_representation(self, data): diff --git a/rest_framework/relations.py b/rest_framework/relations.py --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -32,7 +32,7 @@ def __init__(self, pk): # rather than the parent serializer. MANY_RELATION_KWARGS = ( 'read_only', 'write_only', 'required', 'default', 'initial', 'source', - 'label', 'help_text', 'style', 'error_messages' + 'label', 'help_text', 'style', 'error_messages', 'allow_empty' ) @@ -366,9 +366,14 @@ class ManyRelatedField(Field): """ initial = [] default_empty_html = [] + default_error_messages = { + 'not_a_list': _('Expected a list of items but got type "{input_type}".'), + 'empty': _('This list may not be empty.') + } def __init__(self, child_relation=None, *args, **kwargs): self.child_relation = child_relation + self.allow_empty = kwargs.pop('allow_empty', True) assert child_relation is not None, '`child_relation` is a required argument.' super(ManyRelatedField, self).__init__(*args, **kwargs) self.child_relation.bind(field_name='', parent=self) @@ -386,6 +391,11 @@ def get_value(self, dictionary): return dictionary.get(self.field_name, empty) def to_internal_value(self, data): + if isinstance(data, type('')) or not hasattr(data, '__iter__'): + 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_relation.to_internal_value(item) for item in data diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -49,7 +49,7 @@ # rather than the parent serializer. LIST_SERIALIZER_KWARGS = ( 'read_only', 'write_only', 'required', 'default', 'initial', 'source', - 'label', 'help_text', 'style', 'error_messages', + 'label', 'help_text', 'style', 'error_messages', 'allow_empty', 'instance', 'data', 'partial', 'context' ) @@ -493,11 +493,13 @@ class ListSerializer(BaseSerializer): many = True default_error_messages = { - 'not_a_list': _('Expected a list of items but got type "{input_type}".') + 'not_a_list': _('Expected a list of items but got type "{input_type}".'), + 'empty': _('This list may not be empty.') } def __init__(self, *args, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) + self.allow_empty = kwargs.pop('allow_empty', True) assert self.child is not None, '`child` is a required argument.' assert not inspect.isclass(self.child), '`child` has not been instantiated.' super(ListSerializer, self).__init__(*args, **kwargs) @@ -553,6 +555,12 @@ def to_internal_value(self, data): api_settings.NON_FIELD_ERRORS_KEY: [message] }) + if not self.allow_empty and len(data) == 0: + message = self.error_messages['empty'] + raise ValidationError({ + api_settings.NON_FIELD_ERRORS_KEY: [message] + }) + ret = [] errors = []
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1140,6 +1140,27 @@ def test_against_partial_and_full_updates(self): assert field.get_value(QueryDict({})) == rest_framework.fields.empty +class TestEmptyMultipleChoiceField(FieldValues): + """ + Invalid values for `MultipleChoiceField(allow_empty=False)`. + """ + valid_inputs = { + } + invalid_inputs = ( + ([], ['This selection may not be empty.']), + ) + outputs = [ + ] + field = serializers.MultipleChoiceField( + choices=[ + ('consistency', 'Consistency'), + ('availability', 'Availability'), + ('partition', 'Partition tolerance'), + ], + allow_empty=False + ) + + # File serializers... class MockFile: @@ -1233,7 +1254,8 @@ class TestListField(FieldValues): """ valid_inputs = [ ([1, 2, 3], [1, 2, 3]), - (['1', '2', '3'], [1, 2, 3]) + (['1', '2', '3'], [1, 2, 3]), + ([], []) ] invalid_inputs = [ ('not a list', ['Expected a list of items but got type "str".']), @@ -1246,6 +1268,18 @@ class TestListField(FieldValues): field = serializers.ListField(child=serializers.IntegerField()) +class TestEmptyListField(FieldValues): + """ + Values for `ListField` with allow_empty=False flag. + """ + valid_inputs = {} + invalid_inputs = [ + ([], ['This list may not be empty.']) + ] + outputs = {} + field = serializers.ListField(child=serializers.IntegerField(), allow_empty=False) + + class TestUnvalidatedListField(FieldValues): """ Values for `ListField` with no `child` argument.
Add `allow_empty` flag to ListField. Possible that it might be useful to have an `allow_empty` flag that could be set to `False` to disallow empty selections. Would be for `ListField`, `ListSerializer`, `MultipleChoiceField` and `relations` Eg see. #2804.
Reckon this is worth having. Adding a milestone to this to help keep it visible. May later be dropped or deferred if we don't act on it, but this feature request feels like a good candidate given how widely applicable its use is for relatively little extra complexity.
2015-07-16T12:52:25
encode/django-rest-framework
3,165
encode__django-rest-framework-3165
[ "3163" ]
7b21336872d82c74041cdb592c5004a172b7d3a7
diff --git a/rest_framework/filters.py b/rest_framework/filters.py --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -198,4 +198,7 @@ def filter_queryset(self, request, queryset, view): 'model_name': get_model_name(model_cls) } permission = self.perm_format % kwargs - return guardian.shortcuts.get_objects_for_user(user, permission, queryset) + if guardian.VERSION >= (1, 3): + # Maintain behavior compatibility with versions prior to 1.3 + extra = {'accept_global_perms': False} + return guardian.shortcuts.get_objects_for_user(user, permission, queryset, **extra)
DjangoObjectPermissionsFilter broken by guardian 1.3 (devel) The guardian shortcut "get_objects_for_user" uses accept_global_perms=True as default, which means that if you have a group that has view permission for ModelClass, and then filter on the objects, you will get ALL objects. Easy way to fix this is to return guardian.shortcuts.get_objects_for_user(user, permission, queryset, accept_global_perms=False) instead.
2015-07-16T15:46:31
encode/django-rest-framework
3,179
encode__django-rest-framework-3179
[ "3024" ]
6e6fa893e46541219caab4e434bb370aeedff831
diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -14,6 +14,7 @@ from django.utils.translation import ungettext from rest_framework import status +from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList def _force_text_recursive(data): @@ -22,14 +23,20 @@ def _force_text_recursive(data): lazy translation strings into plain text. """ if isinstance(data, list): - return [ + ret = [ _force_text_recursive(item) for item in data ] + if isinstance(data, ReturnList): + return ReturnList(ret, serializer=data.serializer) + return data elif isinstance(data, dict): - return dict([ + ret = dict([ (key, _force_text_recursive(value)) for key, value in data.items() ]) + if isinstance(data, ReturnDict): + return ReturnDict(ret, serializer=data.serializer) + return data return force_text(data) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -204,7 +204,7 @@ def is_valid(self, raise_exception=False): self._errors = {} if self._errors and raise_exception: - raise ValidationError(self._errors) + raise ValidationError(self.errors) return not bool(self._errors) 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 @@ -72,7 +72,7 @@ def __repr__(self): )) def as_form_field(self): - value = force_text(self.value) + value = '' if self.value is None else force_text(self.value) return self.__class__(self._field, value, self.errors, self._prefix) @@ -100,7 +100,7 @@ def as_form_field(self): if isinstance(value, (list, dict)): values[key] = value else: - values[key] = force_text(value) + values[key] = '' if value is None else force_text(value) return self.__class__(self._field, values, self.errors, self._prefix)
diff --git a/tests/test_generics.py b/tests/test_generics.py --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -145,6 +145,16 @@ def test_post_cannot_set_id(self): created = self.objects.get(id=4) self.assertEqual(created.text, 'foobar') + def test_post_error_root_view(self): + """ + POST requests to ListCreateAPIView in HTML should include a form error. + """ + data = {'text': 'foobar' * 100} + request = factory.post('/', data, HTTP_ACCEPT='text/html') + response = self.view(request).render() + expected_error = '<span class="help-block">Ensure this field has no more than 100 characters.</span>' + self.assertIn(expected_error, response.rendered_content.decode('utf-8')) + EXPECTED_QUERIES_FOR_PUT = 3 if django.VERSION < (1, 6) else 2 @@ -282,6 +292,16 @@ def test_patch_cannot_create_an_object(self): self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertFalse(self.objects.filter(id=999).exists()) + def test_put_error_instance_view(self): + """ + Incorrect PUT requests in HTML should include a form error. + """ + data = {'text': 'foobar' * 100} + request = factory.put('/', data, HTTP_ACCEPT='text/html') + response = self.view(request, pk=1).render() + expected_error = '<span class="help-block">Ensure this field has no more than 100 characters.</span>' + self.assertIn(expected_error, response.rendered_content.decode('utf-8')) + class TestFKInstanceView(TestCase): def setUp(self):
Keeping values in browsable api on error Values entered in the browsable api list view html form are currently cleared on an error. This means that a user would have to re-enter the entirety of what they put in before. Instead, the values should be kept so the user can remedy the incorrect fields and keep what they have already entered. **Steps to reproduce:** 1. Navigate to browsable api list view page. 2. Enter some values into the html form fields, but leave some empty or invalid. 3. Post the form. 4. Error is produced. This also occurs on detail view even though the form is already prefilled with information.
Yup clearly an issue that's worth addressing. Thinking about tackling this one next. It'd definitely make using the browsable api way better. First attempt at this. This is just making sure we pass data to the serializers used in `get_raw_data_form()` and `get_rendered_html_form()`. As you can see the `username` is missing from the raw data form and is `None` in the HTML form because since the serializer has an error `serializer.data` defaults to `serializer.get_initial()` which excludes fields with `empty` values. Ideas on how to proceed are welcomed. <img width="988" alt="screen shot 2015-07-18 at 8 00 42 am" src="https://cloud.githubusercontent.com/assets/83319/8761517/24b75cd6-2d23-11e5-81fe-a4ddea4438a5.png"> <img width="973" alt="screen shot 2015-07-18 at 8 00 51 am" src="https://cloud.githubusercontent.com/assets/83319/8761518/24ba9dc4-2d23-11e5-8c8c-8a837c28b193.png">
2015-07-23T13:32:10
encode/django-rest-framework
3,199
encode__django-rest-framework-3199
[ "2886" ]
1b3b01e042920e13934608d36da93a4d02dd95e9
diff --git a/rest_framework/compat.py b/rest_framework/compat.py --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -203,41 +203,6 @@ def __init__(self, *args, **kwargs): View.http_method_names = View.http_method_names + ['patch'] - -try: - # In 1.5 the test client uses force_bytes - from django.utils.encoding import force_bytes as force_bytes_or_smart_bytes -except ImportError: - # In 1.4 the test client just uses smart_str - from django.utils.encoding import smart_str as force_bytes_or_smart_bytes - - -# RequestFactory only provides `generic` from 1.5 onwards -if django.VERSION >= (1, 5): - from django.test.client import RequestFactory -else: - from django.test.client import RequestFactory as DjangoRequestFactory - - class RequestFactory(DjangoRequestFactory): - def generic(self, method, path, - data='', content_type='application/octet-stream', **extra): - parsed = _urlparse(path) - data = force_bytes_or_smart_bytes(data, settings.DEFAULT_CHARSET) - r = { - 'PATH_INFO': self._get_path(parsed), - 'QUERY_STRING': force_text(parsed[4]), - 'REQUEST_METHOD': six.text_type(method), - } - if data: - r.update({ - 'CONTENT_LENGTH': len(data), - 'CONTENT_TYPE': six.text_type(content_type), - 'wsgi.input': FakePayload(data), - }) - r.update(extra) - return self.request(**r) - - # Markdown is optional try: import markdown
diff --git a/rest_framework/test.py b/rest_framework/test.py --- a/rest_framework/test.py +++ b/rest_framework/test.py @@ -8,12 +8,12 @@ from django.conf import settings from django.test import testcases from django.test.client import Client as DjangoClient +from django.test.client import RequestFactory as DjangoRequestFactory from django.test.client import ClientHandler from django.utils import six +from django.utils.encoding import force_bytes from django.utils.http import urlencode -from rest_framework.compat import RequestFactory as DjangoRequestFactory -from rest_framework.compat import force_bytes_or_smart_bytes from rest_framework.settings import api_settings @@ -47,7 +47,7 @@ def _encode_data(self, data, format=None, content_type=None): if content_type: # Content type specified explicitly, treat data as a raw bytestring - ret = force_bytes_or_smart_bytes(data, settings.DEFAULT_CHARSET) + ret = force_bytes(data, settings.DEFAULT_CHARSET) else: format = format or self.default_format
Resolve deprecation warnings with Django 1.8 RemovedInDjango19Warning: Loading the `url` tag from the `future` library is deprecated and will be removed in Django 1.9. Use the default `url` tag instead. base.html {% load url from future %}
This is blocked by the support of Django < 1.5 Okay, lets plan to resolve this at the same time as we drop support for 1.4. I have no issue with us bumping up some versions in our next major release. Agreed. Not sure if this was addressed already or not: ``` python /usr/local/lib/python2.7/site-packages/rest_framework/settings.py:23: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9. ``` > Not sure if this was addressed already or not: That was addressed in https://github.com/tomchristie/django-rest-framework/pull/2567. @kevin-brown Thanks!
2015-07-30T14:15:44
encode/django-rest-framework
3,202
encode__django-rest-framework-3202
[ "2804" ]
aa3f844b3d9d6f2bd192c7a711eca65dcbe2583e
diff --git a/rest_framework/relations.py b/rest_framework/relations.py --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -64,6 +64,7 @@ def __init__(self, **kwargs): 'when setting read_only=`True`.' ) kwargs.pop('many', None) + kwargs.pop('allow_empty', None) super(RelatedField, self).__init__(**kwargs) def __new__(cls, *args, **kwargs): 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 @@ -225,6 +225,7 @@ def get_relation_kwargs(field_name, relation_info): # If this field is read-only, then return early. # No further keyword arguments are valid. return kwargs + if model_field.has_default() or model_field.null: kwargs['required'] = False if model_field.null: @@ -234,6 +235,8 @@ def get_relation_kwargs(field_name, relation_info): if getattr(model_field, 'unique', False): validator = UniqueValidator(queryset=model_field.model._default_manager) kwargs['validators'] = kwargs.get('validators', []) + [validator] + if to_many and not model_field.blank: + kwargs['allow_empty'] = False return 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 @@ -395,7 +395,7 @@ class Meta: id = IntegerField(label='ID', read_only=True) foreign_key = PrimaryKeyRelatedField(queryset=ForeignKeyTargetModel.objects.all()) one_to_one = PrimaryKeyRelatedField(queryset=OneToOneTargetModel.objects.all(), validators=[<UniqueValidator(queryset=RelationalModel.objects.all())>]) - many_to_many = PrimaryKeyRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all()) + many_to_many = PrimaryKeyRelatedField(allow_empty=False, many=True, queryset=ManyToManyTargetModel.objects.all()) through = PrimaryKeyRelatedField(many=True, read_only=True) """) self.assertEqual(unicode_repr(TestSerializer()), expected) @@ -434,7 +434,7 @@ class Meta: url = HyperlinkedIdentityField(view_name='relationalmodel-detail') foreign_key = HyperlinkedRelatedField(queryset=ForeignKeyTargetModel.objects.all(), view_name='foreignkeytargetmodel-detail') one_to_one = HyperlinkedRelatedField(queryset=OneToOneTargetModel.objects.all(), validators=[<UniqueValidator(queryset=RelationalModel.objects.all())>], view_name='onetoonetargetmodel-detail') - many_to_many = HyperlinkedRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all(), view_name='manytomanytargetmodel-detail') + many_to_many = HyperlinkedRelatedField(allow_empty=False, many=True, queryset=ManyToManyTargetModel.objects.all(), view_name='manytomanytargetmodel-detail') through = HyperlinkedRelatedField(many=True, read_only=True, view_name='throughtargetmodel-detail') """) self.assertEqual(unicode_repr(TestSerializer()), expected)
M2M model field without `blank=True` should map to a serializer relationship with `allow_empty=False`. The Django 1.8 system check framework displays the warning [fields.W340](https://docs.djangoproject.com/en/1.8/ref/checks/#related-fields) when the `null` parameter is defined on a `ManyToManyField`, since it has no effect. This `null` field affects on whether a related field in a model serializer is considered required or not. We can see it [here](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/field_mapping.py#L226-L227). From my point of view, this behavior is correct for a `ForeignKey` but not for a `ManyToManyField`, that should be considered not required by default. Adding the var `to_many` to the condition on the aforementioned code might do the trick.
See test in #2674. +1 > should be considered not required by default. For both this and #2674 I'm unsure _exactly_ what behavior you're expecting. M2M fields default to required, because the input field itself is required, although _it may be an empty list_. Are you expecting to be able to provide `null` as the input for the M2M field, or are you seeing an issue when providing an empty list? As currently described the existing behavior seems correct to me - require the input, but allow it to be an empty list. See my answer in #2674. If `required=True` (the default) the framework should not accept empty lists/arrays. This is because the framework should behave like Django forms and here we got an error if we try to send an empty list to a required form field. (The other point (not this issue) is that the required flag should be controlled by the model field option `blank` which is not the case at the moment.) I agree with https://github.com/tomchristie/django-rest-framework/pull/2674#issuecomment-105479180 +1 Retitled more appropriately. The behavior that's being requested here as far as I understand it is to mirror Django's blank model field -> required input. I'm not 100% convinced that we want `ManyToManyField(Something)` to always require >= 1 entry and `ManyToManyField(Something, blank=True)` to allow empty lists, and I'd really like to see that discussion pushed to the mailing list, but _certainly_ we should at least allow either case to be specified. If we do change the behavior we should do so in a major version bump and call it out prominently. Requires #2250 as a prerequisite. +1 Accepting this, though given the potential for backwards incompatibility it's probably a good idea if we push it in 3.2.0, to allow us to call it out. Also note that `allow_empty` is now a valid flag. You can workaround the behavior here by using `extra_kwargs = {'my_field': {'allow_empty': False}}`.
2015-07-30T16:04:57
encode/django-rest-framework
3,225
encode__django-rest-framework-3225
[ "1533" ]
9a778793f8dc97e0b76070e1e005514b8717a03d
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -108,6 +108,53 @@ def set_value(dictionary, keys, value): dictionary[keys[-1]] = value +def to_choices_dict(choices): + """ + Convert choices into key/value dicts. + + pairwise_choices([1]) -> {1: 1} + pairwise_choices([(1, '1st'), (2, '2nd')]) -> {1: '1st', 2: '2nd'} + pairwise_choices([('Group', ((1, '1st'), 2))]) -> {'Group': {1: '1st', 2: '2nd'}} + """ + # Allow single, paired or grouped choices style: + # choices = [1, 2, 3] + # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')] + # choices = [('Category', ((1, 'First'), (2, 'Second'))), (3, 'Third')] + ret = OrderedDict() + for choice in choices: + if (not isinstance(choice, (list, tuple))): + # single choice + ret[choice] = choice + else: + key, value = choice + if isinstance(value, (list, tuple)): + # grouped choices (category, sub choices) + ret[key] = to_choices_dict(value) + else: + # paired choice (key, display value) + ret[key] = value + return ret + + +def flatten_choices_dict(choices): + """ + Convert a group choices dict into a flat dict of choices. + + flatten_choices({1: '1st', 2: '2nd'}) -> {1: '1st', 2: '2nd'} + flatten_choices({'Group': {1: '1st', 2: '2nd'}}) -> {1: '1st', 2: '2nd'} + """ + ret = OrderedDict() + for key, value in choices.items(): + if isinstance(value, dict): + # grouped choices (category, sub choices) + for sub_key, sub_value in value.items(): + ret[sub_key] = sub_value + else: + # choice (key, display value) + ret[key] = value + return ret + + class CreateOnlyDefault(object): """ This class may be used to provide default values that are only used @@ -1111,17 +1158,8 @@ class ChoiceField(Field): } def __init__(self, choices, **kwargs): - # Allow either single or paired choices style: - # choices = [1, 2, 3] - # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')] - pairs = [ - isinstance(item, (list, tuple)) and len(item) == 2 - for item in choices - ] - if all(pairs): - self.choices = OrderedDict([(key, display_value) for key, display_value in choices]) - else: - self.choices = OrderedDict([(item, item) for item in choices]) + self.grouped_choices = to_choices_dict(choices) + self.choices = flatten_choices_dict(self.grouped_choices) # Map the string representation of choices to the underlying value. # Allows us to deal with eg. integer choices while supporting either @@ -1148,6 +1186,38 @@ def to_representation(self, value): return value return self.choice_strings_to_values.get(six.text_type(value), value) + def iter_options(self): + """ + Helper method for use with templates rendering select widgets. + """ + class StartOptionGroup(object): + start_option_group = True + end_option_group = False + + def __init__(self, label): + self.label = label + + class EndOptionGroup(object): + start_option_group = False + end_option_group = True + + class Option(object): + start_option_group = False + end_option_group = False + + def __init__(self, value, display_text): + self.value = value + self.display_text = display_text + + for key, value in self.grouped_choices.items(): + if isinstance(value, dict): + yield StartOptionGroup(label=key) + for sub_key, sub_value in value.items(): + yield Option(value=sub_key, display_text=sub_value) + yield EndOptionGroup() + else: + yield Option(value=key, display_text=value) + class MultipleChoiceField(ChoiceField): default_error_messages = { 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 @@ -107,10 +107,10 @@ def get_field_kwargs(field_name, model_field): isinstance(model_field, models.TextField)): kwargs['allow_blank'] = True - if model_field.flatchoices: + if model_field.choices: # If this model field contains choices, then return early. # Further keyword arguments are not valid. - kwargs['choices'] = model_field.flatchoices + kwargs['choices'] = model_field.choices return kwargs # Ensure that max_length is passed explicitly as a keyword arg,
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1107,6 +1107,34 @@ def test_allow_null(self): output = field.run_validation(None) assert output is None + def test_iter_options(self): + """ + iter_options() should return a list of options and option groups. + """ + field = serializers.ChoiceField( + choices=[ + ('Numbers', ['integer', 'float']), + ('Strings', ['text', 'email', 'url']), + 'boolean' + ] + ) + items = list(field.iter_options()) + + assert items[0].start_option_group + assert items[0].label == 'Numbers' + assert items[1].value == 'integer' + assert items[2].value == 'float' + assert items[3].end_option_group + + assert items[4].start_option_group + assert items[4].label == 'Strings' + assert items[5].value == 'text' + assert items[6].value == 'email' + assert items[7].value == 'url' + assert items[8].end_option_group + + assert items[9].value == 'boolean' + class TestChoiceFieldWithType(FieldValues): """ @@ -1153,6 +1181,66 @@ class TestChoiceFieldWithListChoices(FieldValues): field = serializers.ChoiceField(choices=('poor', 'medium', 'good')) +class TestChoiceFieldWithGroupedChoices(FieldValues): + """ + Valid and invalid values for a `Choice` field that uses a grouped list for the + choices, rather than a list of pairs of (`value`, `description`). + """ + valid_inputs = { + 'poor': 'poor', + 'medium': 'medium', + 'good': 'good', + } + invalid_inputs = { + 'awful': ['"awful" is not a valid choice.'] + } + outputs = { + 'good': 'good' + } + field = serializers.ChoiceField( + choices=[ + ( + 'Category', + ( + ('poor', 'Poor quality'), + ('medium', 'Medium quality'), + ), + ), + ('good', 'Good quality'), + ] + ) + + +class TestChoiceFieldWithMixedChoices(FieldValues): + """ + Valid and invalid values for a `Choice` field that uses a single paired or + grouped. + """ + valid_inputs = { + 'poor': 'poor', + 'medium': 'medium', + 'good': 'good', + } + invalid_inputs = { + 'awful': ['"awful" is not a valid choice.'] + } + outputs = { + 'good': 'good' + } + field = serializers.ChoiceField( + choices=[ + ( + 'Category', + ( + ('poor', 'Poor quality'), + ), + ), + 'medium', + ('good', 'Good quality'), + ] + ) + + class TestMultipleChoiceField(FieldValues): """ Valid and invalid values for `MultipleChoiceField`. 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 @@ -181,7 +181,7 @@ class Meta: null_field = IntegerField(allow_null=True, required=False) default_field = IntegerField(required=False) descriptive_field = IntegerField(help_text='Some help text', label='A label') - choices_field = ChoiceField(choices=[('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')]) + choices_field = ChoiceField(choices=(('red', 'Red'), ('blue', 'Blue'), ('green', 'Green'))) """) if six.PY2: # This particular case is too awkward to resolve fully across diff --git a/tests/test_validation.py b/tests/test_validation.py --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -141,6 +141,8 @@ def test_max_value_validation_fail(self): self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) +# regression tests for issue: 1533 + class TestChoiceFieldChoicesValidate(TestCase): CHOICES = [ (0, 'Small'), @@ -148,6 +150,8 @@ class TestChoiceFieldChoicesValidate(TestCase): (2, 'Large'), ] + SINGLE_CHOICES = [0, 1, 2] + CHOICES_NESTED = [ ('Category', ( (1, 'First'), @@ -157,6 +161,15 @@ class TestChoiceFieldChoicesValidate(TestCase): (4, 'Fourth'), ] + MIXED_CHOICES = [ + ('Category', ( + (1, 'First'), + (2, 'Second'), + )), + 3, + (4, 'Fourth'), + ] + def test_choices(self): """ Make sure a value for choices works as expected. @@ -168,6 +181,39 @@ def test_choices(self): except serializers.ValidationError: self.fail("Value %s does not validate" % str(value)) + def test_single_choices(self): + """ + Make sure a single value for choices works as expected. + """ + f = serializers.ChoiceField(choices=self.SINGLE_CHOICES) + value = self.SINGLE_CHOICES[0] + try: + f.to_internal_value(value) + except serializers.ValidationError: + self.fail("Value %s does not validate" % str(value)) + + def test_nested_choices(self): + """ + Make sure a nested value for choices works as expected. + """ + f = serializers.ChoiceField(choices=self.CHOICES_NESTED) + value = self.CHOICES_NESTED[0][1][0][0] + try: + f.to_internal_value(value) + except serializers.ValidationError: + self.fail("Value %s does not validate" % str(value)) + + def test_mixed_choices(self): + """ + Make sure mixed values for choices works as expected. + """ + f = serializers.ChoiceField(choices=self.MIXED_CHOICES) + value = self.MIXED_CHOICES[1] + try: + f.to_internal_value(value) + except serializers.ValidationError: + self.fail("Value %s does not validate" % str(value)) + class RegexSerializer(serializers.Serializer): pin = serializers.CharField(
Support grouped choices. **Update from @tomchristie** **Closing off some related tickets and rolling them into this one...** - [ ] Include core support. - [ ] Render in browsable API. - #1636 - [ ] Display as metadata in response to `OPTIONS` requests. - #3101 --- One of our models has a Choicefield with following choices: ``` TYPE_CHOICES = ( ('Default', ( (1, 'Option 1'), (2, 'Option 2'), (3, 'Option 3'))), (4, 'Option 4')) ``` Now in the serializer if i have something _self.field.from_native(3)_, we get a ValidationError. Upon inspection of the DRF code we found that logic for valid_value method in the Choicefield is incorrect if you have nested sets with integer keys. ``` def valid_value(self, value): """ Check to see if the provided value is a valid choice. """ for k, v in self.choices: if isinstance(v, (list, tuple)): # This is an optgroup, so look inside the group for options for k2, v2 in v: if value == smart_text(k2): return True else: if value == smart_text(k) or value == k: return True return False ``` Line _if value == smart_text(k2):_ should really be: _if value == smart_text(k2) or value == k2:_
Yup, that seems valid to me. DjangoCon sprint guidance - check out Django's docs on grouped choices. Demonstrate to yourself that the browsable API in REST framework does not currently support them. Make a pull request with the fix, including a screenshot of before and after. Ensure that `OPTIONS` requests continue to function identically before and after for endpoints that include choice fields. I'll take a look at solving this at the DjangoCon Sprints today/tomorrow. Ace. Tom, Thanks for the guidance on this. However I don't believe this issue affects the browsable API because integer values are always set as strings in the <option> tag. As a result of this, they are POSTed as strings, and appear as such in the request QueryDict. For this reason, the condition `value == smart_text(k2)` actually evaluates as `True` because smart_text() effectively typecasts `k2` as a string, matching the string sent by the browser and causing validation to succeed in this case. However, using curl the issue is easily repeatable, e.g.: `curl -H "Content-Type: application/json" -d '{"this_is_an_integer_field": 1 }' http://127.0.0.1:8000/api/v1/widgets/` causes validation to fail unexpectedly as reported by @ameyc. For this reason on the pull request I'll just include a targeted unit test that demonstrates the main failure case and succeeds with the change. Looking at the test suite structure I'm planning to add it to test_validation.py. Good for you? Chris Sounds okay. This appears to be broken again in the latest release (3.1.3). The test `test_nested_choices` was commented in https://github.com/tomchristie/django-rest-framework/commit/de301f3b6647e1c79a506405a88071ef977418d1#diff-92133d9c634f57bfbbad89754f6713af and then removed in https://github.com/tomchristie/django-rest-framework/commit/c8764de7881f419c9269913ec3654fc1d904ab2e#diff-92133d9c634f57bfbbad89754f6713af - it is worth noting that [`CHOICES_NESTED`](https://github.com/tomchristie/django-rest-framework/blob/3.1.3/tests/test_validation.py#L148-L155) used by the test is still there. Has support for grouped choices been dropped? I will take a look at fixing this
2015-08-06T10:44:02
encode/django-rest-framework
3,238
encode__django-rest-framework-3238
[ "3235" ]
981265fc484ab2e81bc43a8e5505feba3e30c9bd
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1384,7 +1384,7 @@ def get_value(self, dictionary): # lists in HTML forms. if html.is_html_input(dictionary): val = dictionary.getlist(self.field_name, []) - if len(val) > 1: + if len(val) > 0: # Support QueryDict lists in HTML input. return val return html.parse_html_list(dictionary, prefix=self.field_name)
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -317,6 +317,14 @@ class TestSerializer(serializers.Serializer): assert serializer.is_valid() assert serializer.validated_data == {'scores': [1, 3]} + def test_querydict_list_input_only_one_input(self): + class TestSerializer(serializers.Serializer): + scores = serializers.ListField(child=serializers.IntegerField()) + + serializer = TestSerializer(data=QueryDict('scores=1&')) + assert serializer.is_valid() + assert serializer.validated_data == {'scores': [1]} + class TestCreateOnlyDefault: def setup(self):
ListField seems to miss single values The [get_value](https://github.com/tomchristie/django-rest-framework/blob/37b4d4248895e1583861af863a3906f582e4cd0c/rest_framework/fields.py#L1382) method of `ListField` seems to use `if len(val) > 1:` where I believe it ought to be `if len(val) >= 1:` or `if len(val) > 0:` In a Django `QueryDict`, for example, `getlist` will yield a list of 1 item even if there is _only_ one item. This seems to miss all the paths currently defined. By way of example, here's a quick sketch of what I believe is demonstrable of the issue I think we're having: ``` >>> from rest_framework.fields import ListField >>> from django.http import QueryDict >>> qs = QueryDict('foo=1') [u'1'] >>> qs2 = QueryDict('foo=1&foo=2') [u'1', u'2'] >>> field = ListField() >>> field.field_name = 'foo' # for the purposes of getting the prefix right >>> field.get_value(qs2) [u'1', u'2'] >>> field.get_value(qs) [] ``` I'd expect the last, empty list `[]` to be `[u'1']` This is against drf `3.2.0` and Django `1.8.x`
What's the behavior against 3.1.3? Would you be able to create a failing test case pull request for this? with `pip install djangorestframework==3.1.3` and the same code, both querydicts (`qs`, `qs2`) yield `[]` when thrown through `get_value`, so the new one is _better_, but not quite what I'd hope for. I ought to be able to produce a PR for it, if testing at this level, rather than a instrumenting from a higher level, is acceptable.
2015-08-07T10:47:43
encode/django-rest-framework
3,241
encode__django-rest-framework-3241
[ "3236" ]
0cbfbc27d838730f8238b3fd2d973369ca81d379
diff --git a/rest_framework/response.py b/rest_framework/response.py --- a/rest_framework/response.py +++ b/rest_framework/response.py @@ -10,6 +10,8 @@ from django.utils import six from django.utils.six.moves.http_client import responses +from rest_framework.serializers import Serializer + class Response(SimpleTemplateResponse): """ @@ -28,6 +30,15 @@ def __init__(self, data=None, status=None, For example being set automatically by the `APIView`. """ super(Response, self).__init__(None, status=status) + + if isinstance(data, Serializer): + msg = ( + 'You passed a Serializer instance as data, but ' + 'probably meant to pass serialized `.data` or ' + '`.error`. representation.' + ) + raise AssertionError(msg) + self.data = data self.template_name = template_name self.exception = exception
Response should raise an error if passed a serializer instance We should guard against accidental `Response(serializer)`, with an error stating "You probably meant serializer.data or serializer.errors".
2015-08-07T17:13:39
encode/django-rest-framework
3,300
encode__django-rest-framework-3300
[ "3292" ]
dd850df1d886352779659748478dec6f5c9d86da
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1381,7 +1381,13 @@ class ListField(Field): def __init__(self, *args, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) self.allow_empty = kwargs.pop('allow_empty', True) + assert not inspect.isclass(self.child), '`child` has not been instantiated.' + assert self.child.source is None, ( + "The `source` argument is not meaningful when applied to a `child=` field. " + "Remove `source=` from the field declaration." + ) + super(ListField, self).__init__(*args, **kwargs) self.child.bind(field_name='', parent=self) @@ -1424,7 +1430,13 @@ class DictField(Field): def __init__(self, *args, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) + assert not inspect.isclass(self.child), '`child` has not been instantiated.' + assert self.child.source is None, ( + "The `source` argument is not meaningful when applied to a `child=` field. " + "Remove `source=` from the field declaration." + ) + super(DictField, self).__init__(*args, **kwargs) self.child.bind(field_name='', parent=self)
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1416,6 +1416,15 @@ class TestListField(FieldValues): ] field = serializers.ListField(child=serializers.IntegerField()) + def test_no_source_on_child(self): + with pytest.raises(AssertionError) as exc_info: + serializers.ListField(child=serializers.IntegerField(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." + ) + class TestEmptyListField(FieldValues): """ @@ -1461,6 +1470,15 @@ class TestDictField(FieldValues): ] field = serializers.DictField(child=serializers.CharField()) + def test_no_source_on_child(self): + with pytest.raises(AssertionError) as exc_info: + serializers.DictField(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." + ) + class TestUnvalidatedDictField(FieldValues): """
Raise error when `source=` use on a child, not a field. I am trying to serialise a related model as a list using their names. I can't use a StringRelatedField as the `__str__` representation of my model doesn't match the desired output. My approach was to use a ListField specifying a child with a source attribute, such as child=StringField(source='name'), but the inner source is being ignored. There is no reference in the documentation of this being an issue. It only mentions that ListFields validate lists of objects. Maybe this is not the intended use case but it is not mentioned in the docs, although seems reasonable to me. ``` python class A(models.Model): name = models.CharField(max_length=72) class B(models.Model): name = models.CharField(max_length=72, unique=True) field_I_care_about_but_not_users = models.IntegerField() a = models.ForeignKey(A, related_name='related_bs') def __str__(self): return field_I_care_about_but_not_users class ASerializer(serializers.ModelSerializer): bs = serializers.ListField( source='related_bs', child=serializers.CharField(source='name')) class Meta: model = A fields = ('name', 'bs') ``` When using `ASerializer` I get `field_I_care_about_but_not_users` in the list instead of `name`. I know I can override `to_representation`, but it surprised me when it didn't work.
Specifying source in that situation doesn't have any meaning. Normally you're using it to associate a field with a different attribute on the instance than its field name, but when used as a child in a list or other composite element its redundant. We could consider raising an error in this use-case. I'd rather not go into it in the docs, as I think it'd likely be noise rather than actually helpful. Have retitled with what I think would be an appropriate action for this. Thanks for clarifying this.
2015-08-19T15:39:21
encode/django-rest-framework
3,313
encode__django-rest-framework-3313
[ "3309" ]
490f0c9f3426142aa5b7af50f8f9f01dc1d3fd08
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -156,7 +156,7 @@ def flatten_choices_dict(choices): return ret -def iter_options(grouped_choices): +def iter_options(grouped_choices, cutoff=None, cutoff_text=None): """ Helper function for options and option groups in templates. """ @@ -175,18 +175,32 @@ class Option(object): start_option_group = False end_option_group = False - def __init__(self, value, display_text): + def __init__(self, value, display_text, disabled=False): self.value = value self.display_text = display_text + self.disabled = disabled + + count = 0 for key, value in grouped_choices.items(): + if cutoff and count >= cutoff: + break + if isinstance(value, dict): yield StartOptionGroup(label=key) for sub_key, sub_value in value.items(): + if cutoff and count >= cutoff: + break yield Option(value=sub_key, display_text=sub_value) + count += 1 yield EndOptionGroup() else: yield Option(value=key, display_text=value) + count += 1 + + if cutoff and count >= cutoff and cutoff_text: + cutoff_text = cutoff_text.format(count=cutoff) + yield Option(value='n/a', display_text=cutoff_text, disabled=True) class CreateOnlyDefault(object): @@ -1188,10 +1202,14 @@ class ChoiceField(Field): default_error_messages = { 'invalid_choice': _('"{input}" is not a valid choice.') } + html_cutoff = None + html_cutoff_text = _('More than {count} items...') def __init__(self, choices, **kwargs): self.grouped_choices = to_choices_dict(choices) self.choices = flatten_choices_dict(self.grouped_choices) + self.html_cutoff = kwargs.pop('html_cutoff', self.html_cutoff) + self.html_cutoff_text = kwargs.pop('html_cutoff_text', self.html_cutoff_text) # Map the string representation of choices to the underlying value. # Allows us to deal with eg. integer choices while supporting either @@ -1222,7 +1240,11 @@ def iter_options(self): """ Helper method for use with templates rendering select widgets. """ - return iter_options(self.grouped_choices) + return iter_options( + self.grouped_choices, + cutoff=self.html_cutoff, + cutoff_text=self.html_cutoff_text + ) class MultipleChoiceField(ChoiceField): diff --git a/rest_framework/relations.py b/rest_framework/relations.py --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -54,9 +54,13 @@ def __init__(self, pk): class RelatedField(Field): queryset = None + html_cutoff = 1000 + html_cutoff_text = _('More than {count} items...') def __init__(self, **kwargs): self.queryset = kwargs.pop('queryset', self.queryset) + self.html_cutoff = kwargs.pop('html_cutoff', self.html_cutoff) + self.html_cutoff_text = kwargs.pop('html_cutoff_text', self.html_cutoff_text) assert self.queryset is not None or kwargs.get('read_only', None), ( 'Relational field must provide a `queryset` argument, ' 'or set read_only=`True`.' @@ -158,7 +162,11 @@ def grouped_choices(self): return self.choices def iter_options(self): - return iter_options(self.grouped_choices) + return iter_options( + self.grouped_choices, + cutoff=self.html_cutoff, + cutoff_text=self.html_cutoff_text + ) def display_value(self, instance): return six.text_type(instance) @@ -415,10 +423,15 @@ class ManyRelatedField(Field): 'not_a_list': _('Expected a list of items but got type "{input_type}".'), 'empty': _('This list may not be empty.') } + html_cutoff = 1000 + html_cutoff_text = _('More than {count} items...') def __init__(self, child_relation=None, *args, **kwargs): self.child_relation = child_relation self.allow_empty = kwargs.pop('allow_empty', True) + self.html_cutoff = kwargs.pop('html_cutoff', self.html_cutoff) + self.html_cutoff_text = kwargs.pop('html_cutoff_text', self.html_cutoff_text) + assert child_relation is not None, '`child_relation` is a required argument.' super(ManyRelatedField, self).__init__(*args, **kwargs) self.child_relation.bind(field_name='', parent=self) @@ -469,4 +482,8 @@ def grouped_choices(self): return self.choices def iter_options(self): - return iter_options(self.grouped_choices) + return iter_options( + self.grouped_choices, + cutoff=self.html_cutoff, + cutoff_text=self.html_cutoff_text + )
Limit select dropdowns. Related fields with many possible values will render into select dropdowns with potentially 1000's+++ rows. This will stop the page from rendering and leave the end user at a loss. We should be more graceful here, and also consider ajax-loaded widgets.
A default setting of 500 or 1000 would go a long way towards addressing this. On large tables, a dropdown is kind of useful over a few hundred anyways. Thanks! Yup, that'd certainly be a good start!... Another option is to implement something similar to Django's raw_id_field: https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields Or django-extensions' ForeignKeyAutocompleteAdmin: https://django-extensions.readthedocs.org/en/latest/admin_extensions.html#current-admin-extensions Ideally, `raw_id` would be the default to avoid this problems from the start :) Same goes for the Django Admin. I'm going to toss the idea of using [Select2](http://select2.github.io/) out there. - It's designed to be a replacement for `<select>` boxes that supports searching - It has support for pulling results from remote data sources There are a few Django integrations that may be useful to build from - https://github.com/asyncee/django-easy-select2 - Pros - Uses the newer version of Select2 (4.0.0) - Cons - Not designed (out of the box) to pull results from AJAX - https://github.com/applegrew/django-select2 - Pros - Has views for populating results using AJAX - Cons - Still uses the older version of Select2 (3.5.2) Considering we already have the API set up, and we aren't tied to Django forms, it would probably be easier to not use a third party app for integrating it. _**Disclaimer:** I'm the active maintainer of Select2._
2015-08-21T09:54:00
encode/django-rest-framework
3,315
encode__django-rest-framework-3315
[ "2180" ]
86470b7813d891890241149928d4679a3d2c92f6
diff --git a/rest_framework/compat.py b/rest_framework/compat.py --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -77,6 +77,26 @@ def distinct(queryset, base): except ImportError: django_filters = None + +# django-crispy-forms is optional +try: + import crispy_forms +except ImportError: + crispy_forms = None + + +if django.VERSION >= (1, 6): + def clean_manytomany_helptext(text): + return text +else: + # Up to version 1.5 many to many fields automatically suffix + # the `help_text` attribute with hardcoded text. + def clean_manytomany_helptext(text): + if text.endswith(' Hold down "Control", or "Command" on a Mac, to select more than one.'): + text = text[:-69] + return text + + # Django-guardian is optional. Import only if guardian is in INSTALLED_APPS # Fixes (#1712). We keep the try/except for the test suite. guardian = None diff --git a/rest_framework/filters.py b/rest_framework/filters.py --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -7,14 +7,57 @@ import operator from functools import reduce +from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import models +from django.template import Context, loader from django.utils import six +from django.utils.translation import ugettext_lazy as _ -from rest_framework.compat import distinct, django_filters, guardian +from rest_framework.compat import ( + crispy_forms, distinct, django_filters, guardian +) from rest_framework.settings import api_settings -FilterSet = django_filters and django_filters.FilterSet or None +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): @@ -34,6 +77,7 @@ class DjangoFilterBackend(BaseFilterBackend): A filter backend that uses django-filter. """ default_filter_set = FilterSet + template = filter_template def __init__(self): assert django_filters, 'Using DjangoFilterBackend, but django-filter is not installed' @@ -55,7 +99,7 @@ def get_filter_class(self, view, queryset=None): return filter_class if filter_fields: - class AutoFilterSet(self.default_filter_set): + class AutoFilterSet(FilterSet): class Meta: model = queryset.model fields = filter_fields @@ -72,10 +116,20 @@ def filter_queryset(self, request, queryset, view): return queryset + def to_html(self, request, queryset, view): + cls = self.get_filter_class(view, queryset) + filter_instance = cls(request.query_params, queryset=queryset) + context = Context({ + 'filter': filter_instance + }) + template = loader.get_template(self.template) + return template.render(context) + class SearchFilter(BaseFilterBackend): # The URL query parameter used for the search. search_param = api_settings.SEARCH_PARAM + template = 'rest_framework/filters/search.html' def get_search_terms(self, request): """ @@ -99,7 +153,6 @@ def construct_search(self, field_name): def filter_queryset(self, request, queryset, view): search_fields = getattr(view, 'search_fields', None) - search_terms = self.get_search_terms(request) if not search_fields or not search_terms: @@ -123,11 +176,25 @@ def filter_queryset(self, request, queryset, view): # in the resulting queryset. return distinct(queryset, base) + def to_html(self, request, queryset, view): + if not getattr(view, 'search_fields', None): + return '' + + term = self.get_search_terms(request) + term = term[0] if term else '' + context = Context({ + 'param': self.search_param, + 'term': term + }) + template = loader.get_template(self.template) + return template.render(context) + class OrderingFilter(BaseFilterBackend): # The URL query parameter used for the ordering. ordering_param = api_settings.ORDERING_PARAM ordering_fields = None + template = 'rest_framework/filters/ordering.html' def get_ordering(self, request, queryset, view): """ @@ -153,7 +220,7 @@ def get_default_ordering(self, view): return (ordering,) return ordering - def remove_invalid_fields(self, queryset, fields, view): + def get_valid_fields(self, queryset, view): valid_fields = getattr(view, 'ordering_fields', self.ordering_fields) if valid_fields is None: @@ -164,15 +231,30 @@ def remove_invalid_fields(self, queryset, fields, view): "'serializer_class' or 'ordering_fields' attribute.") raise ImproperlyConfigured(msg % self.__class__.__name__) valid_fields = [ - field.source or field_name + (field.source or field_name, field.label) for field_name, field in serializer_class().fields.items() - if not getattr(field, 'write_only', False) + if not getattr(field, 'write_only', False) and not field.source == '*' ] elif valid_fields == '__all__': # View explicitly allows filtering on any model field - valid_fields = [field.name for field in queryset.model._meta.fields] - valid_fields += queryset.query.aggregates.keys() + valid_fields = [ + (field.name, getattr(field, 'label', field.name.title())) + for field in queryset.model._meta.fields + ] + valid_fields += [ + (key, key.title().split('__')) + for key in queryset.query.aggregates.keys() + ] + else: + valid_fields = [ + (item, item) if isinstance(item, six.string_types) else item + for item in valid_fields + ] + + return valid_fields + def remove_invalid_fields(self, queryset, fields, view): + valid_fields = [item[0] for item in self.get_valid_fields(queryset, view)] return [term for term in fields if term.lstrip('-') in valid_fields] def filter_queryset(self, request, queryset, view): @@ -183,6 +265,25 @@ def filter_queryset(self, request, queryset, view): return queryset + def get_template_context(self, request, queryset, view): + current = self.get_ordering(request, queryset, view) + current = None if current is None else current[0] + options = [] + for key, label in self.get_valid_fields(queryset, view): + options.append((key, '%s - ascending' % label)) + options.append(('-' + key, '%s - descending' % label)) + return { + 'request': request, + 'current': current, + 'param': self.ordering_param, + 'options': options, + } + + def to_html(self, request, queryset, view): + template = loader.get_template(self.template) + context = Context(self.get_template_context(request, queryset, view)) + return template.render(context) + class DjangoObjectPermissionsFilter(BaseFilterBackend): """ diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -374,6 +374,7 @@ class BrowsableAPIRenderer(BaseRenderer): media_type = 'text/html' format = 'api' template = 'rest_framework/api.html' + filter_template = 'rest_framework/filters/base.html' charset = 'utf-8' form_renderer_class = HTMLFormRenderer @@ -584,6 +585,37 @@ def get_description(self, view, status_code): def get_breadcrumbs(self, request): return get_breadcrumbs(request.path, request) + def get_filter_form(self, data, view, request): + if not hasattr(view, 'get_queryset') or not hasattr(view, 'filter_backends'): + return + + # Infer if this is a list view or not. + paginator = getattr(view, 'paginator', None) + if isinstance(data, list): + pass + elif (paginator is not None and data is not None): + try: + paginator.get_results(data) + except (TypeError, KeyError): + return + elif not isinstance(data, list): + return + + queryset = view.get_queryset() + elements = [] + for backend in view.filter_backends: + if hasattr(backend, 'to_html'): + html = backend().to_html(request, queryset, view) + if html: + elements.append(html) + + if not elements: + return + + template = loader.get_template(self.filter_template) + context = Context({'elements': elements}) + return template.render(context) + def get_context(self, data, accepted_media_type, renderer_context): """ Returns the context used to render. @@ -631,6 +663,8 @@ def get_context(self, data, accepted_media_type, renderer_context): 'delete_form': self.get_rendered_html_form(data, view, 'DELETE', request), 'options_form': self.get_rendered_html_form(data, view, 'OPTIONS', request), + 'filter_form': self.get_filter_form(data, view, request), + 'raw_data_put_form': raw_data_put_form, 'raw_data_post_form': raw_data_post_form, 'raw_data_patch_form': raw_data_patch_form,
Search and filter controls for Browsable API & Admin The search and filter classes should render in the browsable API in a way that ensures they can be used without having to manually edit the URL querystring.
:+1: definitely very useful, but I'm wondering how exactly we'll make filtering work, since filtering can happen for different fields. Would it only work for `SearchFilter`? Ask me when I get there :p More seriously tho: I've been assuming we'll need an interface on filter classes that can be used to define if and how they should render to HTML. Any appetite for pushing whatever is needed/can be pushed into Django Filter here? I'm more or less on top of the issues backlog there: next up is improving the documentation and then I wanted to think through where it's going — there's seems to be a tendency to sprout new Filter subclasses like mushrooms on a damp night — compatibility with DRF, whilst not everything, seems like an important _feature_ @carltongibson I don't think we'll need to do much pushing into Django Filter. We can probably just add a simple wrapper around its own HTML generation stuff. OK, well as needed. @tomchristie This issue should probably be labeled as `Browseable API`. Not a distinction that we make any more: https://github.com/tomchristie/django-rest-framework/labels Still very much on the roadmap but I'd like to start tying up 3.1.0 since there's a bunch of great improvements in there already. We may have 3.2.0 for the first portion of HTML stuff and 3.3.0 for the final bit of the admin api work, but currently undecided (may just all be 3.2.0)
2015-08-21T15:19:11
encode/django-rest-framework
3,321
encode__django-rest-framework-3321
[ "3318" ]
9758838d861baec024f96592c26cff7cd0f47b48
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -385,8 +385,10 @@ def get_value(self, dictionary): # If the field is blank, and null is a valid value then # determine if we should use null instead. return '' if getattr(self, 'allow_blank', False) else None - elif ret == '' and self.default: - return empty + elif ret == '' and not self.required: + # If the field is blank, and emptyness is valid then + # determine if we should use emptyness instead. + return '' if getattr(self, 'allow_blank', False) else empty return ret return dictionary.get(self.field_name, empty)
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -253,7 +253,7 @@ class TestSerializer(serializers.Serializer): class TestHTMLInput: - def test_empty_html_charfield(self): + def test_empty_html_charfield_with_default(self): class TestSerializer(serializers.Serializer): message = serializers.CharField(default='happy') @@ -261,6 +261,22 @@ class TestSerializer(serializers.Serializer): assert serializer.is_valid() assert serializer.validated_data == {'message': 'happy'} + def test_empty_html_charfield_without_default(self): + class TestSerializer(serializers.Serializer): + message = serializers.CharField(allow_blank=True) + + serializer = TestSerializer(data=QueryDict('message=')) + assert serializer.is_valid() + assert serializer.validated_data == {'message': ''} + + def test_empty_html_charfield_without_default_not_required(self): + class TestSerializer(serializers.Serializer): + message = serializers.CharField(allow_blank=True, required=False) + + serializer = TestSerializer(data=QueryDict('message=')) + assert serializer.is_valid() + assert serializer.validated_data == {'message': ''} + def test_empty_html_integerfield(self): class TestSerializer(serializers.Serializer): message = serializers.IntegerField(default=123)
Resetting a CharFiled to an empty string after fix for #3130 Commit d231f36 to fix #3130 added the following check to `fields.Field.get_value()`: ``` elif ret == '' and self.default: return empty ``` Maybe I am wrong, but it looks like with this change it is no longer possible to reset a `CharField` with `allow_blank=True` but no `default` argument which currently has a non-empty value back to an empty string: The default value for the `default` argument is the `empty` marker. Since the `validate_empty_values()` method raises a `SkipField` execption for this marker the field is skipped on update if set to an empty string. To work around this problem the field may be defined with the empty string as `default` argument, but to have both `allow_blank=True` and `default=''` in the field's argument list seems counter-intuitive.
I'm sorry it's a bit abstract to me. Do you have a failing test case or snippet we could look at ? Hi Xavier, thanks for your prompt reply. You can reproduce the problem with the tutorial. The `Snippet` class has a `title` field: ``` class Snippet(models.Model): ... title = models.CharField(max_length=100, blank=True, default='') ... ``` (btw I wonder why the `default=''` argument is added, since that's what `blank=True` is saying already). To reproduce the problem: 1. Go to the browsable API and add a snippet with a title. 2. Update the snippet and reset the title to an empty string. This has no effect, the original title is still displayed. Adding ``` title = serializers.CharField(required=False, allow_blank=True, max_length=100, default='') ``` to the `SnippetSerializer` fixes this. Note the `default=''` argument (actually any value evaluating to `False` will do). I forget to mention that the problem occurs with HTML requests only, not with JSON requests (as can also be reproduced in the browsable API). The reason for the described behaviour is that with the change introduced in commit d231f36 the empty string is skipped on validation of the serializer, therefore not included in the validated serializer data, and therefore not updated. See https://gist.github.com/mkemmerling/c6f532b31c8c41e9b5c8 . Does this help to clarify the problem? Actually, I gave this a try and my title was set to an empty string. What Django REST framework version are you using ? Note that default is enforced at the DB level which means that if you're creating an instance with the Django shell without giving a title it'll be an empty string. > I forget to mention that the problem occurs with HTML requests only, not with JSON requests (as can also be reproduced in the browsable API). This is a limitation of the html forms that would send an empty string where JSON data makes a difference between empty and null. Will have a look at your test case. Thanks for the details. I'm using version 3.2.3 (with Django 1.8.,4). The problem arises with the changes made for 3.2.0. And yes it occurs only with html forms where the `empty` marker is used. Thanks again for having a look into this. ok, I had an issue in my DRF version and confirme I could reproduce your issue with the tutorial.
2015-08-24T09:13:44
encode/django-rest-framework
3,324
encode__django-rest-framework-3324
[ "3323", "3323" ]
0198bce34f13e3852f082863bd2add7d0285e48b
diff --git a/rest_framework/filters.py b/rest_framework/filters.py --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -102,15 +102,16 @@ def construct_search(self, field_name): def filter_queryset(self, request, queryset, view): search_fields = getattr(view, 'search_fields', None) - orm_lookups = [ - self.construct_search(six.text_type(search_field)) - for search_field in search_fields - ] search_terms = self.get_search_terms(request) if not search_fields or not search_terms: return queryset + orm_lookups = [ + self.construct_search(six.text_type(search_field)) + for search_field in search_fields + ] + base = queryset for search_term in search_terms: queries = [
TypeError when search_fields is omitted Contrary to documentation, if SearchFilter is added but search_fields accidentally (or on purpose) omitted, DRF Release 3.2.3 presents a TypeError when listing a ViewSet. This behavior was not present in Release 3.2.2. TypeError when search_fields is omitted Contrary to documentation, if SearchFilter is added but search_fields accidentally (or on purpose) omitted, DRF Release 3.2.3 presents a TypeError when listing a ViewSet. This behavior was not present in Release 3.2.2.
2015-08-24T14:04:32
encode/django-rest-framework
3,364
encode__django-rest-framework-3364
[ "3361" ]
39ec564ae92805ce630c6855ce95f3d586c7203f
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -113,8 +113,13 @@ def many_init(cls, *args, **kwargs): kwargs['child'] = cls() return CustomListSerializer(*args, **kwargs) """ + allow_empty = kwargs.pop('allow_empty', None) child_serializer = cls(*args, **kwargs) - list_kwargs = {'child': child_serializer} + list_kwargs = { + 'child': child_serializer, + } + if allow_empty is not None: + list_kwargs['allow_empty'] = allow_empty list_kwargs.update(dict([ (key, value) for key, value in kwargs.items() if key in LIST_SERIALIZER_KWARGS
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 @@ -79,17 +79,23 @@ class NestedSerializer(serializers.Serializer): class TestSerializer(serializers.Serializer): allow_null = NestedSerializer(many=True, allow_null=True) not_allow_null = NestedSerializer(many=True) + allow_empty = NestedSerializer(many=True, allow_empty=True) + not_allow_empty = NestedSerializer(many=True, allow_empty=False) self.Serializer = TestSerializer def test_null_allowed_if_allow_null_is_set(self): input_data = { 'allow_null': None, - 'not_allow_null': [{'example': '2'}, {'example': '3'}] + 'not_allow_null': [{'example': '2'}, {'example': '3'}], + 'allow_empty': [{'example': '2'}], + 'not_allow_empty': [{'example': '2'}], } expected_data = { 'allow_null': None, - 'not_allow_null': [{'example': 2}, {'example': 3}] + 'not_allow_null': [{'example': 2}, {'example': 3}], + 'allow_empty': [{'example': 2}], + 'not_allow_empty': [{'example': 2}], } serializer = self.Serializer(data=input_data) @@ -99,7 +105,9 @@ def test_null_allowed_if_allow_null_is_set(self): def test_null_is_not_allowed_if_allow_null_is_not_set(self): input_data = { 'allow_null': None, - 'not_allow_null': None + 'not_allow_null': None, + 'allow_empty': [{'example': '2'}], + 'not_allow_empty': [{'example': '2'}], } serializer = self.Serializer(data=input_data) @@ -118,10 +126,44 @@ def validate_allow_null(self, value): input_data = { 'allow_null': None, - 'not_allow_null': [{'example': 2}] + 'not_allow_null': [{'example': 2}], + 'allow_empty': [{'example': 2}], + 'not_allow_empty': [{'example': 2}], } serializer = TestSerializer(data=input_data) assert serializer.is_valid() assert serializer.validated_data == input_data assert TestSerializer.validation_was_run + + def test_empty_allowed_if_allow_empty_is_set(self): + input_data = { + 'allow_null': [{'example': '2'}], + 'not_allow_null': [{'example': '2'}], + 'allow_empty': [], + 'not_allow_empty': [{'example': '2'}], + } + expected_data = { + 'allow_null': [{'example': 2}], + 'not_allow_null': [{'example': 2}], + 'allow_empty': [], + 'not_allow_empty': [{'example': 2}], + } + serializer = self.Serializer(data=input_data) + + assert serializer.is_valid(), serializer.errors + assert serializer.validated_data == expected_data + + def test_empty_not_allowed_if_allow_empty_is_set_to_false(self): + input_data = { + 'allow_null': [{'example': '2'}], + 'not_allow_null': [{'example': '2'}], + 'allow_empty': [], + 'not_allow_empty': [], + } + serializer = self.Serializer(data=input_data) + + assert not serializer.is_valid() + + expected_errors = {'not_allow_empty': {'non_field_errors': [serializers.ListSerializer.default_error_messages['empty']]}} + assert serializer.errors == expected_errors
`allow_empty` does not work on serializers with `many=True`. Is this expected behaviour? ``` python >>> from rest_framework import serializers >>> >>> class ChildSerializer(serializers.Serializer): ... name = serializers.CharField() ... >>> class ParentSerializer(serializers.Serializer): ... children = ChildSerializer(many=True, allow_empty=False) ... Traceback (most recent call last): File "<console>", line 1, in <module> File "<console>", line 2, in ParentSerializer File "/Users/pmdarrow/.virtualenvs/api/lib/python3.4/site-packages/rest_framework/serializers.py", line 96, in __new__ return cls.many_init(*args, **kwargs) File "/Users/pmdarrow/.virtualenvs/api/lib/python3.4/site-packages/rest_framework/serializers.py", line 116, in many_init child_serializer = cls(*args, **kwargs) File "/Users/pmdarrow/.virtualenvs/api/lib/python3.4/site-packages/rest_framework/serializers.py", line 90, in __init__ super(BaseSerializer, self).__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'allow_empty' ```
`allow_empty` isn't part of the `Field`'s core arguments as listed in the [documentation](http://www.django-rest-framework.org/api-guide/fields/) so I'd expect `allow_empty` will raise an exception. Do you have a use case where this should be a required argument ? It's the same use case for `allow_empty` on a `ListField`. In my example I want to disallow an empty list for `children`. To be clear I don't think it should be a required argument, it should be optional. Alright, looks legit. PR to come.
2015-09-03T15:29:34
encode/django-rest-framework
3,415
encode__django-rest-framework-3415
[ "2761" ]
b1a5294a1aafbc55103031379cf5ffc0f5c42d90
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1262,14 +1262,13 @@ def __init__(self, *args, **kwargs): super(MultipleChoiceField, self).__init__(*args, **kwargs) def get_value(self, dictionary): + if self.field_name not in dictionary: + if getattr(self.root, 'partial', False): + return empty # We override the default field access in order to support # lists in HTML forms. if html.is_html_input(dictionary): - ret = dictionary.getlist(self.field_name) - if getattr(self.root, 'partial', False) and not ret: - ret = empty - return ret - + return dictionary.getlist(self.field_name) return dictionary.get(self.field_name, empty) def to_internal_value(self, data): @@ -1416,6 +1415,9 @@ def __init__(self, *args, **kwargs): self.child.bind(field_name='', parent=self) def get_value(self, dictionary): + if self.field_name not in dictionary: + if getattr(self.root, 'partial', False): + return empty # We override the default field access in order to support # lists in HTML forms. if html.is_html_input(dictionary):
diff --git a/tests/test_serializer_lists.py b/tests/test_serializer_lists.py --- a/tests/test_serializer_lists.py +++ b/tests/test_serializer_lists.py @@ -289,3 +289,32 @@ class Meta: serializer = TestSerializer(data=[], many=True) assert not serializer.is_valid() assert serializer.errors == {'non_field_errors': ['Non field error']} + + +class TestSerializerPartialUsage: + """ + When not submitting key for list fields or multiple choice, partial + serialization should result in an empty state (key not there), not + an empty list. + + Regression test for Github issue #2761. + """ + def test_partial_listfield(self): + class ListSerializer(serializers.Serializer): + listdata = serializers.ListField() + serializer = ListSerializer(data=MultiValueDict(), partial=True) + result = serializer.to_internal_value(data={}) + assert "listdata" not in result + assert serializer.is_valid() + assert serializer.validated_data == {} + assert serializer.errors == {} + + def test_partial_multiplechoice(self): + class MultipleChoiceSerializer(serializers.Serializer): + multiplechoice = serializers.MultipleChoiceField(choices=[1, 2, 3]) + serializer = MultipleChoiceSerializer(data=MultiValueDict(), partial=True) + result = serializer.to_internal_value(data={}) + assert "multiplechoice" not in result + assert serializer.is_valid() + assert serializer.validated_data == {} + assert serializer.errors == {}
PATCH with no data is updating ListField values on ModelSerializer instead of leaving them alone I've got a model serializer with two ListFields and an email field in it, something like this ``` class MySettingsSerializer(ModelSerializer): location_codes = serializers.ListField(child=serializers.CharField(), required=False) permissions = serializers.ListField(child=serializers.CharField(), required=False ) class Meta: model = MySettings fields = ('id', 'email', 'location_codes', 'permissions' ) ``` I've also got a view class that uses UpdateModelMixin to provide an update method. When I do a PATCH to to my view, the expected behavior is that only the values that are sent will be changed. For example, PATCH with {"permissions": [ "change_mymodel" ] } should change the permissions field on the MySettings object, and not change any of the other fields. This works as expected. However, if I do a PATCH with no data at all, both the permissions and locations_codes are set to empty lists. The other field (email) is not changed, which leads me to believe that there is bug related to identifying if a ListField should be updated during a PATCH. Note that this issue cannot be triggered by the HTML form interface by PATCHING a {} -- I can only see it by using a client like Postman and doing a PATCH with no content.
Sounds valid - it'd be good to pull together a more minimal example case that uses a regular serializer rather than a model serializer - that'd help us progress the issue. Hello from DjangoCon sprints. Working on proof of concept solution for this issue. Should have a PR to you in a few days. @adamsc64 Welcome onboard ! It would be wonderfull to start with a failing test case first in order to prove the issue and make sure the fix actually fixes the issue.
2015-09-19T14:21:06
encode/django-rest-framework
3,431
encode__django-rest-framework-3431
[ "3265" ]
41b796d8440364b8999bc14d7af1ca53d43f68cb
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -166,6 +166,12 @@ def save(self, **kwargs): "For example: 'serializer.save(owner=request.user)'.'" ) + assert not hasattr(self, '_data'), ( + "You cannot call `.save()` after accessing `serializer.data`." + "If you need to access data before committing to the database then " + "inspect 'serializer.validated_data' instead. " + ) + validated_data = dict( list(self.validated_data.items()) + list(kwargs.items())
diff --git a/tests/test_serializer.py b/tests/test_serializer.py --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -51,6 +51,16 @@ class MissingAttributes: with pytest.raises(AttributeError): serializer.data + def test_data_access_before_save_raises_error(self): + def create(validated_data): + return validated_data + serializer = self.Serializer(data={'char': 'abc', 'integer': 123}) + serializer.create = create + assert serializer.is_valid() + assert serializer.data == {'char': 'abc', 'integer': 123} + with pytest.raises(AssertionError): + serializer.save() + class TestValidateMethod: def test_non_field_error_validate_method(self):
Guard against calling `serializer.data` before `serializer.save()` It appears that accessing `serializer.data` has side effects. Merely accessing the property inside `perform_create()` will cause the response data to change. I created a simple Django project with a test case that illustrates the bug: [django-rest-bug](https://github.com/kylefox/django-rest-bug). The expected behavior is for `response.data` to contain the serialized version of the created object: ``` python class AlbumViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): # ... snip ... def perform_create(self, serializer): serializer.save() # >>> post_data = {'title': 'The Wall', 'artist': 'Pink Floyd'} # >>> response = self.client.post(reverse('album-list'), post_data) # >>> print response.data # {'id': 1, 'artist': u'Pink Floyd', 'title': u'The Wall'} ``` But when `serializer.data` is present it will cause `response.data` to be equal to the initially posted data (ex: the `id` is missing from response): ``` python class AlbumViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): # ... snip ... def perform_create(self, serializer): serializer.data # This line being present changes the value of `response.data` serializer.save() # >>> post_data = {'title': 'The Wall', 'artist': 'Pink Floyd'} # >>> response = self.client.post(reverse('album-list'), post_data) # >>> print response.data # {'artist': u'Pink Floyd', 'title': u'The Wall'} ``` Even if `serializer.data` is not "safe", I think it's incorrect for property access to result in side effects. I _think_ the culprit is somewhere in [`BaseSerializer.data`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L210) but am not certain.
I'd be interested in hearing why you want to access the `serializer.data` within the view. The flow you've demonstrated there isn't intended usage, and it's possible that its something we should guard against. (Ie raise an exception if `.save()` is called _after_ accessing `.data`) It's valid to access either `.initial_data` or `.validated_data` prior to `.save()`, but it shouldn't be valid to access `.data` and then subsequently call `.save()`. What's happening internally is that `serializer.data` is serializing the _unsaved_ instance, because you've called it prior to save. When we properly restrict the flow then effectively our properties don't have side effects, but this is a case we've obviously left unguarded. Retitled this issue to reflect the change we should make. @xordoquy I was attempting to use it for some validation/permission logic before creating the object. Let's say a `User` is only allowed to create `Messages` attached to a `Project` they have access to. In that case `MessageViewSet. perform_create` would look like this: ``` python class MessageViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): def perform_create(self, serializer): project = serializer.data['project'] if project in self.request.user.projects.all(): serializer.save(project=project) else: raise exceptions.PermissionDenied ``` It feels wrong to put this into the view, but I wasn't sure where else to put it. I guess this might be a case for creating a validation method in my serializer which uses `.context` to access `request.user` and validate there? @tomchristie Good to know, thanks. I actually found, through experimentation, that `.validated_data` worked properly in this scenario. Glad to know this is the correct way to access it :) Though as I mentioned above I think now I understand the correct way to implement what I'm trying to do (`.context`). I suppose it's not _as critical_ to prevent side effects when this flow/scenario isn't intended usage :sweat_smile: Not critical no, but preferable, so let's keep this open for now. > I guess this might be a case for creating a validation method in my serializer which uses .context to access request.user and validate there? Yup. Validation should really be kept inside of the serializer. Or at least it should happen before `perform_create` is called. I usually recommend people limit the `[serializer_field].queryset` property during the initialization of the serializer so the user gets an error if they try to set the relation to something invalid. @kevin-brown Thanks for pointing me in that direction — this is what I wound up with in my serializer: ``` python class MessageSerializer(serializers.ModelSerializer): class Meta: model = Message fields = ('id', 'project', 'body') def __init__(self, *args, **kwargs): super(MessageSerializer, self).__init__(*args, **kwargs) self.user = self.context['request'].user self.fields['project'].queryset = self.user.projects.all() def validate_project(self, project): if project not in self.user.projects.all(): raise exceptions.PermissionDenied return project ``` Because I'm already limiting the queryset in `__init__`, maybe I can remove `validate_project()` entirely...
2015-09-22T18:44:24
encode/django-rest-framework
3,435
encode__django-rest-framework-3435
[ "2878" ]
51443166a875d7d578cdb4fef957968773df560e
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 @@ -193,7 +193,15 @@ def get_field_kwargs(field_name, model_field): ] if getattr(model_field, 'unique', False): - validator = UniqueValidator(queryset=model_field.model._default_manager) + unique_error_message = model_field.error_messages.get('unique', None) + if unique_error_message: + unique_error_message = unique_error_message % { + 'model_name': model_field.model._meta.object_name, + 'field_label': model_field.verbose_name + } + validator = UniqueValidator( + queryset=model_field.model._default_manager, + message=unique_error_message) validator_kwarg.append(validator) if validator_kwarg:
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -48,7 +48,7 @@ def test_is_not_unique(self): data = {'username': 'existing'} serializer = UniquenessSerializer(data=data) assert not serializer.is_valid() - assert serializer.errors == {'username': ['This field must be unique.']} + assert serializer.errors == {'username': ['UniquenessModel with this username already exists.']} def test_is_unique(self): data = {'username': 'other'}
error_messages on serializer fields should also be used by validators. ``` email = models.EmailField( unique=True, error_messages={ 'unique': 'my message' } ) ``` This does not show the defined error as expected when the field is not unique. The message is still the default: "This field must be unique.".
I see. We automatically add `UniqueValidator` for model fields that have `unique=True` [here](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/field_mapping.py#L186). @tomchristie I wonder if we should be forwarding `error_messages['unique']` to `UniqueValidator`, which IMHO seems like we should. @hobarrera A workaround might be to subclass `UniqueValidator` and change the message there. Then in your serializer manually add your email field with that validator. > @tomchristie I wonder if we should be forwarding error_messages['unique'] to UniqueValidator, which IMHO seems like we should. I believe that that makes sense and is what would usually be expected by most developers. > @hobarrera A workaround might be to subclass UniqueValidator and change the message there. Then in your serializer manually add your email field with that validator. Yes, that's what I did. In case anybody else needs a bit more details on this workaround: ``` class ClientSerializer(serializers.ModelSerializer): email = serializers.EmailField(validators=[ UniqueValidator( queryset=Client.objects.all(), message="This email is already in use.", )] ) # ... ``` Is the proposed enhancement to take the error messages from what's defined on the model level and forward them on? Edit: I'd be interested in working on this, if so. > Is the proposed enhancement to take the error messages from what's defined on the model level and forward them on? Yes, that's what's expected (and it's done for other validators, unless I'm mistaken). Seems reasonable to me for us to check the validator codes and apply the field error message if one exists, yup. No objection to this from me. +1 any progress on this one? is this saying we can define error message on the Model level as in https://docs.djangoproject.com/en/1.8/ref/models/fields/#error-messages? > +1 any progress on this one? No, if there's progress you'd see it here. > is this saying we can define error message on the Model level Yup cool, if you tell me the general idea for how that should work or where I need to make updates I can take a stab at it... You'd need to change something here, at least: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/field_mapping.py#L195 That's where a UniqueValidator is automatically added to the serializer for fields with unique constraints. It takes an optional message parameter. I'm not quite sure how to get the message off of the model field, though. > I'm not quite sure how to get the message off of the model field, though. Error messages for a specific field [are available as `field.error_messages`](https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.Field.error_messages). The unique message uses the key `unique`.
2015-09-23T13:30:14
encode/django-rest-framework
3,454
encode__django-rest-framework-3454
[ "3170" ]
bae47b7f36c6e9a76de7b39fa59d9b9c67e57422
diff --git a/rest_framework/compat.py b/rest_framework/compat.py --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -64,6 +64,13 @@ def distinct(queryset, base): postgres_fields = None +# JSONField is only supported from 1.9 onwards +try: + from django.contrib.postgres.fields import JSONField +except ImportError: + JSONField = None + + # django-filter is optional try: import django_filters diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -5,6 +5,7 @@ import datetime import decimal import inspect +import json import re import uuid from collections import OrderedDict @@ -1522,6 +1523,37 @@ def to_representation(self, value): ]) +class JSONField(Field): + default_error_messages = { + 'invalid': _('Value must be valid JSON.') + } + + def __init__(self, *args, **kwargs): + self.binary = kwargs.pop('binary', False) + super(JSONField, self).__init__(*args, **kwargs) + + def to_internal_value(self, data): + try: + if self.binary: + if isinstance(data, six.binary_type): + data = data.decode('utf-8') + return json.loads(data) + else: + json.dumps(data) + except (TypeError, ValueError): + self.fail('invalid') + return data + + def to_representation(self, value): + if self.binary: + value = json.dumps(value) + # On python 2.x the return type for json.dumps() is underspecified. + # On python 3.x json.dumps() returns unicode strings. + if isinstance(value, six.text_type): + value = bytes(value.encode('utf-8')) + return value + + # Miscellaneous field types... class ReadOnlyField(Field): diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -21,6 +21,7 @@ from django.utils.translation import ugettext_lazy as _ from rest_framework.compat import DurationField as ModelDurationField +from rest_framework.compat import JSONField as ModelJSONField from rest_framework.compat import postgres_fields, unicode_to_repr from rest_framework.utils import model_meta from rest_framework.utils.field_mapping import ( @@ -790,6 +791,8 @@ class ModelSerializer(Serializer): } if ModelDurationField is not None: serializer_field_mapping[ModelDurationField] = DurationField + if ModelJSONField is not None: + serializer_field_mapping[ModelJSONField] = JSONField serializer_related_field = PrimaryKeyRelatedField serializer_url_field = HyperlinkedIdentityField serializer_choice_field = ChoiceField
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1525,6 +1525,58 @@ class TestUnvalidatedDictField(FieldValues): field = serializers.DictField() +class TestJSONField(FieldValues): + """ + Values for `JSONField`. + """ + valid_inputs = [ + ({ + 'a': 1, + 'b': ['some', 'list', True, 1.23], + '3': None + }, { + 'a': 1, + 'b': ['some', 'list', True, 1.23], + '3': None + }), + ] + invalid_inputs = [ + ({'a': set()}, ['Value must be valid JSON.']), + ] + outputs = [ + ({ + 'a': 1, + 'b': ['some', 'list', True, 1.23], + '3': 3 + }, { + 'a': 1, + 'b': ['some', 'list', True, 1.23], + '3': 3 + }), + ] + field = serializers.JSONField() + + +class TestBinaryJSONField(FieldValues): + """ + Values for `JSONField` with binary=True. + """ + valid_inputs = [ + (b'{"a": 1, "3": null, "b": ["some", "list", true, 1.23]}', { + 'a': 1, + 'b': ['some', 'list', True, 1.23], + '3': None + }), + ] + invalid_inputs = [ + ('{"a": "unterminated string}', ['Value must be valid JSON.']), + ] + outputs = [ + (['some', 'list', True, 1.23], b'["some", "list", true, 1.23]'), + ] + field = serializers.JSONField(binary=True) + + # Tests for FieldField. # ---------------------
Support PostgreSQL JSONField hi thank you very much , DRF not support JSONField, but Django 1.9 support JSONField url: https://docs.djangoproject.com/en/dev/ref/contrib/postgres/fields/#jsonfield i use django 1.9 ,DRF 3.13 ,Postgresql 9.4 ## My database table fields: [i use postgresql] ``` id<int> , jsonInfo<jsonb> 1,{"username": "dddd","pass":"fffff"} 2,{"username": "1111","pass":"22222"} 3,{"username": "33333","pass":"444444"} ``` --- i created custom JSONField in DRF --- ``` class JSONField(serializers.ReadOnlyField): def to_native(self, obj): return json.dumps(obj) def from_native(self, value): return json.loads(value) ``` --- My Serializer: --- ``` class tradeSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(read_only=True) username= JSONField(source='jsonInfo__username') ``` --- then : i run ``` curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/tr/ ``` i can get 'id' field value, but i canot get username value, it's return null --- if i changed My Serializer code like this: --- ``` class tradeSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(read_only=True) username= JSONField(source='jsonInfo') ``` --- i run ``` curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/tr/ ``` is it ok! but it's return all jsonInfo field value i hope , i can use JSONField(source='jsonInfo__username') i only want get username can you help me ? thank you very much :)
According to the Roadmap https://code.djangoproject.com/wiki/Version1.9Roadmap the alpha for 1.9 is not due for another two months. Final release is a while after that. DRF support for JSONField will be in line with that. @carltongibson thank you :) Isn't the JSONField already supported with the DictField? There's still at least _some_ work to do here... - We probably want to validate that only valid JSON native datatypes are present in the data structure. - We _may_ want to treat string and binary inputs as raw JSON and parse them. - We need to map the JSONField model field onto a serializer field by default. But yes, using DictField will give you 90% of what you need already.
2015-09-28T16:26:23
encode/django-rest-framework
3,475
encode__django-rest-framework-3475
[ "2060" ]
6fb96e93efce2492d7154e283cf83a2e85d9db4a
diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -249,7 +249,7 @@ class HTMLFormRenderer(BaseRenderer): media_type = 'text/html' format = 'form' charset = 'utf-8' - template_pack = 'rest_framework/horizontal/' + template_pack = 'rest_framework/vertical/' base_template = 'form.html' default_style = ClassLookupDict({ @@ -341,26 +341,16 @@ def render(self, data, accepted_media_type=None, renderer_context=None): Render serializer data and return an HTML form, as a string. """ form = data.serializer - meta = getattr(form, 'Meta', None) - style = getattr(meta, 'style', {}) + + style = renderer_context.get('style', {}) if 'template_pack' not in style: style['template_pack'] = self.template_pack - if 'base_template' not in style: - style['base_template'] = self.base_template style['renderer'] = self - # This API needs to be finessed and finalized for 3.1 - if 'template' in renderer_context: - template_name = renderer_context['template'] - elif 'template' in style: - template_name = style['template'] - else: - template_name = style['template_pack'].strip('/') + '/' + style['base_template'] - - renderer_context = renderer_context or {} - request = renderer_context['request'] + template_pack = style['template_pack'].strip('/') + template_name = template_pack + '/' + self.base_template template = loader.get_template(template_name) - context = RequestContext(request, { + context = Context({ 'form': form, 'style': style }) @@ -505,10 +495,7 @@ def get_rendered_html_form(self, data, view, method, request): return form_renderer.render( serializer.data, self.accepted_media_type, - dict( - list(self.renderer_context.items()) + - [('template', 'rest_framework/api_form.html')] - ) + {'style': {'template_pack': 'rest_framework/horizontal'}} ) def get_raw_data_form(self, data, view, method, request): 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 @@ -25,8 +25,14 @@ def get_pagination_html(pager): @register.simple_tag -def render_field(field, style=None): - style = style or {} +def render_form(serializer, template_pack=None): + style = {'template_pack': template_pack} if template_pack else {} + renderer = HTMLFormRenderer() + return renderer.render(serializer.data, None, {'style': style}) + + [email protected]_tag +def render_field(field, style): renderer = style.get('renderer', HTMLFormRenderer()) return renderer.render_field(field, style)
Public forms API. With 3.0 we now have a template based form rendering for serializers. This has basically everything it needs to serve as a fully fledged alternative to django forms. I'm also currently planning for it to be compatible with use in eg. Django's standard class based views. (So for example, we'll need to provide a `files` keyword argument for cross-compatibility) The API for all this still needs to be made public, documented, and any rough edges ironed out. In order to not block the 3.0 release I'm milestoning this to 3.1 - there's no reason that this needs to become public API straight away, better to take an incremental approach. In particular we should document how to create alternate template packs.
This might also be related: https://groups.google.com/forum/#!topic/django-rest-framework/Xd5JpZ3H_o8 (I apologize for my terrible photoshop skills). The idea here is to support nested serializers on the form itself. In the example address is nested to `state`, etc. and `full_name` is nested to first name and last name. Yes indeed - nested forms are already supported :) eg... ``` class ProfileSerializer(serializers.Serializer): role = serializers.ChoiceField( ['owner', 'staff', 'customer'], style={'base_template': 'radio.html', 'inline': True} ) last_payment = serializers.DateTimeField() class UserSerializer(serializers.Serializer): email = serializers.EmailField() username = serializers.CharField() profile = ProfileSerializer() ``` Renders as this... ![screen shot 2014-11-10 at 22 35 54](https://cloud.githubusercontent.com/assets/647359/4985142/324eb424-692a-11e4-8e95-9e1b66013a62.png) It doesn't yet support multiple items or multiple inline items, and don't assume any of the API above is final, but as you can see we've got the bases pretty much covered. :) Ah. Very cool. Is this new to 3.0 or was it there all along? This might ALSO be related to the ticket: https://groups.google.com/forum/#!topic/django-rest-framework/e75osh1Wcyg. It's completely new to 3.0. I was planning on making it public API for 3.0, but I think we'll do better to let any of the more basic niggles get thrashed out during 3.0, and only make it publicly supported API in 3.1 (so think another ~2 months after 3.0, but should mostly be usable during that period, if you're willing to keep up to date with any private API changes) I am willing to deal with a changing API. On Mon Nov 10 2014 at 5:43:43 PM Tom Christie [email protected] wrote: > It's completely new to 3.0. > I was planning on making it public API for 3.0, but I think we'll do > better to let any of the more basic niggles get thrashed out during 3.0, > and only make it publicly supported API in 3.1 (so think another ~2 months > after 3.0, but should mostly be usable during that period, if you're > willing to keep up to date with any private API changes) > > — > Reply to this email directly or view it on GitHub > https://github.com/tomchristie/django-rest-framework/issues/2060#issuecomment-62469932 > . Pushing all further HTML specific stuff to 3.2.0. @tomchristie Taking a look at the [example rendering from above](https://github.com/tomchristie/django-rest-framework/issues/2060#issuecomment-62469196), if you set the order of the fields explicitly: ``` python class UserSerializer(serializers.Serializer): profile = ProfileSerializer() email = serializers.EmailField() username = serializers.CharField() ``` There is a sub heading for "Profile" but no sub-heading for "User" which make it hard to tell which fields belong to which serializer. Compare these two: ![image](https://cloud.githubusercontent.com/assets/51059/6520952/fb848978-c39c-11e4-99e3-d3335b575dd4.png) and ![image](https://cloud.githubusercontent.com/assets/51059/6520963/1274f848-c39d-11e4-9257-e3e1ad12ea4a.png) Is is not clear in the first image whether color belongs to profile. As the number of fields grows, this can become confusing. Ideally all of the nested serializers should be grouped at the bottom So re So reorder them in the serializer. Quite sure that if do that automatically for the user we'd have issue raised from folks asking for the behavior to not do that. It's also unnecessary extra trickery. So I commingled two concerns here: 1) is the intelligent reordering of fields. I think you made a fair point that this would not be transparent to the user 2) Is just adding a subheading over / some indication of the main set of serializer fields when using nested serializers. The current UI / UX makes it a bit confusing. Yeah worth us having a look at if we can handle it any better. I'll keep this in mind when I come to documenting and formalizing the Serializers as HTML API. https://github.com/WiserTogether/django-remote-forms does this have any use? regarding the issue auvipy - probably not in scope for the work as currently planned.
2015-10-06T09:58:51
encode/django-rest-framework
3,509
encode__django-rest-framework-3509
[ "3499" ]
1b4a41cb801cb94f9018a45d341ade9e5e387d19
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 @@ -123,7 +123,8 @@ def get_field_kwargs(field_name, model_field): # Ensure that max_length is passed explicitly as a keyword arg, # rather than as a validator. max_length = getattr(model_field, 'max_length', None) - if max_length is not None and isinstance(model_field, models.CharField): + if max_length is not None and (isinstance(model_field, models.CharField) or + isinstance(model_field, models.TextField)): kwargs['max_length'] = max_length validator_kwarg = [ validator for validator in validator_kwarg
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 @@ -63,7 +63,7 @@ class RegularFieldsModel(models.Model): positive_small_integer_field = models.PositiveSmallIntegerField() slug_field = models.SlugField(max_length=100) small_integer_field = models.SmallIntegerField() - text_field = models.TextField() + text_field = models.TextField(max_length=100) time_field = models.TimeField() url_field = models.URLField(max_length=100) custom_field = CustomField() @@ -161,11 +161,12 @@ class Meta: positive_small_integer_field = IntegerField() slug_field = SlugField(max_length=100) small_integer_field = IntegerField() - text_field = CharField(style={'base_template': 'textarea.html'}) + text_field = CharField(max_length=100, style={'base_template': 'textarea.html'}) time_field = TimeField() url_field = URLField(max_length=100) custom_field = ModelField(model_field=<tests.test_model_serializer.CustomField: custom_field>) """) + self.assertEqual(unicode_repr(TestSerializer()), expected) def test_field_options(self):
Keep max_length when converting TextField to CharField in ModelSerializer When Django makes a ModelForm out of a Model it validates the max_length of any TextFields (if specified) even though it is not enforced on a database level. I realize this did not use to be the case and that may be why DRF does not currently do the same with ModelSerializers. I see no downside to having them do the same. Currently `TextField(max_length=1000)` becomes `CharField(style={'base_template': 'textarea.html'})`.
Seems valid. Working on this.
2015-10-16T11:24:03
encode/django-rest-framework
3,526
encode__django-rest-framework-3526
[ "2426" ]
825e67454d9e3bd839a23e7da504b020e2d71864
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -794,6 +794,7 @@ class ModelSerializer(Serializer): if ModelJSONField is not None: serializer_field_mapping[ModelJSONField] = JSONField serializer_related_field = PrimaryKeyRelatedField + serializer_related_to_field = SlugRelatedField serializer_url_field = HyperlinkedIdentityField serializer_choice_field = ChoiceField @@ -1129,6 +1130,11 @@ def build_relational_field(self, field_name, relation_info): field_class = self.serializer_related_field field_kwargs = get_relation_kwargs(field_name, relation_info) + to_field = field_kwargs.pop('to_field', None) + if to_field and to_field != 'id': + field_kwargs['slug_field'] = to_field + field_class = self.serializer_related_to_field + # `view_name` is only valid for hyperlinked relationships. if not issubclass(field_class, HyperlinkedRelatedField): field_kwargs.pop('view_name', None) 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 @@ -222,7 +222,7 @@ def get_relation_kwargs(field_name, relation_info): """ Creates a default instance of a flat relational field. """ - model_field, related_model, to_many, has_through_model = relation_info + model_field, related_model, to_many, to_field, has_through_model = relation_info kwargs = { 'queryset': related_model._default_manager, 'view_name': get_detail_view_name(related_model) @@ -231,6 +231,9 @@ def get_relation_kwargs(field_name, relation_info): if to_many: kwargs['many'] = True + if to_field: + kwargs['to_field'] = to_field + if has_through_model: kwargs['read_only'] = True kwargs.pop('queryset', None) 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 @@ -26,6 +26,7 @@ 'model_field', 'related_model', 'to_many', + 'to_field', 'has_through_model' ]) @@ -90,6 +91,10 @@ def _get_fields(opts): return fields +def _get_to_field(field): + return field.to_fields[0] if field.to_fields else None + + def _get_forward_relationships(opts): """ Returns an `OrderedDict` of field names to `RelationInfo`. @@ -100,6 +105,7 @@ def _get_forward_relationships(opts): model_field=field, related_model=_resolve_model(field.rel.to), to_many=False, + to_field=_get_to_field(field), has_through_model=False ) @@ -109,6 +115,8 @@ def _get_forward_relationships(opts): model_field=field, related_model=_resolve_model(field.rel.to), to_many=True, + # manytomany do not have to_fields + to_field=None, has_through_model=( not field.rel.through._meta.auto_created ) @@ -133,6 +141,7 @@ def _get_reverse_relationships(opts): model_field=None, related_model=related, to_many=relation.field.rel.multiple, + to_field=_get_to_field(relation.field), has_through_model=False ) @@ -144,6 +153,8 @@ def _get_reverse_relationships(opts): model_field=None, related_model=related, to_many=True, + # manytomany do not have to_fields + to_field=None, has_through_model=( (getattr(relation.field.rel, 'through', None) is not None) and not relation.field.rel.through._meta.auto_created
Respect to_field property of ForeignKey relations In my project i use ForeignKeys with the to_field property to link on a uuid Field. That UUID field is Unique but NOT the primary key for a few reasons. (Including that mysql uses the dumbest indextype possible for primary keys and i need to scale. you cannot change that) I do also have multiple peers with possible network outage that have to create database entries. So using UUIDs all over is the only feasable way. Therefore i need to serialize my ForeignKeys to the uuid field specified in to_field and deserialize from it. Despite my unusual requirements i think using to_field to unique but not primary keys is perfectly fine and should be supported. ``` python >>> b = Statement(device_id="335680b80f204e25a0e23caa052a3e83", rule_id="d19b314a8cb04a558798d6d8026cc56e", evalOperator="EQ", evalDesiredState=False) >>> x=StatementSerializer(b) >>> json = JSONRenderer().render(x.data) >>> json '{"id":null,"created":null,"modified":null,"uuid":"8846412b-5b07-485a-9f2b-d41c0902a98c","evalOperator":"EQ","evalDesiredState":false,"device":"335680b80f204e25a0e23caa052a3e83","rule":"d19b314a8cb04a558798d6d8026cc56e"}' ``` Serialization works kind of. Notice that i have to/can use key_id syntax -> device: <uuid> ``` python >>> mod_json = json.replace('rule','rule_id').replace('device',"device_id").replace('user',"user_id") >>> json_data = JSONParser().parse(BytesIO(json)) >>> mjson_data = JSONParser().parse(BytesIO(mod_json)) >>> xx=StatementSerializer(data=json_data) >>> xx.is_valid() False >>> xx.errors ReturnDict([('device', [u'Incorrect type. Expected pk value, received unicode.']), ('user', [u'Incorrect type. Expected pk value, received unicode.']), ('rule', [u'Incorrect type. Expected pk value, received unicode.'])]) >>> xx=StatementSerializer(data=mjson_data) >>> x.is_valid() False >>> x.errors ReturnDict([('device', [u'This field is required.']), ('user', [u'This field is required.']), ('rule', [u'This field is required.'])]) ``` Note: I also tried replacing <key> with <key>_id for deserialization but even that does not work. IMHO it should. ``` python class PrimaryKeyRelatedField(RelatedField): def use_pk_only_optimization(self): return True ``` A hotfix could be disabling use_pk_only_optimization in PrimaryKeyRelatedField. It deserialized correctly that way but .data etc. still shows the primary key like: ReturnDict([(u'id', None), ('created', None), ('modified', None), ('uuid', u'43c93954-e9c3-4e90-9d40-c1a87f68cb73'), ('evalOperator', 'EQ'), ('evalDesiredState', False), ('user', 1L), ('device', 2L), ('rule', 2L)])
Sidenote: Seems that if i disable the use_pk_only_optimization i only get the primary key serialized - not the uuid field like above I hacked together something that works for me. Please let me know if thats the right way designwise. I would create a pull request. Maybe with some logic so that this field would be used if to_field is set on the modelfield. ``` python class UniqueKeyRelatedField(PrimaryKeyRelatedField): def __init__(self, **kwargs): self.to_field = kwargs.pop('to_field', None) super(UniqueKeyRelatedField, self).__init__(**kwargs) def use_pk_only_optimization(self): return False def to_internal_value(self, data): try: return self.get_queryset().get(**{self.to_field: data}) except ObjectDoesNotExist: self.fail('does_not_exist', pk_value=data) except (TypeError, ValueError): self.fail('incorrect_type', data_type=type(data).__name__) def to_representation(self, value): return str(getattr(value, self.to_field)) class StatementSerializer(serializers.ModelSerializer): class Meta: model = Statement device = UniqueKeyRelatedField(to_field='uuid', queryset=Device.objects.all()) user = UniqueKeyRelatedField(to_field='uuid', queryset=User.objects.all()) # had a crazy loop because the rule model has a 'cached' version of the statement as a JSONField and tries to deserialize it rule = UniqueKeyRelatedField(to_field='uuid', queryset=Rule.objects.only('uuid').all()) ``` `SlugRelatedField` will work for any unique fields, not necessarily just "slug" type values. I'd assume this will solve your use case just fine... ``` device = SlugRelatedField(slug_field='uuid', queryset=Device.objects.all()) ``` Happy to reopen if this needs more correspondence, and we may consider more docs/renaming at some point in the future as similar questions do come up occasionally. Thanks your help! I think i overlooked SlugRelatedField because the example in the doc looks like something i would use directly in a view. However i still think this should be done automagically as this is a ModelSerializer for Django Models and i specified my intention clearly by using the to_field parameter so i am interested in that relation not in the one to the primary key. Would be more DRY also to because now i have to specify like 30 Fields only to reflect that i am using the builtin to_field for relations. Any thoughts regarding this? Another unrelated issue i stumbled upon using SlugRelatedField: I am using the django dev trunk so i can use the shiny new UUIDField. ``` python File "/Users/tomjaster/DevFolder/master/airyengine/airy/lib/rest_framework/utils/encoders.py", line 60, in default return super(JSONEncoder, self).default(obj) File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: UUID('335680b8-0f20-4e25-a0e2-3caa052a3e83') is not JSON serializable ``` My quick fix was to add this to JSONEncoder.default but i assume this needs a new class in fields.py? Will there be support for this before django 1.8 gets released? Maybe in the development branch? I don't like to rely on maintaining my own branch to keep those little patches in. ``` python elif hasattr(obj, 'hex'): return obj.hex ``` best regards Tom Now tracking the UUID one here: #2432 Dropping the 3.0.x milestone - valid enhancement, but no reason we need to prioritize this higher than other ongoing work right now.
2015-10-21T10:29:47
encode/django-rest-framework
3,546
encode__django-rest-framework-3546
[ "3545" ]
af5474f9b3a220245c6031911ea7ef614b8f556e
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 @@ -7,7 +7,7 @@ from django.template import Context, loader from django.utils import six from django.utils.encoding import force_text, iri_to_uri -from django.utils.html import escape, smart_urlquote +from django.utils.html import escape, format_html, smart_urlquote from django.utils.safestring import SafeData, mark_safe from rest_framework.renderers import HTMLFormRenderer @@ -48,7 +48,8 @@ def optional_login(request): return '' snippet = "<li><a href='{href}?next={next}'>Log in</a></li>" - snippet = snippet.format(href=login_url, next=escape(request.path)) + snippet = format_html(snippet, href=login_url, next=escape(request.path)) + return mark_safe(snippet) @@ -71,7 +72,8 @@ def optional_logout(request, user): <li><a href='{href}?next={next}'>Log out</a></li> </ul> </li>""" - snippet = snippet.format(user=escape(user), href=logout_url, next=escape(request.path)) + snippet = format_html(snippet, user=escape(user), href=logout_url, next=escape(request.path)) + return mark_safe(snippet)
Django 1.9 raw HTML in header I just upgraded to 3.2.4 and this is what I see: <img width="1002" alt="screen shot 2015-10-25 at 8 35 12 pm" src="https://cloud.githubusercontent.com/assets/54896/10714927/f175ae3a-7b57-11e5-94ab-bb253219113f.png">
Notes on how to replicate would be great, as we've not had this raised elsewhere. Does it replicate on a clean install, and what exact steps are required? Oh yea, I just replicated this. ``` $ git clone https://github.com/tomchristie/rest-framework-tutorial.git $ pip install -r requirements.txt $ pip install --upgrade --pre django $ pip install --upgrade djangorestframework $ ./manage.py runserver ``` Might be because of this [change on simple_tag on Django 1.9](https://docs.djangoproject.com/en/1.9/releases/1.9/#simple-tag-now-wraps-tag-output-in-conditional-escape). Checking it out.
2015-10-25T12:28:42
encode/django-rest-framework
3,560
encode__django-rest-framework-3560
[ "3559", "3559" ]
b8c9c809ff3e5e000a313e9a4a68eefb276d51da
diff --git a/rest_framework/filters.py b/rest_framework/filters.py --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -117,8 +117,11 @@ def filter_queryset(self, request, queryset, view): return queryset def to_html(self, request, queryset, view): - cls = self.get_filter_class(view, queryset) - filter_instance = cls(request.query_params, queryset=queryset) + filter_class = self.get_filter_class(view, queryset) + if filter_class: + filter_instance = filter_class(request.query_params, queryset=queryset) + else: + filter_instance = None context = Context({ 'filter': filter_instance })
Viewsets without a filter_class break Browser Viewer The `to_html` function doesn't check if the `cls` exists in this line: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/filters.py#L121 It should have logic checking for a `None`, similar to the above bit: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/filters.py#L112-L114 Causes this error when viewing those pages: `'NoneType' object is not callable` Viewsets without a filter_class break Browser Viewer The `to_html` function doesn't check if the `cls` exists in this line: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/filters.py#L121 It should have logic checking for a `None`, similar to the above bit: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/filters.py#L112-L114 Causes this error when viewing those pages: `'NoneType' object is not callable`
2015-10-28T19:38:51
encode/django-rest-framework
3,568
encode__django-rest-framework-3568
[ "3562" ]
6f6f794be596c84a84bcbc7ee3e68755ffdac73b
diff --git a/rest_framework/compat.py b/rest_framework/compat.py --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -185,6 +185,11 @@ def apply_markdown(text): else: DurationField = duration_string = parse_duration = None +try: + # DecimalValidator is unavailable in Django < 1.9 + from django.core.validators import DecimalValidator +except ImportError: + DecimalValidator = None def set_rollback(): if hasattr(transaction, 'set_rollback'): 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,6 +8,7 @@ from django.db import models from django.utils.text import capfirst +from rest_framework.compat import DecimalValidator from rest_framework.validators import UniqueValidator NUMERIC_FIELD_TYPES = ( @@ -132,7 +133,7 @@ def get_field_kwargs(field_name, model_field): if isinstance(model_field, models.DecimalField): validator_kwarg = [ validator for validator in validator_kwarg - if not isinstance(validator, validators.DecimalValidator) + if DecimalValidator and not isinstance(validator, DecimalValidator) ] # Ensure that max_length is passed explicitly as a keyword arg,
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 @@ -22,7 +22,7 @@ from rest_framework import serializers from rest_framework.compat import DurationField as ModelDurationField -from rest_framework.compat import unicode_repr +from rest_framework.compat import DecimalValidator, unicode_repr def dedent(blocktext): @@ -861,3 +861,41 @@ class Meta: }] assert serializer.data == expected + + +class DecimalFieldModel(models.Model): + decimal_field = models.DecimalField( + max_digits=3, + decimal_places=1, + validators=[MinValueValidator(1), MaxValueValidator(3)] + ) + + +class TestDecimalFieldMappings(TestCase): + @pytest.mark.skipif(DecimalValidator is not None, + reason='DecimalValidator is available in Django 1.9+') + def test_decimal_field_has_no_decimal_validator(self): + """ + Test that a DecimalField has no validators before Django 1.9. + """ + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = DecimalFieldModel + + serializer = TestSerializer() + + assert len(serializer.fields['decimal_field'].validators) == 0 + + @pytest.mark.skipif(DecimalValidator is None, + reason='DecimalValidator is available in Django 1.9+') + def test_decimal_field_has_decimal_validator(self): + """ + Test that a DecimalField has DecimalValidator in Django 1.9+. + """ + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = DecimalFieldModel + + serializer = TestSerializer() + + assert len(serializer.fields['decimal_field'].validators) == 2
DecimalValidator is unavailable in Django < 1.9 ``` File "D:\VirtualEnvs\nouvelleoffre\lib\site-packages\rest_framework\serializers.py", line 431, in to_internal_value fields = self._writable_fields File "D:\VirtualEnvs\nouvelleoffre\lib\site-packages\django\utils\functional.py", line 59, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\VirtualEnvs\nouvelleoffre\lib\site-packages\rest_framework\serializers.py", line 346, in _writable_fields field for field in self.fields.values() File "D:\VirtualEnvs\nouvelleoffre\lib\site-packages\rest_framework\serializers.py", line 339, in fields for key, value in self.get_fields().items(): File "D:\VirtualEnvs\nouvelleoffre\lib\site-packages\rest_framework\serializers.py", line 939, in get_fields field_name, info, model, depth File "D:\VirtualEnvs\nouvelleoffre\lib\site-packages\rest_framework\serializers.py", line 1061, in build_field return self.build_standard_field(field_name, model_field) File "D:\VirtualEnvs\nouvelleoffre\lib\site-packages\rest_framework\serializers.py", line 1085, in build_standard_field field_kwargs = get_field_kwargs(field_name, model_field) File "D:\VirtualEnvs\nouvelleoffre\lib\site-packages\rest_framework\utils\field_mapping.py", line 134, in get_field_kwargs validator for validator in validator_kwarg File "D:\VirtualEnvs\nouvelleoffre\lib\site-packages\rest_framework\utils\field_mapping.py", line 135, in <listcomp> if not isinstance(validator, validators.DecimalValidator) AttributeError: 'module' object has no attribute 'DecimalValidator' ``` https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/field_mapping.py#L135
We may need something to ensure this will only apply to Django >= 1.9, maybe in compat. Yep, DecimalValidator is only available in Django 1.9: http://django.readthedocs.org/en/latest/ref/validators.html#decimalvalidator
2015-10-29T10:43:13
encode/django-rest-framework
3,592
encode__django-rest-framework-3592
[ "3574" ]
950e5e0fecf934f37c973f87da992e6ca086ac61
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.2.4' +__version__ = '3.3.0' __author__ = 'Tom Christie' __license__ = 'BSD 2-Clause' __copyright__ = 'Copyright 2011-2015 Tom Christie' diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py --- a/rest_framework/authentication.py +++ b/rest_framework/authentication.py @@ -117,9 +117,8 @@ def authenticate(self, request): Otherwise returns `None`. """ - # Get the underlying HttpRequest object - request = request._request - user = getattr(request, 'user', None) + # Get the session-based user from the underlying HttpRequest object + user = getattr(request._request, 'user', None) # Unauthenticated, CSRF validation not required if not user or not user.is_active: diff --git a/rest_framework/request.py b/rest_framework/request.py --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -365,6 +365,15 @@ def DATA(self): 'since version 3.0, and has been fully removed as of version 3.2.' ) + @property + def POST(self): + # Ensure that request.POST uses our request parsing. + if not _hasattr(self, '_data'): + self._load_data_and_files() + if is_form_media_type(self.content_type): + return self.data + return QueryDict('', encoding=self._request._encoding) + @property def FILES(self): # Leave this one alone for backwards compat with Django's request.FILES
HTML form in generics.listCreateAPI is not taking values When we try to submit json through the HTML form where the view is created with ListCreateAPI, it is not saving the values. If we save it using the application/json, it saves the values. This was working fine in version 3.2.5 but it is not working in version 3.3.0
2015-11-04T14:11:48
encode/django-rest-framework
3,593
encode__django-rest-framework-3593
[ "3555" ]
95f92e995c7c2822f3a6483a86f45ada34684c22
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -1131,7 +1131,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 to_field != 'id': + if to_field 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
Assumes primary key called `id`, breaks HyperlinkedModelSerializer Does [this line](https://github.com/tomchristie/django-rest-framework/blob/3.3.0/rest_framework/serializers.py#L1134) assume now that the primary key of a model is called `id`? In the past the `ModelSerializer` generated (In this case the primary key on the `Order` model is `order_id`): ``` order = PrimaryKeyRelatedField(read_only=True) ``` Now I get: ``` order = SlugRelatedField(read_only=True, slug_field='order_id') ``` The issue comes up in that if instead I use a `HyperlinkedModelSerializer`, I no longer get a hyperlink for that field.
@cancan101 it indeed looks like it assumes the PK to be "id" which doesn't look right. Looks like this was relatively recent PR: https://github.com/tomchristie/django-rest-framework/pull/3526.
2015-11-04T14:38:19
encode/django-rest-framework
3,656
encode__django-rest-framework-3656
[ "3252" ]
f3de2146ea10377ad4f2482b32212ee92d4995fd
diff --git a/rest_framework/compat.py b/rest_framework/compat.py --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -230,3 +230,32 @@ def template_render(template, context=None, request=None): # backends template, e.g. django.template.backends.django.Template else: return template.render(context, request=request) + + +def get_all_related_objects(opts): + """ + Django 1.8 changed meta api, see + https://docs.djangoproject.com/en/1.8/ref/models/meta/#migrating-old-meta-api + https://code.djangoproject.com/ticket/12663 + https://github.com/django/django/pull/3848 + + :param opts: Options instance + :return: list of relations except many-to-many ones + """ + if django.VERSION < (1, 9): + return opts.get_all_related_objects() + else: + return [r for r in opts.related_objects if not r.field.many_to_many] + + +def get_all_related_many_to_many_objects(opts): + """ + Django 1.8 changed meta api, see docstr in compat.get_all_related_objects() + + :param opts: Options instance + :return: list of many-to-many relations + """ + if django.VERSION < (1, 9): + return opts.get_all_related_many_to_many_objects() + else: + return [r for r in opts.related_objects if r.field.many_to_many] 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 @@ -13,6 +13,10 @@ from django.db import models from django.utils import six +from rest_framework.compat import ( + get_all_related_many_to_many_objects, get_all_related_objects +) + FieldInfo = namedtuple('FieldResult', [ 'pk', # Model field instance 'fields', # Dict of field name -> model field instance @@ -134,7 +138,7 @@ def _get_reverse_relationships(opts): # See: https://code.djangoproject.com/ticket/24208 reverse_relations = OrderedDict() - for relation in opts.get_all_related_objects(): + for relation in get_all_related_objects(opts): accessor_name = relation.get_accessor_name() related = getattr(relation, 'related_model', relation.model) reverse_relations[accessor_name] = RelationInfo( @@ -146,7 +150,7 @@ def _get_reverse_relationships(opts): ) # Deal with reverse many-to-many relationships. - for relation in opts.get_all_related_many_to_many_objects(): + for relation in get_all_related_many_to_many_objects(opts): accessor_name = relation.get_accessor_name() related = getattr(relation, 'related_model', relation.model) reverse_relations[accessor_name] = RelationInfo(
Model._meta API warnings with Django 1.9 (RemovedInDjango110Warning) Whilst running Django 1.9.dev (master) I'm getting a couple of warnings in relations to the changes in the [Model._meta API](https://docs.djangoproject.com/en/1.8/ref/models/meta/) introduced in Django 1.8. > .../lib/python3.4/site-packages/rest_framework/utils/model_meta.py:130: RemovedInDjango110Warning: 'get_all_related_objects is an unofficial API that has been deprecated. You may be able to replace it with 'get_fields()' > for relation in opts.get_all_related_objects(): > > .../lib/python3.4/site-packages/rest_framework/utils/model_meta.py:141: RemovedInDjango110Warning: 'get_all_related_many_to_many_objects is an unofficial API that has been deprecated. You may be able to replace it with 'get_fields()' > for relation in opts.get_all_related_many_to_many_objects():
Noted, thanks. We'll aim to clear this up as part of official 1.9 support when that comes out. Now resolved in master. Now running Django 1.9b1 and DRF 3.3.0 I'm continuing to get a couple of warnings in relations to the changes in the [Model._meta API](https://docs.djangoproject.com/en/1.8/ref/models/meta/) introduced in Django 1.8. > ...lib/python3.4/site-packages/rest_framework/utils/model_meta.py:137: RemovedInDjango110Warning: 'get_all_related_objects is an unofficial API that has been deprecated. You may be able to replace it with 'get_fields()' > for relation in opts.get_all_related_objects(): > > .../lib/python3.4/site-packages/rest_framework/utils/model_meta.py:149: RemovedInDjango110Warning: 'get_all_related_many_to_many_objects is an unofficial API that has been deprecated. You may be able to replace it with 'get_fields()' > for relation in opts.get_all_related_many_to_many_objects(): Thanks for the report.
2015-11-18T19:22:53
encode/django-rest-framework
3,687
encode__django-rest-framework-3687
[ "3679" ]
d2f90fd6af96d1160498d9c35ab85bf5205d87dc
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -769,9 +769,11 @@ def to_internal_value(self, data): try: if isinstance(data, six.integer_types): return uuid.UUID(int=data) - else: + elif isinstance(data, six.string_types): return uuid.UUID(hex=data) - except (ValueError, TypeError): + else: + self.fail('invalid', value=data) + except (ValueError): self.fail('invalid', value=data) return data
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -609,7 +609,8 @@ class TestUUIDField(FieldValues): 284758210125106368185219588917561929842: uuid.UUID('d63a6fb6-88d5-40c7-a91c-9edf73283072') } invalid_inputs = { - '825d7aeb-05a9-45b5-a5b7': ['"825d7aeb-05a9-45b5-a5b7" is not a valid UUID.'] + '825d7aeb-05a9-45b5-a5b7': ['"825d7aeb-05a9-45b5-a5b7" is not a valid UUID.'], + (1, 2, 3): ['"(1, 2, 3)" is not a valid UUID.'] } outputs = { uuid.UUID('825d7aeb-05a9-45b5-a5b7-05df87923cda'): '825d7aeb-05a9-45b5-a5b7-05df87923cda'
UUIDField validation does not catch AttributeError I am using a UUIDField in a serializer as such: ``` class ExampleSerializer(serializers.Serializer): some_id = serializers.UUIDField(required = False) class ExampleView(APIView): def post(self, request): example_serializer = ExampleSerializer(data = request.data) example_serializer.is_valid() ``` If I make a request to this view with the parameter some_id mapped to a list, e.g. `{"some_id": [1, 2, 3]}`, I get an `AttributeError: list object has no attribute replace`, even though the expected behavior is that the exception is caught by `is_valid` and its return value is `False` (since a list is clearly not valid input to a UUIDField) The `AttributeError` is thrown by Python's uuid.py (I am on Python 3.4.3) at the following line of UUID's `__init__` method: ``` if hex is not None: hex = hex.replace('urn:', '').replace('uuid:', '') ``` I believe the issue lies in the `to_internal_value` method of UUIDField when it calls the UUID constructor to construct the field from the input data (code from https://github.com/tomchristie/django-rest-framework/blob/a8deb380ff70b5df8d3c62c9be981b60e363c7f9/rest_framework/fields.py#L767): ``` def to_internal_value(self, data): if not isinstance(data, uuid.UUID): try: if isinstance(data, six.integer_types): return uuid.UUID(int=data) else: return uuid.UUID(hex=data) except (ValueError, TypeError): self.fail('invalid', value=data) return data ``` Shouldn't `AttributeError` also be caught here before calling `self.fail` (to register validation failure)? I an on djangorestframework version 3.3.1 Thanks for taking a look!
Looks to me like we should ensure data is a string when calling UUID(hex=data). Yes. Binary string prob also okay. And then only catch ValueError Alt: push upstream and ensure Django raises a TypeError in this case (it probably should, really) We may want to resolve both in REST framework, and upstream in Django. > Yes. Binary string prob also okay. No, it's not. There's a bytes argument for binary. See https://docs.python.org/2/library/uuid.html Got it! > Alt: push upstream and ensure Django raises a TypeError in this case (it probably should, really) Correct me but uuid doesn't seem to be using Django's field for that one right ? Right yup, ignore my upstream comments! :p
2015-12-01T19:15:20
encode/django-rest-framework
3,701
encode__django-rest-framework-3701
[ "3628", "3628" ]
9f74b8860e64dcaeef54972db347ac1bd2afe1a3
diff --git a/rest_framework/relations.py b/rest_framework/relations.py --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -32,6 +32,9 @@ def __new__(self, url, name): ret.name = name return ret + def __getnewargs__(self): + return(str(self), self.name,) + is_hyperlink = True
diff --git a/tests/test_relations.py b/tests/test_relations.py --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -206,3 +206,14 @@ def test_get_value_multi_dictionary_partial(self): mvd = MultiValueDict({'baz': ['bar1', 'bar2']}) assert empty == self.field.get_value(mvd) + + +class TestHyperlink: + def setup(self): + self.default_hyperlink = serializers.Hyperlink('http://example.com', 'test') + + def test_can_be_pickled(self): + import pickle + upkled = pickle.loads(pickle.dumps(self.default_hyperlink)) + assert upkled == self.default_hyperlink + assert upkled.name == self.default_hyperlink.name
Hyperlink Class Cannot Be Pickled Related to #3350, the `rest_framework.relations.Hyperlink` instances cannot be pickled as demonstrated with this sample: ``` >>> import pickle >>> from rest_framework.relations import Hyperlink >>> link = Hyperlink('http://example.com', 'test') >>> pickle.loads(pickle.dumps(link)) Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: __new__() missing 1 required positional argument: 'name' ``` For serializers which use the hyperlink relations, this breaks the caching of the response objects since most of the cache backends rely on pickle by default. Hyperlink Class Cannot Be Pickled Related to #3350, the `rest_framework.relations.Hyperlink` instances cannot be pickled as demonstrated with this sample: ``` >>> import pickle >>> from rest_framework.relations import Hyperlink >>> link = Hyperlink('http://example.com', 'test') >>> pickle.loads(pickle.dumps(link)) Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: __new__() missing 1 required positional argument: 'name' ``` For serializers which use the hyperlink relations, this breaks the caching of the response objects since most of the cache backends rely on pickle by default.
Thanks a lot @mlavin. I think this can be linked to another issue where cache was failing with a similar message though we were not able to identify where it did come from. Thanks a lot @mlavin. I think this can be linked to another issue where cache was failing with a similar message though we were not able to identify where it did come from.
2015-12-04T05:50:09
encode/django-rest-framework
3,705
encode__django-rest-framework-3705
[ "3596", "3596" ]
9f74b8860e64dcaeef54972db347ac1bd2afe1a3
diff --git a/rest_framework/filters.py b/rest_framework/filters.py --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -118,10 +118,9 @@ def filter_queryset(self, request, queryset, view): def to_html(self, request, queryset, view): filter_class = self.get_filter_class(view, queryset) - if filter_class: - filter_instance = filter_class(request.query_params, queryset=queryset) - else: - filter_instance = None + if not filter_class: + return None + filter_instance = filter_class(request.query_params, queryset=queryset) context = { 'filter': filter_instance }
Admin and API browser fails for views without a filter_class The JSON browser does work though. It seems crispy forms breaks because it's expecting a filter form even when there is no filter_class set on a given view. ``` VariableDoesNotExist at /api/users/ Failed lookup for key [form] in u'None' Template error: In template /Users/user/virtualenvs/ddrsite/lib/python2.7/site-packages/rest_framework/templates/rest_framework/filters/django_filter_crispyforms.html, error at line 5 (Could not get exception message) 1 : {% load crispy_forms_tags %} 2 : {% load i18n %} 3 : 4 : <h2>{% trans "Field filters" %}</h2> 5 : {% crispy filter.form %} ``` Admin and API browser fails for views without a filter_class The JSON browser does work though. It seems crispy forms breaks because it's expecting a filter form even when there is no filter_class set on a given view. ``` VariableDoesNotExist at /api/users/ Failed lookup for key [form] in u'None' Template error: In template /Users/user/virtualenvs/ddrsite/lib/python2.7/site-packages/rest_framework/templates/rest_framework/filters/django_filter_crispyforms.html, error at line 5 (Could not get exception message) 1 : {% load crispy_forms_tags %} 2 : {% load i18n %} 3 : 4 : <h2>{% trans "Field filters" %}</h2> 5 : {% crispy filter.form %} ```
Ugh! Yeah that's definitely what I thought might happen with #3560. @mcastle can you confirm this is happening with the just released 3.3.1? Update: Specifically talking about [this comment](https://github.com/tomchristie/django-rest-framework/pull/3560#issuecomment-152003241) on #3560. Yep, this happened with 3.3.1. Same for me with 3.3.1, upgraded for #3560 Thanks for confirming. So I think what should probably be happening here is that if there's no filter class the filter backend's `to_html()` returns None. It'd then be skipped [here](https://github.com/tomchristie/django-rest-framework/blob/c53c9eddfe1159a731c1ac879b3f72b1085b2fe9/rest_framework/renderers.py#L596). Ugh! Yeah that's definitely what I thought might happen with #3560. @mcastle can you confirm this is happening with the just released 3.3.1? Update: Specifically talking about [this comment](https://github.com/tomchristie/django-rest-framework/pull/3560#issuecomment-152003241) on #3560. Yep, this happened with 3.3.1. Same for me with 3.3.1, upgraded for #3560 Thanks for confirming. So I think what should probably be happening here is that if there's no filter class the filter backend's `to_html()` returns None. It'd then be skipped [here](https://github.com/tomchristie/django-rest-framework/blob/c53c9eddfe1159a731c1ac879b3f72b1085b2fe9/rest_framework/renderers.py#L596).
2015-12-05T17:10:59
encode/django-rest-framework
3,715
encode__django-rest-framework-3715
[ "3644" ]
6eb3a429936c99003db82f0816dd59093e5a0268
diff --git a/rest_framework/settings.py b/rest_framework/settings.py --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -19,6 +19,8 @@ """ from __future__ import unicode_literals +import warnings + from django.conf import settings from django.test.signals import setting_changed from django.utils import six @@ -135,6 +137,12 @@ ) +# List of settings that have been removed +REMOVED_SETTINGS = ( + "PAGINATE_BY", "PAGINATE_BY_PARAM", "MAX_PAGINATE_BY", +) + + def perform_import(val, setting_name): """ If the given setting is a string import notation, @@ -177,7 +185,7 @@ class APISettings(object): """ def __init__(self, user_settings=None, defaults=None, import_strings=None): if user_settings: - self._user_settings = user_settings + self._user_settings = self.__check_user_settings(user_settings) self.defaults = defaults or DEFAULTS self.import_strings = import_strings or IMPORT_STRINGS @@ -206,6 +214,13 @@ def __getattr__(self, attr): setattr(self, attr, val) return val + def __check_user_settings(self, user_settings): + SETTINGS_DOC = "http://www.django-rest-framework.org/api-guide/settings/" + for setting in REMOVED_SETTINGS: + if setting in user_settings: + warnings.warn("The '%s' setting has been removed. Please refer to '%s' for available settings." % (setting, SETTINGS_DOC), DeprecationWarning) + return user_settings + api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)
diff --git a/tests/test_settings.py b/tests/test_settings.py --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -1,5 +1,7 @@ from __future__ import unicode_literals +import warnings + from django.test import TestCase from rest_framework.settings import APISettings @@ -18,6 +20,19 @@ def test_import_error_message_maintained(self): with self.assertRaises(ImportError): settings.DEFAULT_RENDERER_CLASSES + def test_warning_raised_on_removed_setting(self): + """ + Make sure user is alerted with an error when a removed setting + is set. + """ + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + APISettings({ + 'MAX_PAGINATE_BY': 100 + }) + self.assertEqual(len(w), 1) + self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) + class TestSettingTypes(TestCase): def test_settings_consistently_coerced_to_list(self):
Response format change from 3.2.x to 3.3.x After upgrading DRF from 3.2.5 to 3.3.1 I noticed the api response format changed and no longer represents the format that's shown on the main page. **Api response with DRF 3.2.5 (expected response)** ``` { "count": 1, "next": null, "previous": null, "results": [ // my object results ] } ``` **Api response with DRF 3.3.1 (only returns list/array)** ``` [ // my object results ] ``` There is only 1 object returned in the result set so no additional pages exist. However, this change breaks every api consuming caller since the response format has now changed.
You probably missed previous deprecation affecting the pagination. Have a look at http://www.django-rest-framework.org/topics/3.3-announcement/#deprecations If your use case doesn't match the above cases feel free to reopen and if possible add a test case so we can figure the issue. Reopening to dig a bit deeper. @xordoquy prob correct re. related to deprecation there, but shouldn't be in a position where we've got an altered API response, rather than an error condition (eg hitting an assertion 'this no longer works') Probably worth a bit more info from @troygrosfield on most minimal way possible to replicate, so we can see if we need to be catching some particular case, and eg raising error XYZ style is no longer supported. I'll work on the testcase here in a bit, but you can plug any model into a ViewSet and have it do the same thing (alter the response format as mentioned above). @xordoquy, the deprecation link you provided didn't mention anything about altering response formats in any case which to me would warrant a major version change. I'll work on the test case but here was the code I was working with: ``` py from rest_framework.filters import DjangoFilterBackend from rest_framework.filters import OrderingFilter from rest_framework.viewsets import ReadOnlyModelViewSet from my_models.models import MyModel from .serializers import MyModelSerializer class MyModelViewSet(ReadOnlyModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer permission_classes = [] filter_backends = (OrderingFilter, DjangoFilterBackend) filter_fields = ('some_field',) ordering = ('-id',) page_query_param = 'p' ``` @troygrosfield What are your pagination settings for the example given? > Reopening to dig a bit deeper. @xordoquy prob correct re. related to deprecation there, but shouldn't be in a position where we've got an altered API response, rather than an error condition (eg hitting an assertion 'this no longer works') Makes sense to make it fail loud. Waiting for the full use case we can reproduce and will retitle the issue by then. The current settings are below. ``` # djangorestframework settings REST_FRAMEWORK = { # Use hyperlinked styles by default. # Only used if the `serializer_class` attribute is not set on a view. 'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.HyperlinkedModelSerializer', 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'api.authentication.CustomSessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAdminUser', ), 'PAGINATE_BY': 25, 'PAGINATE_BY_PARAM': 'ps', 'SEARCH_PARAM': 'q', 'MAX_PAGINATE_BY': 100 } ``` I understand some of those pagination settings have change from the deprecation post you guys outlined which I'm yet to update. However, I also never received any deprecation messages in the console when running the application which I guess I would've expected similar to what django does. Example: ``` /usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/importlib/_bootstrap.py:321: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9. return f(*args, **kwds) ``` That was the issue was changing the global settings. However, that seems to be a major change as that will most certainly break pagination for all all existing code which will require all DRF consumers to make a change. A 4.0 release version may have been more appropriate. **New global settings (for people that come across this in the future)** ``` py # djangorestframework settings REST_FRAMEWORK = { # Use hyperlinked styles by default. # Only used if the `serializer_class` attribute is not set on a view. 'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.HyperlinkedModelSerializer', 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'api.authentication.CustomSessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAdminUser', ), 'PAGE_SIZE': 25, 'PAGE_SIZE_QUERY_PARAM': 'ps', 'SEARCH_PARAM': 'q', 'MAX_PAGE_SIZE': 100 } ``` Thanks for the quick response guys! Reopening, as should probably still be taking action here, eg. - Loud error when `PAGINATE_BY` set. - Loud error when `PAGINATE_BY_PARAM` set. - Loud error when `MAX_PAGINATE_BY_SET` set. :+1: agreed. Furthermore, not convinced on first sight that `PAGE_SIZE` setting is properly documented (eg no mention in deprecation notes) Actually, paging page and page size aren't being honored now. Using the following url (with the settings listed above): - http://api.localmm.com/mymodel?p=2&ps=10 I get the following response: ``` { "count": 25, "next": null, "previous": null, "results": [ // 25 objects ] } ``` If I override the page size in the url, shouldn't that be honored? Also, `PAGE_SIZE_QUERY_PARAM` isn't documented in the settings page: - http://www.django-rest-framework.org/api-guide/settings/ Or am I required to override the `DEFAULT_PAGINATION_CLASS` and there is not more global setting for this? Ignore that last comment. I was looking at count as the number of results returned and not as the total count. So that's correct. Is it okay if i work on this issue? @Cheglader I don't think anyone's working on this at the moment.
2015-12-08T05:46:16
encode/django-rest-framework
3,723
encode__django-rest-framework-3723
[ "3718" ]
ff4bc43a2f7da91d831fc4dedfea49fde4176d33
diff --git a/rest_framework/authtoken/views.py b/rest_framework/authtoken/views.py --- a/rest_framework/authtoken/views.py +++ b/rest_framework/authtoken/views.py @@ -12,7 +12,7 @@ class ObtainAuthToken(APIView): renderer_classes = (renderers.JSONRenderer,) serializer_class = AuthTokenSerializer - def post(self, request): + def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user']
URLPathVersioning should maybe remove the version_param kwarg from subsequent view dispatch? I've been playing around with getting `URLPathVersioning` working properly, and have discovered what might be a bug, or maybe just undocumented (or obvious and expected) behaviour. urlconf contains: ``` from rest_framework.authtoken.views import obtain_auth_token # ... api_patterns = [ url(r'^', include(router.urls), name='api-root'), url(r'^auth-token/', obtain_auth_token, name='api-auth-token'), ] urlpatterns = [ url(r'^api/(?P<version>v\d{1,})/', include(api_patterns)), # ... ] ``` When testing, with something like: ``` url = reverse('api-auth-token', kwargs=dict(version='v1')) self.client.post(url, data, format='json') ``` I get an exception that ultimately ends in: ``` File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 463, in dispatch response = handler(request, *args, **kwargs) TypeError: post() got an unexpected keyword argument 'version' ``` Investigation shows that the `ObtainAuthToken.post()` method doesn't accept any kwargs, so it's clearly failing because it's getting version passed in by default from the rest of the versionating mechanism. Simplest fix would be to just fix the definition of `ObtainAuthToken.post(self, request, **kwargs)`, but it made me wonder if it'll be an issue for other views that are receiving a somewhat unexpected kwarg, and which is by intent already available to them in `request.version`. If there's no good reason to keep it around after extracting it, would it make sense to clean it from the view args in `views.APIView` somewhere in the initial pre-dispatch phases, maybe as simple as a `kwargs.pop(request.versioning_scheme.version_param, None)` (with some checks around it) in the appropriate place? I'm currently subclassing `authtoken.ObtainAuthToken` to do exactly this in `post()`, but I figured it might make sense to raise a a more general issue.
I'd rather fix the AuthToken to accept the extra kwarg. Thanks for reporting. > I'd rather fix the AuthToken to accept the extra kwarg. Seems reasonable.
2015-12-11T10:17:06
encode/django-rest-framework
3,731
encode__django-rest-framework-3731
[ "3726" ]
6eb3a429936c99003db82f0816dd59093e5a0268
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1061,6 +1061,9 @@ def to_internal_value(self, value): self.fail('invalid', format=humanized_format) def to_representation(self, value): + if not value: + return None + output_format = getattr(self, 'format', api_settings.DATETIME_FORMAT) if output_format is None: @@ -1118,11 +1121,11 @@ def to_internal_value(self, value): self.fail('invalid', format=humanized_format) def to_representation(self, value): - output_format = getattr(self, 'format', api_settings.DATE_FORMAT) - if not value: return None + output_format = getattr(self, 'format', api_settings.DATE_FORMAT) + if output_format is None: return value @@ -1183,6 +1186,9 @@ def to_internal_value(self, value): self.fail('invalid', format=humanized_format) def to_representation(self, value): + if not value: + return None + output_format = getattr(self, 'format', api_settings.TIME_FORMAT) if output_format is None:
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -959,7 +959,9 @@ class TestDateTimeField(FieldValues): } outputs = { datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00', - datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): '2001-01-01T13:00:00Z' + datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): '2001-01-01T13:00:00Z', + None: None, + '': None, } field = serializers.DateTimeField(default_timezone=timezone.UTC()) @@ -1028,7 +1030,9 @@ class TestTimeField(FieldValues): '99:99': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]].'], } outputs = { - datetime.time(13, 00): '13:00:00' + datetime.time(13, 00): '13:00:00', + None: None, + '': None, } field = serializers.TimeField()
`DateTimeField` does not handle empty values correctly Reference: https://github.com/tomchristie/django-rest-framework/pull/2869 https://github.com/tomchristie/django-rest-framework/issues/2687 This issue was fixed by 2869 for DateField and need the same fix for DateTimeField. <pre> def to_representation(self, value): if not value: return None </pre> If I have a serializer with start = serializers.DateTimeField(required=False) then I should not have to supply a value but if I dont supply a value I get the below error. <pre> 2015-12-12 00:31:18,347 ERROR RequestDetailsHandler::get::371 <type 'exceptions.AttributeError'> Traceback (most recent call last): File "/x/local/aitv2/automatic_integration_v2/eci/handlers/RequestDetailsHandler.py", line 368, in get return response.Response(RequestDetailsResponseSerializer(response_data).data, File "/Users/miparker/.virtualenvs/aitv3/lib/python2.7/site-packages/rest_framework/serializers.py", line 503, in data ret = super(Serializer, self).data File "/Users/miparker/.virtualenvs/aitv3/lib/python2.7/site-packages/rest_framework/serializers.py", line 239, in data self._data = self.to_representation(self.instance) File "/Users/miparker/.virtualenvs/aitv3/lib/python2.7/site-packages/rest_framework/serializers.py", line 472, in to_representation ret[field.field_name] = field.to_representation(attribute) File "/Users/miparker/.virtualenvs/aitv3/lib/python2.7/site-packages/rest_framework/serializers.py", line 614, in to_representation self.child.to_representation(item) for item in iterable File "/Users/miparker/.virtualenvs/aitv3/lib/python2.7/site-packages/rest_framework/serializers.py", line 472, in to_representation ret[field.field_name] = field.to_representation(attribute) File "/Users/miparker/.virtualenvs/aitv3/lib/python2.7/site-packages/rest_framework/serializers.py", line 472, in to_representation ret[field.field_name] = field.to_representation(attribute) File "/Users/miparker/.virtualenvs/aitv3/lib/python2.7/site-packages/rest_framework/fields.py", line 1068, in to_representation value = value.isoformat() AttributeError: 'str' object has no attribute 'isoformat' </pre>
2015-12-13T19:23:29
encode/django-rest-framework
3,805
encode__django-rest-framework-3805
[ "3804" ]
c46ed66d0aff22637b526c791ed60032b274733c
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -1212,7 +1212,7 @@ def get_extra_kwargs(self): Return a dictionary mapping field names to a dictionary of additional keyword arguments. """ - extra_kwargs = getattr(self.Meta, 'extra_kwargs', {}) + extra_kwargs = copy.deepcopy(getattr(self.Meta, 'extra_kwargs', {})) read_only_fields = getattr(self.Meta, 'read_only_fields', None) if read_only_fields is not None:
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 @@ -909,3 +909,34 @@ class Meta: serializer = TestSerializer() assert serializer.fields['decimal_field'].max_value == 3 + + +class TestMetaInheritance(TestCase): + def test_extra_kwargs_not_altered(self): + class TestSerializer(serializers.ModelSerializer): + non_model_field = serializers.CharField() + + class Meta: + model = OneFieldModel + read_only_fields = ('char_field', 'non_model_field') + fields = read_only_fields + extra_kwargs = {} + + class ChildSerializer(TestSerializer): + class Meta(TestSerializer.Meta): + read_only_fields = () + + test_expected = dedent(""" + TestSerializer(): + char_field = CharField(read_only=True) + non_model_field = CharField() + """) + + child_expected = dedent(""" + ChildSerializer(): + char_field = CharField(max_length=100) + non_model_field = CharField() + """) + self.assertEqual(unicode_repr(ChildSerializer()), child_expected) + self.assertEqual(unicode_repr(TestSerializer()), test_expected) + self.assertEqual(unicode_repr(ChildSerializer()), child_expected)
ModelSerializer.get_extra_kwargs() should not alter Meta.extra_kwargs ModelSerializer.get_extra_kwargs() currently does: ``` extra_kwargs = getattr(self.Meta, 'extra_kwargs', {}) <snip> extra_kwargs[field_name] = kwargs ``` If extra_kwargs is defined in the Meta class, this alters the value of it. To avoid this, get_extra_kwargs() should update a _copy_ of it: ``` extra_kwargs = copy.deepcopy(getattr(self.Meta, 'extra_kwargs', {})) ``` When the value of Meta.extra_kwargs is updated, it causes side effects for child serializers that inherit from Meta. (I know that this is officially not recommended, but the doc does show how to do it.) For example: ``` >>> from django.contrib.auth.models import User >>> from rest_framework import serializers >>> >>> class UserSerializer(serializers.ModelSerializer): ... class Meta: ... model = User ... read_only_fields = ('username', 'email') ... fields = read_only_fields ... extra_kwargs = {} ... >>> class ChildUserSerializer(UserSerializer): ... class Meta(UserSerializer.Meta): ... read_only_fields = () ... ``` Before instantiating the base class, the child class looks correct: ``` >>> ChildUserSerializer.Meta.extra_kwargs {} >>> print ChildUserSerializer() ChildUserSerializer(): username = CharField(help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=30, validators=[<django.core.validators.RegexValidator object>, <UniqueValidator(queryset=User.objects.all())>]) email = EmailField(allow_blank=True, label='Email address', max_length=254, required=False) ``` But after instantiating the base class, the child class' Meta.extra_kwargs is corrupted: ``` >>> print UserSerializer() UserSerializer(): username = CharField(help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', read_only=True) email = EmailField(label='Email address', read_only=True) >>> ChildUserSerializer.Meta.extra_kwargs {'username': {u'read_only': True}, 'email': {u'read_only': True}} >>> print ChildUserSerializer() ChildUserSerializer(): username = CharField(help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', read_only=True) email = EmailField(label='Email address', read_only=True) ```
Seems valid. Pull request with test case would be next step here.
2016-01-06T20:19:10
encode/django-rest-framework
3,815
encode__django-rest-framework-3815
[ "3786" ]
69fb34b0db4c7b629d61848265c13aa7556bb45a
diff --git a/rest_framework/settings.py b/rest_framework/settings.py --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -196,7 +196,7 @@ def user_settings(self): return self._user_settings def __getattr__(self, attr): - if attr not in self.defaults.keys(): + if attr not in self.defaults: raise AttributeError("Invalid API setting: '%s'" % attr) try:
Rest Framework Settings file Performs an O(n) operation on settings access that could be O(1) Calling .keys() on a dictionary returns an iterable, so doing a membership test against that iterable is an O(n) operation. By not including a call to .keys(), the same effect will be attained in O(1) time. https://github.com/tomchristie/django-rest-framework/blob/af0ea8ef5136da30cb058b10a493d36619d24add/rest_framework/settings.py#L199
@CuriousG102 mind submitting a PR to discuss further? Sounds like a smal improvement since values are cached after that but still possible Ah. I didn't notice the caching going on on line 214. That does indeed make this a small improvement. Otherwise it might have been a bit bigger depending on how often settings are accessed. In any case I'll make a PR after New Years celebrations. Thanks and enjoy the celebrations !
2016-01-08T18:41:57
encode/django-rest-framework
3,820
encode__django-rest-framework-3820
[ "3710" ]
efe2c3739d620e00ab5dcd72e14644cd2b15c9cc
diff --git a/rest_framework/utils/html.py b/rest_framework/utils/html.py --- a/rest_framework/utils/html.py +++ b/rest_framework/utils/html.py @@ -80,10 +80,12 @@ def parse_html_dict(dictionary, prefix=''): """ ret = MultiValueDict() regex = re.compile(r'^%s\.(.+)$' % re.escape(prefix)) - for field, value in dictionary.items(): + for field in dictionary: match = regex.match(field) if not match: continue key = match.groups()[0] - ret[key] = value + value = dictionary.getlist(field) + ret.setlist(key, value) + return ret
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 @@ -167,3 +167,32 @@ def test_empty_not_allowed_if_allow_empty_is_set_to_false(self): expected_errors = {'not_allow_empty': {'non_field_errors': [serializers.ListSerializer.default_error_messages['empty']]}} assert serializer.errors == expected_errors + + +class TestNestedSerializerWithList: + def setup(self): + class NestedSerializer(serializers.Serializer): + example = serializers.MultipleChoiceField(choices=[1, 2, 3]) + + class TestSerializer(serializers.Serializer): + nested = NestedSerializer() + + self.Serializer = TestSerializer + + def test_nested_serializer_with_list_json(self): + input_data = { + 'nested': { + 'example': [1, 2], + } + } + serializer = self.Serializer(data=input_data) + + assert serializer.is_valid() + assert serializer.validated_data['nested']['example'] == set([1, 2]) + + def test_nested_serializer_with_list_multipart(self): + input_data = QueryDict('nested.example=1&nested.example=2') + serializer = self.Serializer(data=input_data) + + assert serializer.is_valid() + assert serializer.validated_data['nested']['example'] == set([1, 2])
Test case for #3598 There is no fix for this test case, just test case which fails. I don't know how to fix it in a good way. See more investigation details in issue #3598
2016-01-11T12:40:33
encode/django-rest-framework
3,860
encode__django-rest-framework-3860
[ "3858" ]
06dd55ac1ca6281af2b41b3ad12cc33a2fde2fce
diff --git a/rest_framework/authtoken/models.py b/rest_framework/authtoken/models.py --- a/rest_framework/authtoken/models.py +++ b/rest_framework/authtoken/models.py @@ -22,6 +22,14 @@ class Token(models.Model): on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) + class Meta: + # Work around for a bug in Django: + # https://code.djangoproject.com/ticket/19422 + # + # Also see corresponding ticket: + # https://github.com/tomchristie/django-rest-framework/issues/705 + abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS + def save(self, *args, **kwargs): if not self.key: self.key = self.generate_key()
Re-add conditional abstract setting to Token model When attempting to use [a custom model](https://github.com/incuna/django-user-management/blob/master/user_management/api/models.py#L42) instead of DRF's built-in `Token`, Django tries very hard to include the `Token` model even if `rest_framework.authtoken` isn't in `INSTALLED_APPS`. Attempting to run migrations on a fresh database will explode with a missing user model error, and an already-set-up database will have a `Token` table added to it (which also means the user model gets an unwanted `auth_token` `OneToOne` field on it). I believe a simple fix for this behaviour is to reinstate [the `Meta` `abstract` setting](https://github.com/tomchristie/django-rest-framework/blob/af0ea8ef5136da30cb058b10a493d36619d24add/rest_framework/authtoken/models.py#L24-L30) in the `Token` model. I spent a day or so digging for other ways to avoid using `Token` in the project I was working on and couldn't find anything, but there may also be other fixes.
Should be fixed by #3785 Unfortunately, that's the exact commit that introduces the breakage. The delayed import doesn't seem to help. I haven't been able to figure out why. When I was experimenting and trying to figure out how to work around this, I even deleted the entire `TokenAuthentication` class, and the problem persisted. I think the `Token` model is being picked up through other means. (We're on Django 1.8.) Do you have some sample project to reproduce the issue ? Not at the moment (it's a private project). I'll try to get some time to make one. I imagine it would involve: - `rest_framework` in `INSTALLED_APPS` (but not `rest_framework.authtoken`) - A `User` model exists and `AUTH_USER_MODEL` is set - A test calls `_meta.get_all_field_names()` on that user model I don't know if the migration ordering issue will occur for the test project - it depends on whether `Token` is migrated before `User`. If it does, trying to run the tests will blow up with the SQL error about a missing relation. If that error doesn't appear, the test should show that `auth_token` is a field on the `User` model. Now that I read this again, I think I get the issue and indeed the Token should be left abstract if the app isn't in the INSTALLED_APPS. :+1: Thanks :)
2016-01-21T12:29:47
encode/django-rest-framework
3,928
encode__django-rest-framework-3928
[ "3817" ]
aeda2adeea49b6cf7556f7641c01b39d4cf3a7c4
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -7,6 +7,17 @@ from setuptools import setup +try: + from pypandoc import convert + + def read_md(f): + return convert(f, 'rst') +except ImportError: + print("warning: pypandoc module not found, could not convert Markdown to RST") + + def read_md(f): + return open(f, 'r').read() + def get_version(package): """ @@ -45,6 +56,10 @@ def get_package_data(package): if sys.argv[-1] == 'publish': + try: + import pypandoc + except ImportError: + print("pypandoc not installed.\nUse `pip install pypandoc`.\nExiting.") if os.system("pip freeze | grep wheel"): print("wheel not installed.\nUse `pip install wheel`.\nExiting.") sys.exit() @@ -68,6 +83,7 @@ def get_package_data(package): url='http://www.django-rest-framework.org', license='BSD', description='Web APIs for Django, made easy.', + long_description=read_md('README.md'), author='Tom Christie', author_email='[email protected]', # SEE NOTE BELOW (*) packages=get_packages('rest_framework'),
Use Pandoc to publish RestructuredText to PyPI A little call out to Pandoc during the `publish` setup.py command would mean this: ![screen shot 2016-01-08 at 6 49 35 pm](https://cloud.githubusercontent.com/assets/62857/12213963/abb63344-b638-11e5-9882-11d13fe809af.png) would look more like: ![screen shot 2016-01-08 at 6 50 59 pm](https://cloud.githubusercontent.com/assets/62857/12213970/cdad432a-b638-11e5-95a8-36323af1d04a.png) 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
2016-02-12T12:17:46
encode/django-rest-framework
3,943
encode__django-rest-framework-3943
[ "3937" ]
79dad012b00501792805e71cde6b9ae6d5944899
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -370,6 +370,8 @@ def get_initial(self): Return a value to use when the field is being returned as a primitive value, without any object instance. """ + if callable(self.initial): + return self.initial() return self.initial def get_value(self, dictionary):
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -191,6 +191,24 @@ def test_initial(self): } +class TestInitialWithCallable: + def setup(self): + def initial_value(): + return 123 + + class TestSerializer(serializers.Serializer): + initial_field = serializers.IntegerField(initial=initial_value) + self.serializer = TestSerializer() + + def test_initial_should_accept_callable(self): + """ + Follows the default ``Field.initial`` behaviour where they accept a + callable to produce the initial value""" + assert self.serializer.data == { + 'initial_field': 123, + } + + class TestLabel: def setup(self): class TestSerializer(serializers.Serializer):
Field.initial does not accept callables While trying to use the `Field.initial` property just like I'm used to do that with regular Django fields, in DRF this property does not accept a callable. When rendering serializer fields in HTML the `initial` becomes something like `<function func_name_here0x0000000>` Example: ``` def some_callable(): return uuid4().hex class FooSerializer(serializers.Serializer): test_field = serializers.CharField(initial=some_callable) ``` The expected behaviour (in a default Django field) would be a input with a `uuid` as it's initial value, but DRF tries to render the function object.
2016-02-17T09:55:38
encode/django-rest-framework
4,021
encode__django-rest-framework-4021
[ "3751" ]
6b1125a2b6c0a28cd3c584f47429f33a2190cb8f
diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py --- a/rest_framework/metadata.py +++ b/rest_framework/metadata.py @@ -137,7 +137,9 @@ def get_field_info(self, field): elif getattr(field, 'fields', None): field_info['children'] = self.get_serializer_info(field) - if not field_info.get('read_only') and hasattr(field, 'choices'): + if (not field_info.get('read_only') and + not isinstance(field, serializers.RelatedField) and + hasattr(field, 'choices')): field_info['choices'] = [ { 'value': choice_value,
diff --git a/tests/test_metadata.py b/tests/test_metadata.py --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -11,6 +11,8 @@ from rest_framework.request import Request from rest_framework.test import APIRequestFactory +from .models import BasicModel + request = Request(APIRequestFactory().options('/')) @@ -261,10 +263,21 @@ def get_serializer(self): view = ExampleView.as_view(versioning_class=scheme) view(request=request) + +class TestSimpleMetadataFieldInfo(TestCase): def test_null_boolean_field_info_type(self): options = metadata.SimpleMetadata() field_info = options.get_field_info(serializers.NullBooleanField()) - assert field_info['type'] == 'boolean' + self.assertEqual(field_info['type'], 'boolean') + + def test_related_field_choices(self): + options = metadata.SimpleMetadata() + BasicModel.objects.create() + with self.assertNumQueries(0): + field_info = options.get_field_info( + serializers.RelatedField(queryset=BasicModel.objects.all()) + ) + self.assertNotIn('choices', field_info) class TestModelSerializerMetadata(TestCase):
OPTIONS fetches and shows all possible foreign keys in choices field I have an object with foreign keys and when I load a `OPTIONS` request for that object type, it shows me a truly insane JSON object with every possible value for the foreign key (there are millions!) So, for example, I have this object: ``` class OpinionCluster(models.Model): """A class representing a cluster of court opinions.""" docket = models.ForeignKey( Docket, help_text="The docket that the opinion cluster is a part of", related_name="clusters", ) ``` Which is serialized with: ``` python class OpinionClusterSerializer(serializers.HyperlinkedModelSerializer): docket = serializers.HyperlinkedRelatedField( many=False, view_name='docket-detail', queryset=Docket.objects.all(), style={'base_template': 'input.html'}, ) ``` When I load this with `OPTIONS`, I get back something that contains: ``` json "docket": { "type": "field", "required": true, "read_only": false, "label": "Docket", "choices": [ { "display_name": "4: United States v. Goodwin", "value": "http://127.0.0.1:8000/api/rest/v3/dockets/4/" }, { "display_name": "5: Quality Cleaning Products v. SCA Tissue of North America", "value": "http://127.0.0.1:8000/api/rest/v3/dockets/5/" }, ....millions more.... ``` I know that there's a way to [disable listing these items](http://www.django-rest-framework.org/api-guide/relations/#select-field-cutoffs) in the form of the HTML view, but in the OPTIONS request we need better default functionality than displaying millions of records.
I made an attempt at resolving this by overwriting the metadata class as mentioned above, but that doesn't work because all you can do at that stage is remove data that's already been pulled from the DB. Meaning: If you do this, you still fetch millions of objects from the DB, you just don't pass those values to the front end. The fix for this, unless I'm mistaken, is one of: - Remove the OPTIONS request from the API (Sad, but would work) - Make the endpoints read_only (Sad, breaks the API) - Some sort of fix in DRF Thanks for any help or other ideas. Milestoning to raise the priority. Agreed. This is odd behavior, treating FK fields as a choices field. Makes OPTIONS a bear trap. I think the fix is to alter the conditional at https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/metadata.py#L140 to not do the choices thing on FK fields, and then possibly to do something else for them. +1 (This may better be submitted as a separate issue. Let me know if I should.) Also note that if one of those choice fields is a settings.AUTH_USER_MODEL, e.g. a owned_by field, it puts actual account data in there. A censored snipped of the returned JSON: ``` "owned_by":{ "type":"field", "required":true, "read_only":false, "label":"Owned by", "choices":[ {"display_name":"engineering+admin@<us>.com","value":"18"}, {"display_name":"engineering+notanadmin@<us>.com","value":"19"},... ``` IMHO, the default shouldn't do this considering the security risk. Is there any known work around while this issue is being sorted out? I'm having the security issue @fleur described with a ForeignKey to AUTH_USER_MODEL. I've made these fields read_only. Works for our implementation, but sucks otherwise. Now there seems to be two reasons to fix this: 1. Information leakage. 2. Performance. In order to work around this limitation you'll need to implement your own `SimpleMetadata` subclass: ``` python from rest_framework.metadata import SimpleMetadata from rest_framework.relations import RelatedField class NoRelatedFieldChoicesMetadata(SimpleMetadata): def get_field_info(self, field): related_field = isinstance(field, RelatedField) # Remove the related fields choices since they can end up with many values. if related_field: field.queryset = field.queryset.none() field_info = super(NoRelatedFieldChoicesMetaData, self).get_field_info(field) # Remove the empty `choices` list. if related_field: field_info.pop('choices') return field_info ``` You can set it per serializer using the `metadata_class` attribute or per-project using the `REST_FRAMEWORK['DEFAULT_METADATA_CLASS']` setting. @charettes beware, however, that this doesn't fix the performance issue. From my earlier comment: > I made an attempt at resolving this by overwriting the metadata class as mentioned above, but that doesn't work because all you can do at that stage is remove data that's already been pulled from the DB. Meaning: If you do this, you still fetch millions of objects from the DB, you just don't pass those values to the front end. There is definitely a performance issue here when a field has a large number of possible options. I honestly have no idea what the best way to fix it would be without breaking backwards compatibility. > ...information leakage... This is something I keep hearing whenever this comes up: that DRF is leaking information that it shouldn't be. And I guess it's true, you aren't intending for that information to be public. I mean, why should anyone be able to get a list of the users that are possible values for the field? But that's usually a sign that you are not restricting your querysets down to only the objects that should be allowed. All objects that DRF lists in the `OPTIONS` request are valid inputs to the field, so if there are objects showing up in the list then you probably aren't filtering them out for the field. @mlissner note that I use `queryset.none()` to avoid any queryset from being performed. > I mean, why should anyone be able to get a list of the users that are possible values for the field? This is a common request to have all the related values within the option to let front end apps fill choice fields. Note that it doesn't show read only fields. @charettes That actually does look promising. You're right, that may be a workaround for the performance aspect of this issue.
2016-03-29T17:26:42
encode/django-rest-framework
4,040
encode__django-rest-framework-4040
[ "4039" ]
6a29196712386416c54ebf718c53dbc297369f8a
diff --git a/rest_framework/views.py b/rest_framework/views.py --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -162,7 +162,7 @@ def permission_denied(self, request, message=None): """ If request is not permitted, determine what kind of exception to raise. """ - if not request.successful_authenticator: + if request.authenticators and not request.successful_authenticator: raise exceptions.NotAuthenticated() raise exceptions.PermissionDenied(detail=message)
diff --git a/tests/test_authentication.py b/tests/test_authentication.py --- a/tests/test_authentication.py +++ b/tests/test_authentication.py @@ -321,3 +321,28 @@ def test_failing_auth_accessed_in_renderer(self): response = self.view(request) content = response.render().content self.assertEqual(content, b'not authenticated') + + +class NoAuthenticationClassesTests(TestCase): + def test_permission_message_with_no_authentication_classes(self): + """ + An unauthenticated request made against a view that containes no + `authentication_classes` but do contain `permissions_classes` the error + code returned should be 403 with the exception's message. + """ + + class DummyPermission(permissions.BasePermission): + message = 'Dummy permission message' + + def has_permission(self, request, view): + return False + + request = factory.get('/') + view = MockView.as_view( + authentication_classes=(), + permission_classes=(DummyPermission,), + ) + response = view(request) + self.assertEqual(response.status_code, + status.HTTP_403_FORBIDDEN) + self.assertEqual(response.data, {'detail': 'Dummy permission message'})
View with no `authentication_classes` failing permission should raise 403 ## 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. (#4040) ## Steps to reproduce Create a view with no `authentication_classes` set and a `permission_classes` set. Query the view in order to fail the permission check. ## Expected behavior A 403 with the permission's message should be returned. ## Actual behavior A 401 with a "Not authenticated" message is returned. This is slightly related to #3754, the main difference being that this issue is only concerned about view with no `authentication_classes` and #3754 is about prioritizing permissions over authentication in views with `authentication_classes`.
2016-04-07T14:45:12
encode/django-rest-framework
4,049
encode__django-rest-framework-4049
[ "4048" ]
08dad04b1989c69295a3536e186e480fde42e460
diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -12,6 +12,7 @@ from collections import OrderedDict from django import forms +from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.paginator import Page from django.http.multipartparser import parse_header @@ -657,7 +658,8 @@ def get_context(self, data, accepted_media_type, renderer_context): 'display_edit_forms': bool(response.status_code != 403), - 'api_settings': api_settings + 'api_settings': api_settings, + 'csrf_cookie_name': settings.CSRF_COOKIE_NAME, } return context
Support customized CSRF token cookie 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. - [ ] 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. Activate `SessionAuthentication` for all views, or a single view. 2. Set [`CSRF_COOKIE_NAME`](https://docs.djangoproject.com/en/1.8/ref/settings/#csrf-cookie-name) to a non-default value. 3. Login. 4. Navigate to a view secured by `SessionAuthentication` via the Browseable API. 5. Attempt to a PATCH/POST/PUT operation. ## Expected behavior The action should be completed successfully. ## Actual behavior The action fails with HTTP status 403, and the message `CSRF Failed: CSRF token missing or incorrect.`. csrf.js has the cookie name hardcoded: https://github.com/tomchristie/django-rest-framework/blob/bb56ca46ed6c07db0146dbdc61c672ff25f127de/rest_framework/static/rest_framework/js/csrf.js#L36. It should instead get the cookie name from settings.
2016-04-12T03:07:19
encode/django-rest-framework
4,090
encode__django-rest-framework-4090
[ "4089" ]
a9bbb502cb0fb516deb444e1b58762cd3edb0c6d
diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py --- a/rest_framework/authentication.py +++ b/rest_framework/authentication.py @@ -4,6 +4,7 @@ from __future__ import unicode_literals import base64 +import binascii from django.contrib.auth import authenticate, get_user_model from django.middleware.csrf import CsrfViewMiddleware @@ -77,7 +78,7 @@ def authenticate(self, request): try: auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':') - except (TypeError, UnicodeDecodeError): + except (TypeError, UnicodeDecodeError, binascii.Error): msg = _('Invalid basic header. Credentials not correctly base64 encoded.') raise exceptions.AuthenticationFailed(msg)
diff --git a/tests/test_authentication.py b/tests/test_authentication.py --- a/tests/test_authentication.py +++ b/tests/test_authentication.py @@ -85,6 +85,14 @@ def test_post_json_passing_basic_auth(self): response = self.csrf_client.post('/basic/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, status.HTTP_200_OK) + def test_regression_handle_bad_base64_basic_auth_header(self): + """Ensure POSTing JSON over basic auth with incorrectly padded Base64 string is handled correctly""" + # regression test for issue in 'rest_framework.authentication.BasicAuthentication.authenticate' + # https://github.com/tomchristie/django-rest-framework/issues/4089 + auth = 'Basic =a=' + response = self.csrf_client.post('/basic/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth) + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + def test_post_form_failing_basic_auth(self): """Ensure POSTing form over basic auth without correct credentials fails""" response = self.csrf_client.post('/basic/', {'example': 'example'})
HTTP basic auth: incorrectly padded base64 string causes an unhandled exception The problem is in `rest_framework.authentication.BasicAuthentication.authenticate`. The call to `base64.b64decode` does not catch `binascii.Error`, which can be raised by `binascii.a2b_base64` This assumes we want to handle that error and not let it propagate up the stack. I can't think of any reason not to, specially considering the raised exception message: > Invalid basic header. Credentials not correctly base64 encoded. ## Stacktrace ``` Traceback (most recent call last): File "/app/.heroku/python/lib/python3.4/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.4/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.4/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.4/site-packages/rest_framework/views.py", line 466, in dispatch response = self.handle_exception(exc) File "/app/.heroku/python/lib/python3.4/site-packages/rest_framework/views.py", line 454, in dispatch self.initial(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.4/site-packages/rest_framework/views.py", line 376, in initial self.perform_authentication(request) File "/app/.heroku/python/lib/python3.4/site-packages/rest_framework/views.py", line 310, in perform_authentication request.user File "/app/.heroku/python/lib/python3.4/site-packages/rest_framework/request.py", line 353, in __getattribute__ return super(Request, self).__getattribute__(attr) File "/app/.heroku/python/lib/python3.4/site-packages/rest_framework/request.py", line 193, in user self._authenticate() File "/app/.heroku/python/lib/python3.4/site-packages/rest_framework/request.py", line 316, in _authenticate user_auth_tuple = authenticator.authenticate(self) File "/app/.heroku/python/lib/python3.4/site-packages/rest_framework/authentication.py", line 78, in authenticate auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':') File "/app/.heroku/python/lib/python3.4/base64.py", line 90, in b64decode return binascii.a2b_base64(s) binascii.Error: Incorrect padding ``` ## 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.)
2016-05-02T18:40:08
encode/django-rest-framework
4,098
encode__django-rest-framework-4098
[ "4079" ]
ffdac0d93619b7ec6039b94ce0e563f0330faeb1
diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -36,10 +36,11 @@ def _positive_int(integer_string, strict=False, cutoff=None): def _divide_with_ceil(a, b): """ - Returns 'a' divded by 'b', with any remainder rounded up. + Returns 'a' divided by 'b', with any remainder rounded up. """ if a % b: return (a // b) + 1 + return a // b @@ -358,17 +359,24 @@ def get_previous_link(self): def get_html_context(self): base_url = self.request.build_absolute_uri() - current = _divide_with_ceil(self.offset, self.limit) + 1 - # The number of pages is a little bit fiddly. - # We need to sum both the number of pages from current offset to end - # plus the number of pages up to the current offset. - # When offset is not strictly divisible by the limit then we may - # end up introducing an extra page as an artifact. - final = ( - _divide_with_ceil(self.count - self.offset, self.limit) + - _divide_with_ceil(self.offset, self.limit) - ) - if final < 1: + + if self.limit: + current = _divide_with_ceil(self.offset, self.limit) + 1 + + # The number of pages is a little bit fiddly. + # We need to sum both the number of pages from current offset to end + # plus the number of pages up to the current offset. + # When offset is not strictly divisible by the limit then we may + # end up introducing an extra page as an artifact. + final = ( + _divide_with_ceil(self.count - self.offset, self.limit) + + _divide_with_ceil(self.offset, self.limit) + ) + + if final < 1: + final = 1 + else: + current = 1 final = 1 if current > final:
diff --git a/tests/test_pagination.py b/tests/test_pagination.py --- a/tests/test_pagination.py +++ b/tests/test_pagination.py @@ -505,6 +505,31 @@ def test_max_limit(self): assert content.get('next') == next_url assert content.get('previous') == prev_url + def test_limit_zero(self): + """ + A limit of 0 should return empty results. + """ + request = Request(factory.get('/', {'limit': 0, 'offset': 10})) + queryset = self.paginate_queryset(request) + context = self.get_html_context() + content = self.get_paginated_content(queryset) + + assert context == { + 'previous_url': 'http://testserver/?limit=0&offset=10', + 'page_links': [ + PageLink( + url='http://testserver/?limit=0', + number=1, + is_active=True, + is_break=False + ) + ], + 'next_url': 'http://testserver/?limit=0&offset=10' + } + + assert queryset == [] + assert content.get('results') == [] + class TestCursorPagination: """
LimitOffset pagination crashes Browseable API when limit=0 We are using `LimitOffsetPagination` on all our endpoints, and noticed that sending `limit=0` to the browsable api causes a crash. Getting `json` output (either from an xmlhttprequest or from `format=json`) does not crash. ## Steps to reproduce 1. Install `LimitOffsetPagination` as the default pagination 2. Open a `list` (ours are `ModelViewSet`) in the browser 3. Set the query string to `?limit=0&offset=20` 4. _boom_ _Notes_ We use a custom LimitOffset pagination, which just overrides the max and default limit Using DRF 3.3.2 ## Expected behavior Should show the browsable api for the endpoint, with the following data: ``` { "count":148, "next":"https://api.co/page/?limit=0&offset=20", "previous":"https://api.co/page/?limit=0&offset=20", "results":[] } ``` ## Actual behavior ``` Exception Type: ZeroDivisionError Exception Value: integer division or modulo by zero Exception Location: .../venv/local/lib/python2.7/site-packages/rest_framework/pagination.py in _divide_with_ceil, line 41 Python Executable: /usr/local/bin/uwsgi .../venv/local/lib/python2.7/site-packages/rest_framework/pagination.py in get_html_context current = _divide_with_ceil(self.offset, self.limit) + 1 ... ▼ Local vars self <mysite.LargePageination object at 0x7f614e677bd0> base_url 'https://api.co/page/?limit=0&offset=20' .../venv/local/lib/python2.7/site-packages/rest_framework/pagination.py in _divide_with_ceil if a % b: ... ▼ Local vars a 20 b 0 ```
I am able to reproduce this behaviour. Also this is not really a crash, it just displays you an error message as you have Debug Mode set to True in your Django Project. Though I guess there is no harm done in catching this and just returning an empty result. Thanks for confirming @anx-ckreuzberger! Agree - this ought to be resolved. Thanks for confirming too. It's nice to know I'm not crazy (though I did try it on a fresh project). Not sure how it's not a crash, it's a `div by 0`. The stack is well protected enough that this sends back a 500, so I guess it's not a core dump ;) Well, no core dump, just an uncaught exception popping up in Sentry.
2016-05-04T03:19:13
encode/django-rest-framework
4,107
encode__django-rest-framework-4107
[ "4105" ]
5ac96851398cdecede9c294856c3981b5053d870
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1191,7 +1191,7 @@ def to_internal_value(self, value): self.fail('invalid', format=humanized_format) def to_representation(self, value): - if not value: + if value in (None, ''): return None output_format = getattr(self, 'format', api_settings.TIME_FORMAT)
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1063,7 +1063,8 @@ class TestTimeField(FieldValues): '99:99': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]].'], } outputs = { - datetime.time(13, 00): '13:00:00', + datetime.time(13, 0): '13:00:00', + datetime.time(0, 0): '00:00:00', '00:00:00': '00:00:00', None: None, '': None,
TimeField render returns None instead of 00:00:00 ## 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. Create a model A with a TimeField B in it. 2. Create an instance C of the model A in which the TimeField B has a "00:00:00" value (midnight). 3. Create a default DRF serializer D for the model A. 4. Render the object C through serializer D ## Expected behavior It should render the TimeField B as "00:00:00". ## Actual behavior It actually gets rendered as None.
2016-05-09T08:04:44
encode/django-rest-framework
4,146
encode__django-rest-framework-4146
[ "3844" ]
35ace2e9ec1cdbbb5d925e5cf53d7c28803c93ef
diff --git a/rest_framework/validators.py b/rest_framework/validators.py --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -35,7 +35,7 @@ def set_context(self, serializer_field): """ # Determine the underlying model field name. This may not be the # same as the serializer field name if `source=<>` is set. - self.field_name = serializer_field.source_attrs[0] + self.field_name = serializer_field.source_attrs[-1] # Determine the existing instance, if this is an update operation. self.instance = getattr(serializer_field.parent, 'instance', None) @@ -174,8 +174,8 @@ def set_context(self, serializer): """ # Determine the underlying model field names. These may not be the # same as the serializer field names if `source=<>` is set. - self.field_name = serializer.fields[self.field].source_attrs[0] - self.date_field_name = serializer.fields[self.date_field].source_attrs[0] + self.field_name = serializer.fields[self.field].source_attrs[-1] + self.date_field_name = serializer.fields[self.date_field].source_attrs[-1] # Determine the existing instance, if this is an update operation. self.instance = getattr(serializer, 'instance', None)
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -4,6 +4,7 @@ from django.test import TestCase from rest_framework import serializers +from rest_framework.validators import UniqueValidator def dedent(blocktext): @@ -22,6 +23,20 @@ class Meta: model = UniquenessModel +class RelatedModel(models.Model): + user = models.OneToOneField(UniquenessModel, on_delete=models.CASCADE) + email = models.CharField(unique=True, max_length=80) + + +class RelatedModelSerializer(serializers.ModelSerializer): + username = serializers.CharField(source='user.username', + validators=[UniqueValidator(queryset=UniquenessModel.objects.all())]) # NOQA + + class Meta: + model = RelatedModel + fields = ('username', 'email') + + class AnotherUniquenessModel(models.Model): code = models.IntegerField(unique=True) @@ -73,6 +88,16 @@ def test_doesnt_pollute_model(self): self.assertEqual( AnotherUniquenessModel._meta.get_field('code').validators, []) + def test_related_model_is_unique(self): + data = {'username': 'existing', 'email': '[email protected]'} + rs = RelatedModelSerializer(data=data) + self.assertFalse(rs.is_valid()) + self.assertEqual(rs.errors, + {'username': ['This field must be unique.']}) + data = {'username': 'new-username', 'email': '[email protected]'} + rs = RelatedModelSerializer(data=data) + self.assertTrue(rs.is_valid()) + # Tests for `UniqueTogetherValidator` # -----------------------------------
Validator for serializer field with `source=` kwargs I've drafted a API with DRF, and there're two models, `django.contrib.auth.models.User` and `Customer`, code for `Customer` model: ``` from django.db import models from django.contrib.auth.models import User class Customer(models.Model): SEXES = ( ('Male', 'Male'), ('Female', 'Female'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) sex = models.CharField(max_length=10, choices=SEXES) mobile_number = models.CharField(max_length=20, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __unicode__(self): return u'<%s, %s, %s>' % (self.user.username, self.sex, self.mobile_number) ``` Note that `Customer` has a `user = models.OneToOneField(User, on_delete=models.CASCADE)` field, thus we can still use django's built authentication while add some extra field to our own `Customer` model. The code for `CustomerSerializer`: ``` class CustomerSerializer(serializers.HyperlinkedModelSerializer): created_at = serializers.DateTimeField(read_only=True, format='%Y-%m-%dT%H:%M:%SZ') updated_at = serializers.DateTimeField(read_only=True, format='%Y-%m-%dT%H:%M:%SZ') mobile_number = serializers.CharField(min_length=6, max_length=20, validators=[UniqueValidator(queryset=Customer.objects.all())]) username = serializers.CharField(source='user.username', validators=[UniqueValidator(queryset=User.objects.all())]) email = serializers.CharField(source='user.email') first_name = serializers.CharField(source='user.first_name') last_name = serializers.CharField(source='user.last_name') password = serializers.CharField(source='user.password', min_length=6, max_length=32, write_only=True) ... ``` But when I work with `CustomerSerializer`, it will raise an exception: ``` E FieldError: Cannot resolve keyword u'user' into field. Choices are: auth_token, customer, date_joined, email, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, masseuse, password, user_permissions, username ``` I've checked DRF's code, and I think this exception comes from https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/validators.py#L38 ``` self.field_name = serializer_field.source_attrs[0] ``` I've read DRF's documentation: http://www.django-rest-framework.org/api-guide/fields/, it says ``` source The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email'). ``` And for `EmailField(source='user.email')`, the code `self.field_name = serializer_field.source_attrs[0]` will return `user` instead of `email`, which is not right and will lead to a `FieldError`. For my case, ``` username = serializers.CharField(source='user.username', validators=[UniqueValidator(queryset=User.objects.all())]) ``` I think it's better to change `self.field_name = serializer_field.source_attrs[0]` to `self.field_name = serializer_field.source_attrs[-1]`.
2016-05-26T03:07:05
encode/django-rest-framework
4,156
encode__django-rest-framework-4156
[ "3957" ]
dc09eef24abf496cd2802f5d289e17997fef1161
diff --git a/rest_framework/filters.py b/rest_framework/filters.py --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -222,24 +222,40 @@ def get_default_ordering(self, view): return (ordering,) return ordering + def get_default_valid_fields(self, queryset, view): + # If `ordering_fields` is not specified, then we determine a default + # based on the serializer class, if one exists on the view. + if hasattr(view, 'get_serializer_class'): + try: + serializer_class = view.get_serializer_class() + except AssertionError: + # Raised by the default implementation if + # no serializer_class was found + serializer_class = None + else: + serializer_class = getattr(view, 'serializer_class', None) + + if serializer_class is None: + msg = ( + "Cannot use %s on a view which does not have either a " + "'serializer_class', an overriding 'get_serializer_class' " + "or 'ordering_fields' attribute." + ) + raise ImproperlyConfigured(msg % self.__class__.__name__) + + return [ + (field.source or field_name, field.label) + for field_name, field in serializer_class().fields.items() + if not getattr(field, 'write_only', False) and not field.source == '*' + ] + def get_valid_fields(self, queryset, view): valid_fields = getattr(view, 'ordering_fields', self.ordering_fields) if valid_fields is None: # Default to allowing filtering on serializer fields - try: - serializer_class = view.get_serializer_class() - except AssertionError: # raised if no serializer_class was found - msg = ("Cannot use %s on a view which does not have either a " - "'serializer_class', an overriding 'get_serializer_class' " - "or 'ordering_fields' attribute.") - raise ImproperlyConfigured(msg % self.__class__.__name__) + return self.get_default_valid_fields(queryset, view) - valid_fields = [ - (field.source or field_name, field.label) - for field_name, field in serializer_class().fields.items() - if not getattr(field, 'write_only', False) and not field.source == '*' - ] elif valid_fields == '__all__': # View explicitly allows filtering on any model field valid_fields = [
`OrderingFilter` should call `get_serializer_class()` to determine default fields. ## Checklist - [X] I have verified that that issue exists against the `master` branch of Django REST framework. - [X] I have searched for similar issues in both open and closed tickets and cannot find a duplicate. - [X] This is not a usage question. (Those should be directed to the [discussion group](https://groups.google.com/forum/#!forum/django-rest-framework) instead.) - [X] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](http://www.django-rest-framework.org/topics/third-party-resources/#about-third-party-packages) where possible.) - [X] I have reduced the issue to the simplest possible case. - [ ] I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.) GenericAPIView says > You'll need to either set these attributes, > or override `get_queryset()`/`get_serializer_class()`. But in the method **get_valid_fields** of the **OrderingFilter** class, it gets the serializer_class like so ``` python serializer_class = getattr(view, 'serializer_class') ``` I believe it should be ``` python serializer_class = view.get_serializer_class() ``` Benjamin
Thanks for the well written issue :+1: Oh yeah, this is an actionable ticket! :clap: @bmampaey want to put a a PR together to address this?
2016-06-01T10:00:26
encode/django-rest-framework
4,180
encode__django-rest-framework-4180
[ "3476" ]
04e5b5b20ac93186ee43f04a442d374c7bfcf57a
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -667,6 +667,28 @@ def save(self, **kwargs): return self.instance + def is_valid(self, raise_exception=False): + # This implementation is the same as the default, + # except that we use lists, rather than dicts, as the empty case. + assert hasattr(self, 'initial_data'), ( + 'Cannot call `.is_valid()` as no `data=` keyword argument was ' + 'passed when instantiating the serializer instance.' + ) + + if not hasattr(self, '_validated_data'): + try: + self._validated_data = self.run_validation(self.initial_data) + except ValidationError as exc: + self._validated_data = [] + self._errors = exc.detail + else: + self._errors = [] + + if self._errors and raise_exception: + raise ValidationError(self.errors) + + return not bool(self._errors) + def __repr__(self): return unicode_to_repr(representation.list_repr(self, indent=1))
diff --git a/tests/test_serializer_bulk_update.py b/tests/test_serializer_bulk_update.py --- a/tests/test_serializer_bulk_update.py +++ b/tests/test_serializer_bulk_update.py @@ -46,6 +46,7 @@ def test_bulk_create_success(self): serializer = self.BookSerializer(data=data, many=True) self.assertEqual(serializer.is_valid(), True) self.assertEqual(serializer.validated_data, data) + self.assertEqual(serializer.errors, []) def test_bulk_create_errors(self): """ @@ -76,6 +77,7 @@ def test_bulk_create_errors(self): serializer = self.BookSerializer(data=data, many=True) self.assertEqual(serializer.is_valid(), False) self.assertEqual(serializer.errors, expected_errors) + self.assertEqual(serializer.validated_data, []) def test_invalid_list_datatype(self): """
Serializers with many=True should return empty list rather than empty dict Follow up proposal fix for #3434 and #3437
@tomchristie this is ready for a review I think I need to dig a bit why we get a dictionary in the first place. Feels like the root cause isn't fixed with this PR.
2016-06-08T14:49:31
encode/django-rest-framework
4,181
encode__django-rest-framework-4181
[ "3164" ]
a5f822d0671ce2412df666afa2b920039b302a0e
diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -472,31 +472,37 @@ def get_rendered_html_form(self, data, view, method, request): return if existing_serializer is not None: - serializer = existing_serializer + try: + return self.render_form_for_serializer(existing_serializer) + except TypeError: + pass + + if has_serializer: + if method in ('PUT', 'PATCH'): + serializer = view.get_serializer(instance=instance, **kwargs) + else: + serializer = view.get_serializer(**kwargs) else: - if has_serializer: - if method in ('PUT', 'PATCH'): - serializer = view.get_serializer(instance=instance, **kwargs) - else: - serializer = view.get_serializer(**kwargs) + # at this point we must have a serializer_class + if method in ('PUT', 'PATCH'): + serializer = self._get_serializer(view.serializer_class, view, + request, instance=instance, **kwargs) else: - # at this point we must have a serializer_class - if method in ('PUT', 'PATCH'): - serializer = self._get_serializer(view.serializer_class, view, - request, instance=instance, **kwargs) - else: - serializer = self._get_serializer(view.serializer_class, view, - request, **kwargs) - - if hasattr(serializer, 'initial_data'): - serializer.is_valid() - - form_renderer = self.form_renderer_class() - return form_renderer.render( - serializer.data, - self.accepted_media_type, - {'style': {'template_pack': 'rest_framework/horizontal'}} - ) + serializer = self._get_serializer(view.serializer_class, view, + request, **kwargs) + + return self.render_form_for_serializer(serializer) + + def render_form_for_serializer(self, serializer): + if hasattr(serializer, 'initial_data'): + serializer.is_valid() + + form_renderer = self.form_renderer_class() + return form_renderer.render( + serializer.data, + self.accepted_media_type, + {'style': {'template_pack': 'rest_framework/horizontal'}} + ) def get_raw_data_form(self, data, view, method, request): """
diff --git a/tests/browsable_api/test_form_rendering.py b/tests/browsable_api/test_form_rendering.py new file mode 100644 --- /dev/null +++ b/tests/browsable_api/test_form_rendering.py @@ -0,0 +1,53 @@ +from django.test import TestCase + +from rest_framework import generics, renderers, serializers, status +from rest_framework.response import Response +from rest_framework.test import APIRequestFactory +from tests.models import BasicModel + +factory = APIRequestFactory() + + +class BasicSerializer(serializers.ModelSerializer): + class Meta: + model = BasicModel + + +class ManyPostView(generics.GenericAPIView): + queryset = BasicModel.objects.all() + serializer_class = BasicSerializer + renderer_classes = (renderers.BrowsableAPIRenderer, renderers.JSONRenderer) + + def post(self, request, *args, **kwargs): + serializer = self.get_serializer(self.get_queryset(), many=True) + return Response(serializer.data, status.HTTP_200_OK) + + +class TestManyPostView(TestCase): + def setUp(self): + """ + Create 3 BasicModel instances. + """ + items = ['foo', 'bar', 'baz'] + for item in items: + BasicModel(text=item).save() + self.objects = BasicModel.objects + self.data = [ + {'id': obj.id, 'text': obj.text} + for obj in self.objects.all() + ] + self.view = ManyPostView.as_view() + + def test_post_many_post_view(self): + """ + POST request to a view that returns a list of objects should + still successfully return the browsable API with a rendered form. + + Regression test for https://github.com/tomchristie/django-rest-framework/pull/3164 + """ + data = {} + request = factory.post('/', data, format='json') + with self.assertNumQueries(1): + response = self.view(request).render() + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(len(response.data), 3)
Retry form rendering when rendering with serializer fails. As per IRC, here's the new pull request. First commit is a small test that tickles the issue. Second commit adds a retry mechanism to use a generated serializer if the one attached to data does not work. The issue here is most easily seen in a POST request that returns multiple objects, in which case the BrowsableAPIRenderer raises a TypeError on the serializer (a ListSerializer) not being iterable. This exception prevents an otherwise fine response to fail on account of a failure to render a form. x-ref: #3138, #2918.
It'd be worth bring a brief description into the summary here. Also cross references should be in the description or thread only, not in the title. I updated the loop to an inline function. I believe this is a good compromise between code duplication and understanding behavior. Ignoring whitespace, renderers.py only gains seven lines, which is pretty minimal. Are there any plans to merge this? It's just the thing I need to get the BrowsableAPI to work when posting multiple objects. Thanks for the note - yes it's in the backlog, and we'd merge an acceptable pull request here. Review: The pull request as it currently stands deals with two separate concerns. There's a refactoring, and there's also the re-try. It'd be easier to comprehensively review if these were treated as separate pull requests. Best thing to move this along would be for someone to take on the task of splitting this into two separately reviewable units, so that we can keep each step as absolutely minimal and thoroughly reviewed as possible. Would splitting it into two separate commits in this pull request suffice? The two changes don't really make sense separately. Any word on this? No change on my original comment. I'd want to see: 1. A refactoring PR that does not change the behavior, but is valid as it stands. 2. A behavioral PR on top of that. Right now I don't have a lot of overhead for issue backlog - dealing with remains of 3.3/kickstarter functionality in last few days of funded time. Hopefully be able to get cracking with it again if we have a subsequent funding drive. I do not understand why you want to see this as two PRs rather than two commits in one PR. The refactor is meaningless without the behavior change. What does anybody gain from multiple Pull Requests for one issue? Specifically, this is one logical change: 1) A commit which breaks the tests, providing an example of what is broken and a way to test that it is fixed. 2) A commit that splits off the behavior we want to modify to fix the broken test, but does not change functionality. 3) A commit to change the functionality in a way that fixes the test. I can't make a PR for (1) by itself because that will break the tests by design. Making a PR for (2) is asking you to review and merge a commit that appears to have no point, then starting over. Making a PR for (3) requires that (2) have already been merged. This is one change. You can take it or leave it. I am done jumping through hoops trying to make your software better for now. I'm still waiting for resolution on this, and I'm not alone. I've added a test that demonstrates the bug, I've made a non-functional change that helps with the fix (at your request), and I've fixed the bug. It's about as simple as a unit of work can get. @asedeno Noted. We've got 114 open issues, and since the end of the kickstarter currently have no funded work on the project, so there's a backlog right now. I understand there is a backlog. That would be more compelling if I were asking you to fix a bug, not handing you a fix for it myself. I put the work in for you, free of charge, and I will make any functional changes you might want to this PR, but I believe it is ready and has been for months. Milestoning to move it up the queue. Thank you! So does a milestone mean anything for this PR, or is it only a can to keep kicking down the road? Checks pass, there are no conflicts, this has been essentially ready for months. This is very far from being a simple, obviously correct or easily reviewable change. It's not immediately apparent to me what _exactly_ the behavior is before or after, and I've not any spare time to review in depth. Having `try...except TypeError` reads completely opaquely, so even as the author I wouldn't understand what's happening there or why. If this was a simpler and more obvious fix, then yes it'd be in - as it stands, it's not terribly clear and hence, given the review bottleneck we've got at the moment it's stalled. Perhaps there's a simpler more obvious fix for this - again, not sure without some proper thinking about it. Is the milestone meaningful? yes - it means this isn't absolutely at the bottom of the queue, and if and when we get paid time back it's likely to get resolved. The try...except TypeError is there to catch `TypeError: 'ListSerializer' object is not iterable` If I could catch a more specific exception, I would. I can add more comments to the code if you like. This is nothing more than: 1. try it with the serializer we have, like we do right now. 2. If we had a serializer and it fails with a TypeError, try again without the serializer like we would if we didn't have one. In all the cases where DRF currently works, no TypeError is raised, so the try...except doesn't do anything. In the case where a TypeError is raised, DRF currently crashes and burns. This tries something else before crashing and burning, and the test I added shows that it does enough to make it succeed. Again, this exception is raised after DRF has a **perfectly valid response** to the user's request, while rendering the **user-friendly** browsable api and trying to pre-fill a form. Returning a response and a form that is not filled in is much **friendlier** than returning a **TypeError** when we have a perfectly good response to the user's request. Noted. One comment for consideration. If the form rendering horribleness that we currently have can at least be nicely encapsulated then this could be a go-er. Pulling the inner function out causes a lot more code churn, adds a lot of function parameters to replicate the enclosing scope, and I think actually makes this harder to reason about. This encapsulates just the piece of `get_rendered_html_form` we want to retry so we can call it without a serializer. This is one of the reasons python has scoping rules that allow for nested scoping. (Thank you, PEP 227.) I don't have any huge problem with an inner scoped function. I still have a problem with relying on outset scoped variables inside the inner scoped function, tho. (i.e. `has_serializer`, others?) The whole point of statically nested scoping ([PEP 227](http://legacy.python.org/dev/peps/pep-0227/)) is to have access to the enclosing scope. I'll refer you to [viewsets.py](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/viewsets.py#L69) where an inner `view` function makes use of `actions` from the enclosing scope. Also, just about every decorator ever. > whole point > It keeps the function out of the global scope, which if it's not useful elsewhere is a nice bit of encapsulation. > > I'll refer you to > Is a different case - we need to take that approach there because we're returning a function closure. Those are side issues tho - In either case I still not convinced it's the right approach to keep it nested here as we're only increasing the complexity, without mitigating that by encapsulating any of it away. (Since we're in the same scope) Wrap it up more strictly and at least we're keeping the horribleness contained somewhat. I think you are wrong. That said, I'm looking at a different approach that will maybe make you happier: Collect a list of serializers to try with. If there is an existing serializer, that one will be first on the list. Next on the list is the serializer we would set up if there was not an existing serializer. Then, loop over them in a try block and return the form using the first one that succeeds. The only question is, if they all fail, and there were multiple attempts, which exception would to like to see raised? I've gone with the last one because that is the one I can raise with the right stack trace. Is this implementation more to your liking? There's no inner function, and the loop is much more manageable. Waking up this PR once again as I am still waiting for feedback or for it to be merged.
2016-06-08T16:03:27
encode/django-rest-framework
4,191
encode__django-rest-framework-4191
[ "4185" ]
bb22ab8ee7c5d484dde7112dbe5551bcfc89d7d3
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 @@ -51,6 +51,9 @@ def default(self, obj): return six.text_type(obj) elif isinstance(obj, QuerySet): return tuple(obj) + elif isinstance(obj, six.binary_type): + # Best-effort for binary blobs. See #4187. + return obj.decode('utf-8') elif hasattr(obj, 'tolist'): # Numpy arrays and array scalars. return obj.tolist()
JSONField(binary=True) represents using binary strings, which JSONRenderer does not support. ## 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 from rest_framework import serializers class TestSerializer(serializers.Serializer): json = serializers.JSONField() s = TestSerializer(data={'json': "{broken JSON"}) assert s.is_valid() is False ``` ## Expected behavior Invalid JSON should result in `is_valid()` returning `False`. ## Actual behavior `is_valid()` returns `True` Specifying `binary=True` for the field definition results in the desired behavior for serialization, but causes deserialization to fail on Python 3.
Unless you set `binary=True` the field will check for valid primitives, not a valid binary encoded bytestring. As currently described, you're passing a valid primitive - a string literal. What you actually want, as you've noted, is this... ``` class TestSerializer(serializers.Serializer): json = serializers.JSONField(binary=True) ``` Which then works as expected - `is_valid()` returns `False`. I've tested this in python 3 and I can't see what you mean wrt "causes deserialization to fail" - can reconsider if that aspect gets more details. The tricky point with binary=True is that it isn't a json renderable data because it's a binary string and the json renderer expect unicodes. I'd point out that the documentation for that field would benefit some clarification: > A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings. As it stands, I understand that it expects a valid JSON input for non binary mode. > It isn't a json renderable data because it's a binary string and the json renderer expect unicodes. Right - then that's the core issue that we should resolve here. Either that or we should output to unicode by default. (Not strictly correct, but it'd do the trick) Sorry, I misspoke. It doesn't break the deserialization, it breaks the `JSONRenderer`, which I see is a separate issue. So until #4187 is resolved, what is the best way to enforce valid JSON inputs for an API? Well, using a binary json blob as a field isn't a particularly common use case, so poss you should just reconsider if that's what you _actually_ want (ie a nested document of json primitives may be better) but if it really is what you need I'd suggest subclassing JSONField and forcing to_representation to do .decode('utf8') on the result so that you have a custom JSONField that returns Unicode, not bytestrings.
2016-06-13T09:31:15
encode/django-rest-framework
4,192
encode__django-rest-framework-4192
[ "2848", "3970" ]
9bffd354327ffc99a0c50ad140a86ede94f9dfba
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -1243,6 +1243,11 @@ def get_extra_kwargs(self): read_only_fields = getattr(self.Meta, 'read_only_fields', None) if read_only_fields is not None: + if not isinstance(read_only_fields, (list, tuple)): + raise TypeError( + 'The `read_only_fields` option must be a list or tuple. ' + 'Got %s.' % type(read_only_fields).__name__ + ) for field_name in read_only_fields: kwargs = extra_kwargs.get(field_name, {}) kwargs['read_only'] = True @@ -1258,6 +1263,9 @@ def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs ('dict of updated extra kwargs', 'mapping of hidden fields') """ + if getattr(self.Meta, 'validators', None) is not None: + return (extra_kwargs, {}) + model = getattr(self.Meta, 'model') model_fields = self._get_model_fields( field_names, declared_fields, extra_kwargs @@ -1308,7 +1316,7 @@ def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs else: uniqueness_extra_kwargs[unique_constraint_name] = {'default': default} elif default is not empty: - # The corresponding field is not present in the, + # The corresponding field is not present in the # serializer. We have a default to use for it, so # add in a hidden field that populates it. hidden_fields[unique_constraint_name] = HiddenField(default=default) @@ -1390,6 +1398,7 @@ def get_unique_together_validators(self): field_names = { field.source for field in self.fields.values() 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
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 @@ -521,8 +521,6 @@ class Meta: one_to_one = NestedSerializer(read_only=True): url = HyperlinkedIdentityField(view_name='onetoonetargetmodel-detail') name = CharField(max_length=100) - class Meta: - validators = [<UniqueTogetherValidator(queryset=UniqueTogetherModel.objects.all(), fields=('foreign_key', 'one_to_one'))>] """) if six.PY2: # This case is also too awkward to resolve fully across both py2 diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -239,6 +239,45 @@ class Meta: """) assert repr(serializer) == expected + def test_ignore_read_only_fields(self): + """ + When serializer fields are read only, then uniqueness + validators should not be added for that field. + """ + class ReadOnlyFieldSerializer(serializers.ModelSerializer): + class Meta: + model = UniquenessTogetherModel + fields = ('id', 'race_name', 'position') + read_only_fields = ('race_name',) + + serializer = ReadOnlyFieldSerializer() + expected = dedent(""" + ReadOnlyFieldSerializer(): + id = IntegerField(label='ID', read_only=True) + race_name = CharField(read_only=True) + position = IntegerField(required=True) + """) + assert repr(serializer) == expected + + def test_allow_explict_override(self): + """ + Ensure validators can be explicitly removed.. + """ + class NoValidatorsSerializer(serializers.ModelSerializer): + class Meta: + model = UniquenessTogetherModel + fields = ('id', 'race_name', 'position') + validators = [] + + serializer = NoValidatorsSerializer() + expected = dedent(""" + NoValidatorsSerializer(): + id = IntegerField(label='ID', read_only=True) + race_name = CharField(max_length=100) + position = IntegerField() + """) + assert repr(serializer) == expected + def test_ignore_validation_for_null_fields(self): # None values that are on fields which are part of the uniqueness # constraint cause the instance to ignore uniqueness validation.
Uniqueness validators should not be run for excluded (read_only) fields get_uniqueness_extra_kwargs and get_unique_together_validators both rely on Django's model unique_together specification. However, if read_only is set for both they should not be expected to be validated as normal. This reflects the behavior of django forms (exclude the field in form and it doesn't validated against this). This allows unique_together fields to be autogenerated in the save method of the model. ListSerializer doesn't handle unique_together constraints ## 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.) As referenced in https://github.com/tomchristie/django-rest-framework/pull/2575 https://github.com/miki725/django-rest-framework-bulk/issues/30 ListSerializer attempts to apply unique together validation on the queryset passed to it, but some part of the code is passed the full queryset, where it attempts to look up attributes on what it expects to be individual instances. ## Steps to reproduce I've modified a test case found in the above links, and run them against master. I'm not sure what the file should be named, and if it follows your quality standards, so I have not submitted a PR with it. ``` python from django.db import models from django.test import TestCase from rest_framework import serializers class ManyUniqueTogetherModel(models.Model): foo = models.IntegerField() bar = models.IntegerField() class Meta: unique_together = ("foo", "bar") class ManyUniqueTogetherSerializer(serializers.ModelSerializer): class Meta: model = ManyUniqueTogetherModel class ManyUniqueTogetherTestCase(TestCase): def test_partial_false(self): obj = ManyUniqueTogetherModel.objects.create(foo=1, bar=2) serializer = ManyUniqueTogetherSerializer( instance=ManyUniqueTogetherModel.objects.all(), data=[{ "id": obj.pk, "foo": 5, "bar": 6, }], many=True ) self.assertTrue(serializer.is_valid()) def test_partial_true(self): obj = ManyUniqueTogetherModel.objects.create(foo=1, bar=2) serializer = ManyUniqueTogetherSerializer( instance=ManyUniqueTogetherModel.objects.all(), data=[{ "id": obj.pk, "foo": 5, }], partial=True, many=True ) self.assertTrue(serializer.is_valid()) ``` ## Expected behavior The code path looks up properties on individual instances in the queryset, is_valid() returns either True or False depending on the actual data, the tests pass. ## Actual behavior ``` ====================================================================== FAILURES ====================================================================== ___________________________________________________ ManyUniqueTogetherTestCase.test_partial_false ____________________________________________________ tests/test_unique_together.py:35: in test_partial_false self.assertTrue(serializer.is_valid()) rest_framework/serializers.py:213: in is_valid self._validated_data = self.run_validation(self.initial_data) rest_framework/serializers.py:557: in run_validation value = self.to_internal_value(data) rest_framework/serializers.py:593: in to_internal_value validated = self.child.run_validation(item) rest_framework/serializers.py:409: in run_validation self.run_validators(value) rest_framework/fields.py:499: in run_validators validator(value) rest_framework/validators.py:142: in __call__ queryset = self.exclude_current_instance(attrs, queryset) rest_framework/validators.py:135: in exclude_current_instance return queryset.exclude(pk=self.instance.pk) E AttributeError: 'QuerySet' object has no attribute 'pk' ____________________________________________________ ManyUniqueTogetherTestCase.test_partial_true ____________________________________________________ tests/test_unique_together.py:50: in test_partial_true self.assertTrue(serializer.is_valid()) rest_framework/serializers.py:213: in is_valid self._validated_data = self.run_validation(self.initial_data) rest_framework/serializers.py:557: in run_validation value = self.to_internal_value(data) rest_framework/serializers.py:593: in to_internal_value validated = self.child.run_validation(item) rest_framework/serializers.py:409: in run_validation self.run_validators(value) rest_framework/fields.py:499: in run_validators validator(value) rest_framework/validators.py:141: in __call__ queryset = self.filter_queryset(attrs, queryset) rest_framework/validators.py:120: in filter_queryset attrs[field_name] = getattr(self.instance, field_name) E AttributeError: 'QuerySet' object has no attribute 'bar' ```
Presumably if _either_ is read_only, then we shouldn't validate them? (Ie. same as excluding one?) This is how django does it: https://github.com/django/django/blob/master/django/forms/models.py#L344 (build exclusion list) Then here: https://github.com/django/django/blob/a10b4c010ab2cdaa6ba8bfaec3e3540299ea77be/django/db/models/base.py#L926 for name in check: # If this is an excluded field, don't add this check. if name in exclude: break So It looks like you are correct, a uniquetogether check is not done if ANY of the fields are missing I can write a PR for this as long as the design is accepted. I just hate writing stuff that won't get approved. I'm broadly in favor of this, but I don't think we can make any definite decisions without seeing an example fix and test case. Labeling this as a valid bug to address tho. Uniqueness validators should also not be run if required=False. I have a serializer (Room) with required=False set on a nested user serializer, but it fails with a "This field is required" because user is part of a unique_together requirement on the Room model. Is there a workaround for now to exclude this validation on the serializer? For now, I've removed the unique_together requirement, but that's obviously less than ideal. This use case is more complex. You want to run the uniqueness constraint when both have a value though not if only one is provided. +1. Both for read_only=True or required=False When both have a value: you want uniqueness. When only one or none have a value: no constraints. Behaviour today is that they are both blocked as required when uniqueness is defined, even when the fields are read_only=True or required=False. (I presume the same should happen if only 1 of the fields is required and the other not?) `required=False` will be "overridden" by the `UniqueTogetherValidator`. I start feeling there are too many possible use cases. What if one field is not required, what if one is read only, what if we have both constraints and what if.... I'm not even sure what I should think about a `UniqueTogetherValidator` with one field having a read only constraint on top of it. Let's rather use a custom `UniqueTogetherValidator` or use business logic level validation and make the documentation more clear about what the `UniqueTogetherValidator` does. @tomchristie thoughts on that one ? It comes down to decide which constraint takes precedence? If both are not required but have uniqueness, they might both be blank (thus technically violating the uniqueness if this happens more than once) http://stackoverflow.com/questions/5772176/django-unique-together-and-blank-true Checking on the behaviour of Django, it seems like the uniqueness takes precedence, as it is enforced on DB level. What I would at least suggest is to handle the exception more gracefully. Now if you have a field that you put required=False but with uniqueness, you get the message "this field is required". > It comes down to decide which constraint takes precedence? It comes down to how to handle the most common use cases and easily allow developers to deal with edge cases. To me, it's very similar to the work done on writable nested serializers. Raising warnings if conflicting constraints are found could be a nice way to make the developers aware that they might be hitting a wall. I strongly recommend following Django's behavior. Partially for dev sanity, but mainly so unique_together fields can be autogenerated in the save method of the model. If they are both read_only, then there is no point in validating because there is nothing to be sent from the wire. However, having validating fail, makes it so you cannot autogenerate values, which is very problematic. > unique_together fields can be autogenerated in the save method of the model. There's no way DRF can be aware of auto generated data at save time. This basically means the API will raise 500 errors because the unique_together constraint may be broken if the dev forgot to set the data. This falls back to my previous comment. > There's no way DRF can be aware of auto generated data at save time. Exactly. That's why DRF can't be imposing itself when you declare that you will be managing those fields yourself. If you disagree, give me one scenario where read_only is set on a field, but DRF itself will save that field based on user input. @ntucker any create operation on a model that has a unique_together constraint with a read_only field on one of them. Note that I've been performing something similar but handled it outside of generic DRF. Reason is, even if `UniqueTogetherConstraint` would work with QuerySet it would still fail in some cases such as: ``` data=[{ "id": id1, "foo": 5, "bar": 6, }, { "id": id2, "foo": 5, "bar": 6, },], ``` I suspect there are some other specific use cases that would prove hard to solve with validators in their current forms. Could it be related to the issue I'm having ? I got ``` author = models.ForeignKey(User) created_at = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = "created_at" ordering = ['-created_at'] unique_together = [ ["author", "created_at"] ] ``` in my Model. User is a cms.models.User object. For some reason, Swagger is throwing an error when trying to list available API endpoints `'CreateOnlyDefault' object has no attribute 'is_update'` ``` Traceback: File "/Users/louis/Documents/WebProjects/Python/SiteTestlib/python2.7/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/louis/Documents/WebProjects/Python/SiteTestlib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/Users/louis/Documents/WebProjects/Python/SiteTestlib/python2.7/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/Users/louis/Documents/WebProjects/Python/SiteTestlib/python2.7/site-packages/rest_framework/views.py" in dispatch 466. response = self.handle_exception(exc) File "/Users/louis/Documents/WebProjects/Python/SiteTestlib/python2.7/site-packages/rest_framework/views.py" in dispatch 463. response = handler(request, *args, **kwargs) File "/Users/louis/Documents/WebProjects/Python/SiteTestlib/python2.7/site-packages/rest_framework_swagger/views.py" in get 164. 'models': generator.get_models(apis), File "/Users/louis/Documents/WebProjects/Python/SiteTestlib/python2.7/site-packages/rest_framework_swagger/docgenerator.py" in get_models 139. data = self._get_serializer_fields(serializer) File "/Users/louis/Documents/WebProjects/Python/SiteTestlib/python2.7/site-packages/rest_framework_swagger/docgenerator.py" in _get_serializer_fields 328. 'defaultValue': get_default_value(field), File "/Users/louis/Documents/WebProjects/Python/SiteTestlib/python2.7/site-packages/rest_framework_swagger/introspectors.py" in get_default_value 54. default_value = default_value() File "/Users/louis/Documents/WebProjects/Python/SiteTestlib/python2.7/site-packages/rest_framework/fields.py" in __call__ 225. if self.is_update: ``` I know Django REST Swagger is not part of that project, but the call is made from Django REST Framework if I understand the stack trace correctly. Related: #2996.
2016-06-13T11:00:48
encode/django-rest-framework
4,196
encode__django-rest-framework-4196
[ "4019" ]
1633a0a2b1ae21bfa5d971c583039577a1e7abef
diff --git a/rest_framework/fields.py b/rest_framework/fields.py --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1073,7 +1073,7 @@ def to_representation(self, value): output_format = getattr(self, 'format', api_settings.DATETIME_FORMAT) - if output_format is None: + if output_format is None or isinstance(value, six.string_types): return value if output_format.lower() == ISO_8601: @@ -1133,7 +1133,7 @@ def to_representation(self, value): output_format = getattr(self, 'format', api_settings.DATE_FORMAT) - if output_format is None: + if output_format is None or isinstance(value, six.string_types): return value # Applying a `DateField` to a datetime value is almost always @@ -1146,8 +1146,6 @@ def to_representation(self, value): ) if output_format.lower() == ISO_8601: - if isinstance(value, six.string_types): - value = datetime.datetime.strptime(value, '%Y-%m-%d').date() return value.isoformat() return value.strftime(output_format)
diff --git a/tests/test_fields.py b/tests/test_fields.py --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -993,6 +993,8 @@ class TestDateTimeField(FieldValues): outputs = { datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00', datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.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', None: None, '': None, }
DateTimeField to_representation can handle strings. Fixes #4013. Fixes issue with DateTimeField described in #4013.
2016-06-14T11:18:00
encode/django-rest-framework
4,217
encode__django-rest-framework-4217
[ "3493" ]
a20a75636c12b7c2ac60e157c3f8fb02bd7bca42
diff --git a/rest_framework/validators.py b/rest_framework/validators.py --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -8,6 +8,7 @@ """ from __future__ import unicode_literals +from django.db import DataError from django.utils.translation import ugettext_lazy as _ from rest_framework.compat import unicode_to_repr @@ -15,6 +16,24 @@ from rest_framework.utils.representation import smart_repr +# Robust filter and exist implementations. Ensures that queryset.exists() for +# an invalid value returns `False`, rather than raising an error. +# Refs https://github.com/tomchristie/django-rest-framework/issues/3381 + +def qs_exists(queryset): + try: + return queryset.exists() + except (TypeError, ValueError, DataError): + return False + + +def qs_filter(queryset, **kwargs): + try: + return queryset.filter(**kwargs) + except (TypeError, ValueError, DataError): + return queryset.none() + + class UniqueValidator(object): """ Validator that corresponds to `unique=True` on a model field. @@ -44,7 +63,7 @@ def filter_queryset(self, value, queryset): Filter the queryset to all instances matching the given attribute. """ filter_kwargs = {self.field_name: value} - return queryset.filter(**filter_kwargs) + return qs_filter(queryset, **filter_kwargs) def exclude_current_instance(self, queryset): """ @@ -59,7 +78,7 @@ def __call__(self, value): queryset = self.queryset queryset = self.filter_queryset(value, queryset) queryset = self.exclude_current_instance(queryset) - if queryset.exists(): + if qs_exists(queryset): raise ValidationError(self.message) def __repr__(self): @@ -124,7 +143,7 @@ def filter_queryset(self, attrs, queryset): field_name: attrs[field_name] for field_name in self.fields } - return queryset.filter(**filter_kwargs) + return qs_filter(queryset, **filter_kwargs) def exclude_current_instance(self, attrs, queryset): """ @@ -145,7 +164,7 @@ def __call__(self, attrs): checked_values = [ value for field, value in attrs.items() if field in self.fields ] - if None not in checked_values and queryset.exists(): + if None not in checked_values and qs_exists(queryset): field_names = ', '.join(self.fields) raise ValidationError(self.message.format(field_names=field_names)) @@ -209,7 +228,7 @@ def __call__(self, attrs): queryset = self.queryset queryset = self.filter_queryset(attrs, queryset) queryset = self.exclude_current_instance(attrs, queryset) - if queryset.exists(): + if qs_exists(queryset): message = self.message.format(date_field=self.date_field) raise ValidationError({self.field: message}) @@ -234,7 +253,7 @@ def filter_queryset(self, attrs, queryset): filter_kwargs['%s__day' % self.date_field_name] = date.day filter_kwargs['%s__month' % self.date_field_name] = date.month filter_kwargs['%s__year' % self.date_field_name] = date.year - return queryset.filter(**filter_kwargs) + return qs_filter(queryset, **filter_kwargs) class UniqueForMonthValidator(BaseUniqueForValidator): @@ -247,7 +266,7 @@ def filter_queryset(self, attrs, queryset): filter_kwargs = {} filter_kwargs[self.field_name] = value filter_kwargs['%s__month' % self.date_field_name] = date.month - return queryset.filter(**filter_kwargs) + return qs_filter(queryset, **filter_kwargs) class UniqueForYearValidator(BaseUniqueForValidator): @@ -260,4 +279,4 @@ def filter_queryset(self, attrs, queryset): filter_kwargs = {} filter_kwargs[self.field_name] = value filter_kwargs['%s__year' % self.date_field_name] = date.year - return queryset.filter(**filter_kwargs) + return qs_filter(queryset, **filter_kwargs)
diff --git a/tests/test_validators.py b/tests/test_validators.py --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -48,6 +48,18 @@ class Meta: fields = '__all__' +class IntegerFieldModel(models.Model): + integer = models.IntegerField() + + +class UniquenessIntegerSerializer(serializers.Serializer): + # Note that this field *deliberately* does not correspond with the model field. + # This allows us to ensure that `ValueError`, `TypeError` or `DataError` etc + # raised by a uniqueness check does not trigger a deceptive "this field is not unique" + # validation failure. + integer = serializers.CharField(validators=[UniqueValidator(queryset=IntegerFieldModel.objects.all())]) + + class TestUniquenessValidation(TestCase): def setUp(self): self.instance = UniquenessModel.objects.create(username='existing') @@ -100,6 +112,10 @@ def test_related_model_is_unique(self): rs = RelatedModelSerializer(data=data) self.assertTrue(rs.is_valid()) + def test_value_error_treated_as_not_unique(self): + serializer = UniquenessIntegerSerializer(data={'integer': 'abc'}) + assert serializer.is_valid() + # Tests for `UniqueTogetherValidator` # -----------------------------------
fix PostgreSQL fields DataError in unique validator For https://github.com/tomchristie/django-rest-framework/issues/3381 We get DataError only in internal PostgreSQL fields validation, so test will not raise DataError exception in other databases and will be success anyway. Maybe i should remove it?
2016-06-23T13:42:26
encode/django-rest-framework
4,219
encode__django-rest-framework-4219
[ "4010" ]
ea92d505826aa19c3681884ac5022dcdadf0c20e
diff --git a/rest_framework/versioning.py b/rest_framework/versioning.py --- a/rest_framework/versioning.py +++ b/rest_framework/versioning.py @@ -112,16 +112,19 @@ class NamespaceVersioning(BaseVersioning): Host: example.com Accept: application/json """ - invalid_version_message = _('Invalid version in URL path.') + invalid_version_message = _('Invalid version in URL path. Does not match any version namespace.') def determine_version(self, request, *args, **kwargs): resolver_match = getattr(request, 'resolver_match', None) if (resolver_match is None or not resolver_match.namespace): return self.default_version - version = resolver_match.namespace - if not self.is_allowed_version(version): - raise exceptions.NotFound(self.invalid_version_message) - return version + + # Allow for possibly nested namespaces. + possible_versions = resolver_match.namespace.split(':') + for version in possible_versions: + if self.is_allowed_version(version): + return version + raise exceptions.NotFound(self.invalid_version_message) def reverse(self, viewname, args=None, kwargs=None, request=None, format=None, **extra): if request.version is not None:
diff --git a/tests/test_versioning.py b/tests/test_versioning.py --- a/tests/test_versioning.py +++ b/tests/test_versioning.py @@ -85,6 +85,7 @@ def test_query_param_versioning(self): response = view(request) assert response.data == {'version': None} + @override_settings(ALLOWED_HOSTS=['*']) def test_host_name_versioning(self): scheme = versioning.HostNameVersioning view = RequestVersionView.as_view(versioning_class=scheme) @@ -173,6 +174,7 @@ def test_reverse_query_param_versioning(self): response = view(request) assert response.data == {'url': 'http://testserver/another/'} + @override_settings(ALLOWED_HOSTS=['*']) def test_reverse_host_name_versioning(self): scheme = versioning.HostNameVersioning view = ReverseView.as_view(versioning_class=scheme) @@ -223,6 +225,7 @@ def test_invalid_query_param_versioning(self): response = view(request) assert response.status_code == status.HTTP_404_NOT_FOUND + @override_settings(ALLOWED_HOSTS=['*']) def test_invalid_host_name_versioning(self): scheme = versioning.HostNameVersioning view = RequestInvalidVersionView.as_view(versioning_class=scheme) @@ -293,8 +296,12 @@ def test_bug_2489(self): class TestNamespaceVersioningHyperlinkedRelatedFieldScheme(URLPatternsTestCase): + nested = [ + url(r'^namespaced/(?P<pk>\d+)/$', dummy_pk_view, name='nested'), + ] included = [ url(r'^namespaced/(?P<pk>\d+)/$', dummy_pk_view, name='namespaced'), + url(r'^nested/', include(nested, namespace='nested-namespace')) ] urlpatterns = [ @@ -322,6 +329,10 @@ def test_api_url_is_properly_reversed_with_v2(self): field = self._create_field('namespaced', 'v2') assert field.to_representation(PKOnlyObject(5)) == 'http://testserver/v2/namespaced/5/' + def test_api_url_is_properly_reversed_with_nested(self): + field = self._create_field('nested', 'v1:nested-namespace') + assert field.to_representation(PKOnlyObject(3)) == 'http://testserver/v1/nested/namespaced/3/' + def test_non_api_url_is_properly_reversed_regardless_of_the_version(self): """ Regression test for #2711
Nested NamespaceVersioning ## Description This both fixes the misleading error message for `NamespaceVersioning` and adds proper (at least according to me) nested namespaces handling. https://github.com/tomchristie/django-rest-framework/issues/4009
:+1: This breaks my URLs scheme that have another namespace before the versions one, as seem: ``` python # urls.py (root) urlpatterns = [ url(r'^api/', include('api.urls', namespace='api')), ] ``` ``` python # api/urls.py (app) api_v1_patterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] urlpatterns = [ url(r'^v1/', include(api_v1_patterns, namespace='v1')), ] ``` Actual master works. With this PR applied it breaks. ...maybe in conjunction with #3816 it works, but I had not tested. @alanjds it wouldn't work with master if you had any extra namespace _after_ the version, which imho is they way they should be used I guess I'll have to come up with some idea to handle both before and after cases.
2016-06-23T14:50:26
encode/django-rest-framework
4,254
encode__django-rest-framework-4254
[ "4253" ]
c21994e778401e9a82cd1bc0d3aeca5a46b8f432
diff --git a/rest_framework/response.py b/rest_framework/response.py --- a/rest_framework/response.py +++ b/rest_framework/response.py @@ -51,14 +51,13 @@ def __init__(self, data=None, status=None, @property def rendered_content(self): renderer = getattr(self, 'accepted_renderer', None) - media_type = getattr(self, 'accepted_media_type', None) context = getattr(self, 'renderer_context', None) assert renderer, ".accepted_renderer not set on Response" - assert media_type, ".accepted_media_type not set on Response" assert context, ".renderer_context not set on Response" context['response'] = self + media_type = renderer.media_type charset = renderer.charset content_type = self.content_type
Response Content-Type potentially malformed ## 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.) ## Problem description The default request header 'Accept' on many browsers is something like `Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`. This means that currently, if the response is not `text/html`, then the response `Content-Type` incorrectly contains the `q=` parameter. (According to [this](http://stackoverflow.com/a/10496722/3108853), the `q` parameter specifies which content-types the browser prefers). It looks like it is occurring because: 1. [DefaultContentNegotiation.select_renderer](https://github.com/tomchristie/django-rest-framework/blob/10a080d395b8f1fc5cef0778cd2a40c3d81dfe19/rest_framework/negotiation.py#L67-L72) returns the `full_media_type` (which includes the extra `Accept` "parameters" like `q`) 2. [ApiView.perform_content_negotiation](https://github.com/tomchristie/django-rest-framework/blob/10a080d395b8f1fc5cef0778cd2a40c3d81dfe19/rest_framework/views.py#L296) returns the `renderer, full_media_type` tuple 3. [ApiView.initial](https://github.com/tomchristie/django-rest-framework/blob/10a080d395b8f1fc5cef0778cd2a40c3d81dfe19/rest_framework/views.py#L376-L377) sets `request.accepted_media_type` equal to that `full_media_type` 4. [ApiView.finalize_response](https://github.com/tomchristie/django-rest-framework/blob/10a080d395b8f1fc5cef0778cd2a40c3d81dfe19/rest_framework/views.py#L405) sets `response.accepted_media_type` equal to `request.accepted_media_type` 5. [Response.rendered_content](https://github.com/tomchristie/django-rest-framework/blob/bb56ca46ed6c07db0146dbdc61c672ff25f127de/rest_framework/response.py#L65-L69) is setting the response `Content-Type` to the value of `response.accepted_media_type`. This only came to light because I'm running nginx in front of django, and it was not recognizing the content-type (as `application/json` is different from `application/json;q=0.9`). As far as I can tell, this is actually an invalid Content-Type (https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17). ## Steps to reproduce curl --verbose http://example.com/api/model?format=json --H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,_/_;q=0.8' > /dev/null ## Expected behavior `Content-Type: application/json; charset=utf-8` ## Actual behavior `Content-Type: application/json;q=0.9; charset=utf-8`
Closing this as I couldn't replicate the described behavior... ``` $ curl --verbose http://restframework.herokuapp.com/?format=json -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8' ``` --> 406 {"detail":"Could not satisfy the request Accept header."} Or this, without the `format=json`... ``` $ curl --verbose http://restframework.herokuapp.com/ -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8' HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 ... ``` More than happy to reopen this if you can demo an example against `http://restframework.herokuapp.com/` that I can replicate, _or_ if you can demo that the behavior has changed, and that the latest version of REST framework running the tutorial _does_ demonstrate the issue, _or_ if you can provide an example pull request that demonstrates that we do have an issue. They are different. In [`master`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/negotiation.py#L72), the return value is the `full_media_type` (e.g. includes `q` and `indent`). In [`3.1`](https://github.com/tomchristie/django-rest-framework/blob/3.1.0/rest_framework/negotiation.py#L63), the return value is `renderer.media_type`, which does not include the extra parameters passed in by the `Accept` header. Thanks for confirming.
2016-07-11T10:55:05
encode/django-rest-framework
4,256
encode__django-rest-framework-4256
[ "4255" ]
7bfa5a9141f73a9e8d701d927d7ce6e5a07d555e
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 @@ -28,8 +28,6 @@ def default(self, obj): return force_text(obj) elif isinstance(obj, datetime.datetime): representation = obj.isoformat() - if obj.microsecond: - representation = representation[:23] + representation[26:] if representation.endswith('+00:00'): representation = representation[:-6] + 'Z' return representation
Two slightly different iso 8601 datetime 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 datetime 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#L1094 microseconds are included in the serialized value In https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/encoders.py#L30 only milliseconds are ## Expected behavior I would expect a consistent implementation. ## Actual behavior N/A
2016-07-11T12:51:10
encode/django-rest-framework
4,260
encode__django-rest-framework-4260
[ "3328" ]
06751f85487e0f753ce59e4773e38c622782463a
diff --git a/rest_framework/utils/urls.py b/rest_framework/utils/urls.py --- a/rest_framework/utils/urls.py +++ b/rest_framework/utils/urls.py @@ -7,7 +7,7 @@ def replace_query_param(url, key, val): parameters of the URL, and return the new URL. """ (scheme, netloc, path, query, fragment) = urlparse.urlsplit(url) - query_dict = urlparse.parse_qs(query) + query_dict = urlparse.parse_qs(query, keep_blank_values=True) query_dict[key] = [val] query = urlparse.urlencode(sorted(list(query_dict.items())), doseq=True) return urlparse.urlunsplit((scheme, netloc, path, query, fragment)) @@ -19,7 +19,7 @@ def remove_query_param(url, key): parameters of the URL, and return the new URL. """ (scheme, netloc, path, query, fragment) = urlparse.urlsplit(url) - query_dict = urlparse.parse_qs(query) + query_dict = urlparse.parse_qs(query, keep_blank_values=True) query_dict.pop(key, None) query = urlparse.urlencode(sorted(list(query_dict.items())), doseq=True) return urlparse.urlunsplit((scheme, netloc, path, query, fragment))
diff --git a/tests/test_pagination.py b/tests/test_pagination.py --- a/tests/test_pagination.py +++ b/tests/test_pagination.py @@ -108,6 +108,17 @@ def test_additional_query_params_are_preserved(self): 'count': 50 } + def test_empty_query_params_are_preserved(self): + request = factory.get('/', {'page': 2, 'filter': ''}) + response = self.view(request) + assert response.status_code == status.HTTP_200_OK + assert response.data == { + 'results': [12, 14, 16, 18, 20], + 'previous': 'http://testserver/?filter=', + 'next': 'http://testserver/?filter=&page=3', + 'count': 50 + } + def test_404_not_found_for_zero_page(self): request = factory.get('/', {'page': '0'}) response = self.view(request)
Cursor Pagination doesn't play well with query parameters The url in next doesn't include the query parameters used in a request, causing 400 bad request responses when using cursor pagination.
Please try to be more specific when raising an issue. Causing a 400 bad request how exactly? What's the smallest possible replicable example? Fair enough. I'll put some code up tomorrow or the day after. In the meantime, the most basic example, without code, would be this: There is a model Person with a CharField name. There is a a view that is subclassed off of generics.ListAPIView. This view's get_queryset method is overridden to return people whose name contains a search by a user encoded in a parameter q passed in a get request (i.e. `Person.objects.all().filter(Q(name__icontains=self.request.query_params['q']))`). This view is wired up to a url and instantiated with as_view(). Unfortunately, if Cursor Pagination is active (or others, possibly, I have not tested), then the next link will not include the query parameter q. It will only include a parameter for the cursor. This will result in a "400: Bad Request" because there is no query parameter for the search. I don't know if this is a known issue or not. I've already worked around it on my end. If none of the above is clear, no worries, I'll drop some code to clarify ASAP. Thank you for your work on a truly fantastic product! I have subclassed, used, and read the code repeatedly this past year, for a variety of products. It truly is a life-saver. Thanks! That should be enough to get started with. I still don't quite see where/why that'd result in a 400 (I'd expect a KeyError to be raised by your `get_queryset()` method, instead) but either way the upshot is that CursorPagination should preserve any other query parameters present in the request.
2016-07-13T17:04:02
encode/django-rest-framework
4,273
encode__django-rest-framework-4273
[ "4272" ]
91aad9299b8ac58a54515d3f1a1df89255fb6cee
diff --git a/rest_framework/compat.py b/rest_framework/compat.py --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -125,7 +125,7 @@ def get_related_model(field): def value_from_object(field, obj): if django.VERSION < (1, 9): return field._get_val_from_obj(obj) - field.value_from_object(obj) + return field.value_from_object(obj) # contrib.postgres only supported from 1.8 onwards.
Serializing "complex" field returns None instead of the value since 3.4 (Not a great title — I hope the description will clarify.) ## Steps to reproduce First: `pip install django-phonenumber-field` With the following model and serializer: ``` python from django.db.models import Model from phonenumber_field.modelfields import PhoneNumberField from rest_framework.serializers import ModelSerializer class PhoneModel(Model): number = PhoneNumberField() class PhoneSerializer(ModelSerializer): class Meta: model = PhoneModel fields = ['number'] ``` ## Expected behavior This test used to pass (until version 3.3.3): ``` python def test_phone_serializer(): phone = models.PhoneModel(number='+33610293847') data = models.PhoneSerializer(phone).data assert data['number'] == '+33610293847' ``` ## Actual behavior The test fails (since version 3.4) with: ``` def test_phone_serializer(): phone = models.PhoneModel(number='+33610293847') data = models.PhoneSerializer(phone).data > assert data['number'] == '+33610293847' E assert None == '+33610293847' ``` ## Analysis I bisected this regression to 9c996d7d2aa4137c8ba29afa2253efec8d6db74f. As far as I can tell, DRF used to get the string representation of the field and no longer does. ``` (Pdb) phone.number PhoneNumber(country_code=33, national_number=610293847, extension=None, italian_leading_zero=None, number_of_leading_zeros=None, country_code_source=1, preferred_domestic_carrier_code='') (Pdb) str(phone.number) '+33610293847' ```
Actually you seem to be missing a `return` here: https://github.com/tomchristie/django-rest-framework/commit/9c996d7d2aa4137c8ba29afa2253efec8d6db74f#diff-ce493f71b3679e91b72126c168670399R128
2016-07-16T20:48:47